I was so sure my Gemini API key was invalid.
I'm building a RAG chatbot with Flask, Weaviate, and Gemini. The main API for summarizing docs worked perfectly. The chatbot API? RuntimeError: Gemini model is not initialized.
I checked my .env file a dozen times. I generated new API keys. I put print() statements everywhere. The initialization code was definitely running and succeeding at startup! So why was my model None when the API route was called?
Turns out, it was a classic Flask circular dependency issue.
My app/init.py was doing this (the wrong way):
from .routes import main # <-- Imports routes at the top
def create_app():
app = Flask(name)
#...
init_gemini_model(app) # <-- Initializes the model
app.register_blueprint(main)
return app
The problem is that Python imports routes before create_app is ever called. So my RAG service was importing the GEMINI_MODEL when it was still None.
The one-line fix was to change the import structure (the right way):
def create_app():
app = Flask(name)
#...
init_gemini_model(app)
from . import routes # <-- Import INSIDE the function
app.register_blueprint(routes.main)
return app
By importing the routes after the client is initialized, the circular dependency is broken. The error vanished.
It's a huge reminder that sometimes the bug isn't in your fancy AI logic, but in the fundamentals of the framework you're using. Hope this saves someone else a few hours of head-scratching!
Top comments (0)