I am trying to experiment with the Gemini API using Python in VSCode. Unfortunately, when running the boilerplate code in the IDE, I run into a KeyError. Below is the error I get.
Traceback (most recent call last):
File "REDACTED", line 7, in <module>
genai.configure(api_key=os.environ[my_API_key])
~~~~~~~~~~^^^^^^^^^^^^
File "<frozen os>", line 685, in __getitem__
KeyError: 'REDACTED'
Note that “my_API_key” is a variable that I set to my personal API key within the program, and “REDACTED” in the last line of the error is my API key.
In accordance with the recommendations outlined in Google AI Studio, I created an API key, and tested the API by running the cURL command provided on the page:
curl
-H 'Content-Type: application/json'
-d '{"contents":[{"parts":[{"text":"Explain how AI works"}]}]}'
-X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY'
When replacing “YOUR_API_KEY” with the personal API key I created, I was able to successfully receive the response to the given prompt in my Terminal.
However, in VSCode, this is not the case. Below is the boilerplate code that I copied from Google and pasted in the IDE.
import pathlib
import textwrap
import google.generativeai as genai
import os
my_API_key = 'REDACTED'
genai.configure(api_key=os.environ[my_API_key])
model = genai.GenerativeModel(name='gemini-pro')
response = model.generate_content('Prove the Pythagorean theorem')
print(response.text)
When running this program, I receive the error message provided above. I ran this code both in VSCode and a Jupyter notebook, and received the same error message. I would appreciate any advice directing me in the correct direction to resolving this basic issue, or any fixes that worked for similar issues in the past. Thank you!
mathtase is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.