How to get streamlit to recognize my api key?

My issue is that I saved my api key for openai in the secrets section when you deploy steamlit apps.
Also, I saved it in a config.toml and secrests.toml in the .streamlit folder on my private GitHub. Neither is being recognized by my app. I am not sure what to try next to get it to recognize my api key.

  1. Are you running your app locally or is it deployed?
    This is deployed.

  2. If your app is deployed:
    This is my app.
    Here is a link to the source code.

  3. Share the link to your app’s public GitHub repository (including a [requirements file]
    I have my GitHub on Private. Here is the contents of the requirements file.

  4. Share the full text of the error message (not a screenshot).

2023-11-05 13:55:23.305 Uncaught app exception
Traceback (most recent call last):
  File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/", line 534, in _run_script
    exec(code, module.__dict__)
  File "/mount/src/maternalhealthapp/", line 81, in <module>
  File "/mount/src/maternalhealthapp/", line 74, in main
    answer = ask_openai_question(extracted_text, question, openai_api_key)
  File "/mount/src/maternalhealthapp/", line 44, in ask_openai_question
    response = openai.Completion.create(
  File "/home/adminuser/venv/lib/python3.9/site-packages/openai/api_resources/", line 25, in create
    return super().create(*args, **kwargs)
  File "/home/adminuser/venv/lib/python3.9/site-packages/openai/api_resources/abstract/", line 151, in create
    ) = cls.__prepare_create_request(
  File "/home/adminuser/venv/lib/python3.9/site-packages/openai/api_resources/abstract/", line 108, in __prepare_create_request
    requestor = api_requestor.APIRequestor(
  File "/home/adminuser/venv/lib/python3.9/site-packages/openai/", line 139, in __init__
    self.api_key = key or util.default_api_key()
  File "/home/adminuser/venv/lib/python3.9/site-packages/openai/", line 186, in default_api_key
    raise openai.error.AuthenticationError(
openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See for details.
  1. Share the Streamlit and Python versions.

Hi @ah9 :wave:

On line 92 you’re overwriting the API key with None.

Delete line 92:

openai_api_key = os.getenv("OPENAI_API_KEY")

Once you delete the above line, the provided key from line 12 will automatically get passed to the function call and you’ll stop seeing AuthenticationError.

Happy Streamlit-ing! :balloon:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.