pythonpython-3.xgoogle-gemini

Google Gemini API KeyError with valid key in Python


I am currently trying to write a program that takes data from a NASA Astronomy Picture of the Day API, and then presents the data to the user in a simple webpage. The API returns data in JSON format, which I converted to simple strings of text in python. Since this string is very long, I am trying to use Google's Gemini AI API to take the text as input and provide a summary. However, whenever I use my API key, it simply returns a KeyError, citing lines from os.py (not my program). I can access my API using the Google AI Studio website, where it says a couple of requests were received. Any help would be appreciated!

Below is my code: (see lines 12-14 for configuration for API and last chunk of apod() function for problem code) (Replaced actual api key with API KEY for privacy)

# imports for functionality
import requests 
import google.generativeai as genai # ai compiler
import os
# requests module -->  allows us to send/recieve packets to/from APIs
# We use 3 APIs in this program; 2 NASA OpenAPIs, and a Google AI api SDK .
# We extract information from the first 2 apis, and summarize using the Google API,
# which is then presented to the user in a simple webpage.

# NASA API config
key = personal dev key # --> NASA API key

# Google API config --> migrate to openai after developing ai key
genai.configure(api_key=os.environ["API KEY"]) # --> Google ai API
model = genai.GenerativeModel("gemini-1.5-flash") # --> generates stable model


# API ref dict
apis = {
    "apod" : "https://api.nasa.gov/planetary/apod?api_key="+ key 


}

# check for API error codes
rcodes = {
    200 : "Success",
    301 : "Redirecting",
    400 : "Invalid request",
    401 : "Invalid login",
    403 : "Unauthorized page",
    404 : "Page not found",
    503 : "Server not ready"
}

# function for passing text thru google openai library: -> 


# Function blocks for parsing each API data
def apod(data):
    # This block appends apod data to data.txt
    f.write(i + ": \n")
    print(data['date']) # date
    f.write(str(data['url'] + "\n")) # url 
    
    imgexp = str(data['explanation']) # vaiable to store explanation
    f.write(imgexp) # <-- writes explanation to data.txt
 

    airesp = model.generate_content("Summarize the following text, prioritizing scientfic information, while keeping it simple enough for someone not the field to understand: " + imgexp)
    print(airesp)
    
    



f = open("data.txt", "w") # Opens data file in write-over mode

for i in apis: # Runs through api list
    
    # GRABS DATA FROM API: I    
    response = requests.get(apis[i]) # returns status code
    respt = response.json() # Stores text values of api data as a dict
    
    # Delete this part after fully integrated -->
    print(i + "-" + rcodes[response.status_code]) # prints status code 
    print(respt['url']) 
    # Delete this part after fully integrated <--

    # block to determine parsing func
    if i == "apod":
        apod(respt) # <-- passes dict of api response thru parsing function
    else: pass
    

# Call this line last, to enable full data writing
f.close() # Closes file to prevent accidental writing

Running this code results in:

genai.configure(api_key=os.environ['API KEY']) # --> Google ai API
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'API KEY'

Solution

  • You should not include your API keys in code - keep them separate.

    One way (there are several) is to use a Python script from which you can import the required values. In my development environment I have apikeys.py where I store my keys.

    Using that approach, you could have a simpler implementation as follows:

    import google.generativeai as genai
    import requests
    from apikeys import NASA, GAPI
    from functools import cache
    
    AI = "Summarize the following text, prioritizing scientfic information, while keeping it simple enough for someone who is not an astronomer to understand: "
    APIS = [
        "https://api.nasa.gov/planetary/apod"
    ]
    MODEL = "gemini-1.5-flash"
    
    @cache
    def get_model():
        genai.configure(api_key=GAPI)
        return genai.GenerativeModel(MODEL)
    
    if __name__ == "__main__":
        with requests.Session() as session:
            for api in APIS:
                with session.get(api, params={"api_key": NASA}) as response:
                    response.raise_for_status()
                    if explanation := response.json().get("explanation"):
                        print(get_model().generate_content(AI + explanation).text)
                    else:
                        print("No explanation!")