I recommend using a form. Also put your imports at the top.
import streamlit as st
from openai import OpenAI
# Developer's api key is in secrets file.
# dev_api_key = st.secrets['OPENAI_API_KEY']
# Ask the user's api key
with st.form('form'):
user_api_key = st.text_input('Enter OpenAI API token:', type='password')
submit = st.form_submit_button('Submit')
if submit:
if len(user_api_key) == 51 and user_api_key.startswith('sk-'):
client = OpenAI(api_key=user_api_key)
st.success('api key is successfully entered')
else:
st.error('Your api key is invalid.')
st.stop()
yeah but how ? can you give me the code please.
key is the other word i used in place of Api_key. i have tried different names too but still its the same.
it is giving this error
TypeError: __init__() got an unexpected keyword argument 'key'
this too isn’t working…
this is coming NameError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you’re on Streamlit Cloud, click on ‘Manage app’ in the lower right of your app).
Traceback:
File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 535, in _run_script
exec(code, module.__dict__)File "/mount/src/firstgpt/streamlit_app.py", line 37, in <module>
for response in client.chat.completions.create(model="gpt-3.5-turbo",
I cannot give you any code without understanding what you are trying to achieve. Where do you want to retrieve the OpenAI API key from? Streamlit secrets? User input? Something else?
In the repo, under your .streamlit folder you have secrets.toml. That is bad.
Delete or revoke that key in the openai page.
Delete that .streamlit folder.
Another option is to delete or revoke that key in the openai page. Then delete your current repo. Then create a new repo but exclude the .streamlit folder. Do not upload your `.streamlit’ folder with secrets.toml in github public repo or even private repo.
The code above alone will not work. It is because of “if submit:” When streamlit reruns the code from top to bottom, the client is no longer visible. To fix that just add:
client = OpenAI(api_key=user_api_key)
Full code with correction
# Ask the user's api key
with st.form('form'):
user_api_key = st.text_input('Enter OpenAI API token:', type='password')
submit = st.form_submit_button('Submit')
if submit:
if len(user_api_key) == 51 and user_api_key.startswith('sk-'):
client = OpenAI(api_key=user_api_key)
st.success('api key is successfully entered')
else:
st.error('Your api key is invalid.')
st.stop()
# Make the client visible to other codes below it.
client = OpenAI(api_key=user_api_key)
# Your other stuff
Fancy api key checking
import openai
from openai import OpenAI
import streamlit as st
# Ask the user's api key and check it.
with st.sidebar:
with st.form('form'):
user_api_key = st.text_input('Enter OpenAI API token:', type='password')
submit = st.form_submit_button('Submit')
if submit:
# Check the api key string.
if len(user_api_key) == 51 and user_api_key.startswith('sk-'):
# Check the api key authenticity.
try:
client = OpenAI(api_key=user_api_key)
response = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is new in openai in 3 words?"}
],
)
except openai.AuthenticationError as eer:
st.error(eer)
st.stop()
except Exception as uer:
st.error(f'Unexpected error: {uer}')
st.stop()
# Else if no exception is hit, the key is good.
else:
st.success('api key is authentic.')
else:
st.error('Your api key is invalid.')
st.stop()
client = OpenAI(api_key=user_api_key)
this is great everything except this has been resolved
Unexpected error: Error code: 429 - {‘error’: {‘message’: ‘You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.’, ‘type’: ‘insufficient_quota’, ‘param’: None, ‘code’: ‘insufficient_quota’}}
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.