Mehrdad Atariani
Mehrdad Atariani

Reputation: 1

Error processing request: 400 Request contains an invalid argument in Flask

I am trying to use a fine-tuned Gemini model in the Flask app locally but getting this error after running the app: "Error processing request: 400 Request contains an invalid argument." the code:


# app.py
from flask import Flask, render_template, request, jsonify
from dotenv import load_dotenv
import os

import utils  # Import utility functions
import vertexai
from vertexai.generative_models import GenerativeModel

app = Flask(__name__)

load_dotenv()  # Load environment variables from .env file
print(f"GOOGLE_APPLICATION_CREDENTIALS: {os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')}")

# Load the model and environment variables
PROJECT_ID = os.getenv('PROJECT_ID')
LOCATION = os.getenv('LOCATION')
MODEL_NAME = os.getenv('MODEL_NAME')  # Load from .env

# Initialize Vertex AI
vertexai.init(project=PROJECT_ID, location=LOCATION)

# Load the fine-tuned model - adjust this part
model = GenerativeModel(MODEL_NAME)

UPLOAD_FOLDER = 'D:/University of Law/Courses/MSc CS Final Project/AI_Powered_Blueprint_Analyzer/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        try:
            analysis_name = request.form.get("analysis_name")
            blueprint_file = request.files.get("blueprint")
            additional_data = {
                "persona": request.files.get("persona"),
                "kpis": request.files.get("kpis"),
                "stakeholder_maps": request.files.get("stakeholder_maps"),
                "system_map": request.files.get("system_map"),
                "user_journey_map": request.files.get("user_journey_map"),
                "project_roadmap": request.files.get("project_roadmap"),
            }

        # validate required files 
            if not blueprint_file:
                return render_template("index.html", error="Blueprint file is required")

            prompt = utils.construct_prompt(analysis_name, blueprint_file, additional_data, app.config['UPLOAD_FOLDER'])
            print("Generated Prompt:", prompt)  # Debug print

            response = model.generate_content(
                contents=prompt,
                generation_config={
                    "max_output_tokens": 2048,
                    "temperature": 0.7,
                    "top_p": 0.8,
                }
            )
            
            if response and response.text:
                swot_analysis, improvements = utils.parse_gemini_response(response.text)
                return render_template("results.html", 
                                    analysis_name=analysis_name, 
                                    swot=swot_analysis, 
                                    improvements=improvements)
            else:
                return render_template("index.html", 
                                    error="No response generated from the model")

        except Exception as e:
            print(f"Full error details: {str(e)}")  # Debug print
            return render_template("index.html", 
                                error=f"Error processing request: {str(e)}")

    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)


# utils.py
import os
import re
from werkzeug.utils import secure_filename

def allowed_file(filename):
    allowed_extensions = {'png', 'jpg', 'jpeg', 'pdf', 'txt'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions

def construct_prompt(analysis_name, blueprint_file, additional_data, upload_folder):
    prompt = f"Analysis Name: {analysis_name}\n\n"

    def read_file_content(file):
        file_content = file.read()
        file.seek(0)  # Reset file pointer
        try:
            return file_content.decode('utf-8')
        except UnicodeDecodeError:
            return "[Binary file content not included in analysis]"

    if blueprint_file:
        filename = secure_filename(blueprint_file.filename)
        filepath = os.path.join(upload_folder, filename)
        blueprint_file.save(filepath)
        prompt += f"Blueprint File: {filename}\n"
        prompt += read_file_content(blueprint_file) + "\n\n"

    for data_type, file in additional_data.items():
        if file:
            filename = secure_filename(file.filename)
            filepath = os.path.join(upload_folder, filename)
            file.save(filepath)
            prompt += f"{data_type.capitalize()} Content:\n" # Process file content if needed
            prompt += read_file_content(file) + "\n\n"

    prompt += """
Please analyze the provided service blueprint and additional materials. Structure your response as follows:

SWOT Analysis:
- Strengths:
[List key strengths identified in the blueprint]
- Weaknesses:
[List key weaknesses identified in the blueprint]
- Opportunities:
[List key opportunities identified in the blueprint]
- Threats:
[List key threats identified in the blueprint]

Improvements:
1. [First improvement with detailed steps]
2. [Second improvement with detailed steps]
[Continue with numbered improvements as needed]

"""
    return prompt

def parse_gemini_response(response_text):
    #Improved parsing logic using regex
    swot_match = re.search(r"SWOT Analysis:\n(.*?)\nImprovements:", response_text, re.DOTALL)
    improvements_match = re.search(r"Improvements:\n(.*?)$", response_text, re.DOTALL)

    swot_analysis = swot_match.group(1).strip() if swot_match else "SWOT analysis not found."
    improvements = improvements_match.group(1).strip() if improvements_match else "Improvements not found."
    return swot_analysis, improvements

The dotenv file has PROJECT_ID, LOCATION (set in us), MODEL_NAME, and GOOGLE_APPLICATION_CREDENTIALS.

Thanks for your help in advance

Upvotes: 0

Views: 22

Answers (1)

Karl Weinmeister
Karl Weinmeister

Reputation: 507

From your question, it says that the location is set to us. That might be the issue, as Generative AI on Google Cloud models need a specific region, such as us-central. You can find the full list of regions here in the documentation.

You might also want to try the new Google Gen AI SDK, which supports both the the Gemini Developer API and Vertex AI APIs. It may provide a more detailed error message that will help you pinpoint the issue.

Upvotes: 1

Related Questions