API key works in direct request but fails inside my agent script (400 INVALID_ARGUMENT)

API key works in direct request but fails inside my agent script (400 INVALID_ARGUMENT)

400 INVALID_ARGUMENT
API key expired. Please renew the API key.

The strange part is that the key is clearly valid, and it works outside the script. This makes me think the problem is not the key itself, but something in the environment or the library that is causing the script to use an old or different key.

Here is the exact error returned by the agent:

API key expired. Please renew the API key.
status: INVALID_ARGUMENT
reason: API_KEY_INVALID

Could you please help me understand why the API key works in direct calls but fails only inside the script?
Is there any caching, deprecated variable name, or environment conflict that could cause this behavior?

Thanks!

Hi @Hamed_almohareb

Based on this description, it could be possible that the script is picking up a key via a local/global variable

could you check if you have another key set via local variable ?

You were correct.
The issue was caused by having two different API keys stored in my environment variables:

  • GEMINI_API_KEY → the correct and valid key

  • GOOGLE_API_KEY → an old/deprecated key that the script was picking up instead

The agent script was automatically using GOOGLE_API_KEY (which was invalid), even though my direct tests were using GEMINI_API_KEY.
After removing the old GOOGLE_API_KEY variable from both the user and system environment, the issue was fully resolved and the agent works normally again.

Thank you for pointing me in the right direction.