Struggling With Setting OpenAI API Using Streamlit Secrets

Struggling to get my app to run on Streamlit Community Cloud

I have no issues running in Replit but when i try and load the Github repo into Streamlit community i run into issues with the API key.

Using Streamlit secrets ive added my API key

OPENAI_API_KEY = "I have my api key here"

I’m calling the API Key here

    openai_api_key = st.secrets["OPENAI_API_KEY"]

Im getting this error however

Did not find openai_api_key, please add an environment variable `OPENAI_API_KEY` which contains it, or pass  `openai_api_key` as a named parameter. (type=value_error)

[18:32:26] ❗️ We have encountered an unexpected problem. If this issue persists, please contact support

You have section [openai], use the following.

openai_api_key = st.secrets['openai']["OPENAI_API_KEY"]

Hey Ferdy,

Thanks for sharing some ideas.

I ran into the exact same error after adding in your suggestion.

What else would make sense to troubleshoot?

Have a look on secrets management.

You need to copy the contents of your secret file into the advance settings box.

1 Like

Hi @Leghair, this is how I did it.

In my code, I reference the API key like below.

Import OS
os.environ["OPENAI_API_KEY"] = st.secrets["OPENAI_API_KEY"]

Then when you deploy the app, add the OpenAI key in the Advanced Setting.
Make sure the key name “OPENAI_API_KEY” in the setting matches what you use in the code.