the system is throwing the below error. I'm in a local machine.
INFO:werkzeug:127.0.0.1 - - [11/Mar/2025 02:42:06] "OPTIONS /api/generate HTTP/1.1" 200 - ERROR:root:Error calling Gemini API: 400 API key not valid. Please pass a valid API key. [reason: "API_KEY_INVALID" domain: "googleapis.com" metadata { key: "service" value: "generativelanguage.googleapis.com" } , locale: "en-US" message: "API key not valid. Please pass a valid API key." ] INFO:werkzeug:127.0.0.1 - - [11/Mar/2025 02:42:08] "POST /api/generate HTTP/1.1" 500 -
below is my python code. i also has a .env file with the API key. i can't seem to know where is the error. Please advise. thank you.
import os
import logging
from flask import Flask, request, jsonify
from flask_cors import CORS
from google.generativeai import configure, GenerativeModel
from dotenv import load_dotenv
app = Flask(__name__)
CORS(app)
# Load environment variables from .env file
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
# Get the API key from the environment
api_key = os.environ.get("GEMINI_API_KEY")
# Configure the Google GenerativeAI library with the API key
configure(api_key=api_key)
@app.route('/api/generate', methods=['POST'])
def generate():
data = request.json
if not data or 'input' not in data:
return jsonify({'error': 'Invalid input'}), 400
user_input = data['input']
try:
model = GenerativeModel('gemini-2.0-flash')
response = model.generate_content(user_input)
return jsonify({
"response": response.text
})
except Exception as e:
logging.error(f"Error calling Gemini API: {e}")
return jsonify({'error': 'Failed to generate response'}), 500
if __name__ == '__main__':
app.run(debug=True)
-
Well, have you tried logging the API key before you use it, and checked whether that matches what's in your file?Jon Skeet– Jon Skeet2025年03月10日 19:07:05 +00:00Commented Mar 10, 2025 at 19:07
-
Can advise how to log the API key?HyperGoku– HyperGoku2025年03月10日 19:19:21 +00:00Commented Mar 10, 2025 at 19:19
-
Well you already have code to log an error, so you presumably know how to log, and you've already got the API key in a variable... I'm not sure what you expect me to say that you don't already know...Jon Skeet– Jon Skeet2025年03月10日 19:53:13 +00:00Commented Mar 10, 2025 at 19:53
-
I've checked my logs, the key is according to my API key. Would it be something to do with the model that I use?HyperGoku– HyperGoku2025年03月11日 12:50:22 +00:00Commented Mar 11, 2025 at 12:50
-
That I don't know, I'm afraid. Have you tried using the API with a simple curl request as per ai.google.dev/gemini-api/docs/api-key#send-gemini-api-request?Jon Skeet– Jon Skeet2025年03月11日 12:57:06 +00:00Commented Mar 11, 2025 at 12:57