Issue with Invalid API Key in CrewAI Agent for GEMINI API

I’m encountering an issue when using GEMINI through the CrewAI agent. Despite using a valid API key, I receive the following error:
Error during LLM call: litellm.AuthenticationError: geminiException - {
“error”: {
“code”: 400,
“message”: “API key not valid. Please pass a valid API key.”,
“status”: “INVALID_ARGUMENT”,

}

I have confirmed that my API key is valid and properly configured in CrewAI, but the “API_KEY_INVALID” error persists.

2 Likes

I have the same error, I don’t know how to fix this :sob:

1 Like

Same issue here.
Even if i am creating new key and using it its still showing the invalid key error.

I encountered this error and in my instance after a little digging through code, it was resolved by setting GEMINI_API_KEY with my API key value. I previously was trying to use GOOGLE_API_KEY.

Let me know if this helps or if you’re still stuck.

1 Like

Hi Team,

I’m also facing this error when trying to boostrap a little project from one single .py file. It works when creating the project using the crewai create though.

Here is the code in case it can help debug:

import warnings
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
import os
import litellm  

os.environ["LITELLM_MODEL"] = "gemini/gemini-1.5-flash"
os.environ["GEMINI_API_KEY"] = "my-actual-keys"

warnings.filterwarnings('ignore')

website_scraping_tool = ScrapeWebsiteTool(website_url='https://w3champions.com/player/{player_id}/statistics')
search_tool = SerperDevTool()

researcher = Agent(
    role="Player Statistics Researcher",
    goal="Find and extract the statistics of the following Warcraft III player: {player_id}",
    backstory="A dedicated researcher with years of experience in gaming and Warcraft III.",
    tools=[search_tool, website_scraping_tool]
)

data_analyst = Agent(
    role="Data Analyst specialized in Warcraft III",
    goal="Analyze {player_id}'s statistics and share useful and actionable insights about their play",
    backstory="A dedicated data analyst with years of experience in gaming and Warcraft III. You love finding insights on other players.",
)

research_task = Task(
    description="Find and extract the statistics of {player_id}. These stats are all stored on the following URL: https://w3champions.com/player/{player_id}/statistics. Use the tools you have to find and extract them.",
    expected_output="detailed report on a the player's statistics including: win rate vs. each race (orc, human, undead, elf, random), Hero usage & Hero win rate",
    agent=researcher
)

data_analysis_task = Task(
    description="Analyze {player_id}'s statistics and share useful insights for their opponent, who play the race {opponent_race}.",
    expected_output="Give 3 maps the opponent should not play against {player_id}, and which hero they are likely to play against them given their race.",
    agent=data_analyst
)

crew = Crew(
    agents=[researcher, data_analyst],
    tasks=[research_task, data_analysis_task],
    process=Process.sequential,
    default_llm={"model": "gemini/gemini-1.5-flash", "api_key": os.getenv("GEMINI_API_KEY"), "provider": "google"}
)

# player_id = str(input("What Player are you going to play against?"))
# opponent_race = str(input("what race do you play?"))

# results = crew.kickoff(inputs={"player_id": player_id, "opponent_race": opponent_race})
results = crew.kickoff(inputs={"player_id": "ThoMus%2321493", "opponent_race": "orc"})
print(results)

Hey @Thom_Web_Com,

I’m still getting to grips with CrewAI and building a linter to help myself and others. But a few observations:

  • I don’t believe there is a default_llm property on the Crew - available attributes are here: Crews - CrewAI or in code: crewAI/src/crewai/crew.py at main · crewAIInc/crewAI · GitHub
  • General: Do not ever put API keys in code, though you substituted it out here - always set them via .env. I cannot repeat this enough: Never ever secrets/API keys in code. This goes beyond CrewAI and into general software engineering practices to avoid potential pain in the future.
  • You can set the llm on the Agents or by setting environment variables.

Setting the LLM on the agents via code
If you wish to, check here: LLMs - CrewAI

Setting via environment variables
Put the following into your .env file:

MODEL=gemini/gemini-1.5-flash
GEMINI_API_KEY=your-actual-key

Source: crewAI/src/crewai/utilities/llm_utils.py at main · crewAIInc/crewAI · GitHub

Note that you could use OPENAI_MODEL_NAME in lieu of MODEL, but it would be somewhat misleading. Make sure OPENAI_MODEL_NAME environment variable is not set, as it will take precedence over MODEL.

Can I ask from where you got the default_llm property/attribute? I’m assuming an AI hallucination which is one of the reasons I’m building out a linter.

Hope this helps!

1 Like

@William @Thom_Web_Com @Nikhil_J Guys, just use the LLM class. CrewAI’s LLM class leverages LiteLLM in the background, which supports a wide range of LLM providers. Among these is Gemini via Google AI Studio, or Gemini via Vertex AI.

Here’s a code example:

from crewai import Agent, LLM

my_llm = LLM(
    api_key=os.getenv("GEMINI_API_KEY"),
    model="gemini/gemini-1.5-pro-latest",
)

my_agent = Agent(
    ...,
    llm=my_llm,
)
2 Likes

Hi Team,

@rokbenko & @Willian thanks a lot for your recommendations guys.

I tried again using the LLM class as suggested by both of you. I confirm it works.

I had to set the llm=my_llm property to each Agent, though. I only have 2 agents so it’s fine, it’d be easier with a general llm property in the crew class, though :smiley:

You were right @Willian, this attribute does not exist and comes from the CrewAI GPT Assistant suggestion (= hallucination)

Funnily enough, gemini-2.0-flash-exp throws this error while gemini-1.5-flash works perfectly:
Received None or empty response from LLM call.
An unknown error occurred. Please check the details below.

1 Like

I was configuring my .env file like this:
GEMINI_API_KEY=AIza
MODEL_NAME=gemini/gemini-1.5-flash

But it was showing an error. I aligned it the way you suggested, and it worked:
MODEL=gemini/gemini-1.5-flash
GEMINI_API_KEY=your-actual-key

I hope this rigidity will be improved in the future.
Thanks!

1 Like