Hi @amritg,
Thanks for sharing this question! One question for you, are you asking about secrets management for a deployed app on Streamlit Community Cloud?
If yes, then we do have a very detailed blog + docs on how to accomplish this. It’s good practice to make sure your keys are secure.
There are several ways to do this and this is one of them:
Here’s an implementation by one of our community members: Struggling With Setting OpenAI API Using Streamlit Secrets - #5 by nhtkid
You can also load the OpenAI API key from secrets.toml directly:
Example on how to save you API key in the secrets file under .streamlit/secrets.toml
OPENAI_API_KEY="sk-proj-xxxxxxxxxxxxxxxxxxx"
Example script that shows how to read in the API key:
import streamlit as st
from openai import OpenAI
# Access the OpenAI API key from the secrets
api_key = st.secrets["OPENAI_API_KEY"]
# Set up the OpenAI API client
client = OpenAI(api_key=api_key)
def generate_completion(prompt):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are an helpful assistant\n"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
}
]
},
],
max_tokens=100
)
return response.choices[0].message.content
# A simple Streamlit UI
st.title("OpenAI GPT-3.5 Turbo Demo")
prompt = st.text_input("Enter a prompt:")
if st.button("Generate"):
if prompt:
completion = generate_completion(prompt)
st.markdown(completion)
else:
st.write("Please enter a prompt.")
When you’re ready to deploy the app, follow this detailed guide (with images) on how to add the keys to a deployed app.