最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

google gemini throwing invalid api key error - Stack Overflow

programmeradmin4浏览0评论

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" metadata { key: "service" value: "generativelanguage.googleapis" } , 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)

发布评论

评论列表(0)

  1. 暂无评论