I’m encountering a NameError: name 'userdata' is not defined
when trying to use Google Colab’s userdata
module to securely store and retrieve my API key. I’m using it to fetch my API key for configuring the Generative AI client library in a Streamlit app. Here’s the relevant portion of my code:
# Used to securely store your API key
from google.colab import userdata
# Or use `os.getenv('GOOGLE_API_KEY')` to fetch an environment variable.
GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
This is my full code:
# Install required packages
!pip install streamlit ngrok
!pip install -q -U google-generativeai
# Import necessary libraries
from google.colab import userdata
import streamlit as st
import google.generativeai as genai
# Used to securely store your API key
GOOGLE_API_KEY = userdata.get('GOOGLE_API_KEY')
# Configure the Generative AI client library
genai.configure(api_key=GOOGLE_API_KEY)
# Write your Streamlit code to a file
code = """
import streamlit as st
import google.generativeai as genai
st.title("JARVIS")
# Select the model
model = genai.GenerativeModel('gemini-pro')
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = [
{
"role": "assistant",
"content": "Ask me Anything"
}
]
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Process and store Query and Response
def llm_function(query):
response = model.generate_content(query)
# Displaying the Assistant Message
with st.chat_message("assistant"):
st.markdown(response.text)
# Storing the User Message
st.session_state.messages.append(
{
"role": "user",
"content": query
}
)
# Storing the Assistant Message
st.session_state.messages.append(
{
"role": "assistant",
"content": response.text
}
)
# Accept user input
query = st.chat_input("What's up?")
# Calling the Function when Input is Provided
if query:
# Displaying the User Message
with st.chat_message("user"):
st.markdown(query)
llm_function(query)
"""
with open('app.py', 'w') as f:
f.write(code)
# Import required libraries
from pyngrok import ngrok
# Set ngrok authtoken
authtoken = "2gwvvKEWTmfybIwG9UNTMjLbwaS_peD9yUo2YNNYXN71ReEd"
ngrok.set_auth_token(authtoken)
# Get list of existing ngrok tunnels
existing_tunnels = ngrok.get_tunnels()
# Stop existing tunnels if any are running
if existing_tunnels:
print("Stopping existing ngrok tunnels...")
for tunnel in existing_tunnels:
ngrok.disconnect(tunnel.public_url)
print("Existing ngrok tunnels stopped.")
# Start a new ngrok tunnel
try:
# Connect a new ngrok tunnel
public_url = ngrok.connect(8501).public_url
print("New ngrok tunnel started. Public URL:", public_url)
except Exception as e:
print("Error starting ngrok tunnel:", e)
I’ve verified that I’m running my code in a Google Colab environment, so userdata
should be available. I have also put my key in Google Colab Secrets. However, I keep getting the mentioned NameError
. How can I resolve this issue and properly use userdata
to fetch my API key?
Any insights or suggestions would be greatly appreciated. Thank you!