Skip to content

Forum in maintenance, we will back soon 🙂

Chatbot in Streamli...
 
Notifications
Clear all

Chatbot in Streamlit

3 Posts
2 Users
5 Reactions
26 Views
(@tyson-koska)
Posts: 3
Active Member Customer
Topic starter
 

Hi All,

Using the prompt supplied in the lesson "Build UI With ChatGPT", I tried to create Streamlit UI for the chatbot created during the course (which works fine the terminal), here is the code that was created (note I removed my api key):

# Import necessary libraries
importopenai
importstreamlitasst

# Set OpenAI API key
openai.api_key="sk-"

# Define the selected model and initial messages
selected_model="gpt-3.5-turbo"
messages= [{"role": "system", "content": "You are a helpful assistant."}]

# Function to continue the chat with the bot
defcontinue_chat(user_message):
# Append user message to the messages list
messages.append({"role": "user", "content": user_message})

# Call OpenAI API for chat completions
response=openai.chat.completions.create(
model=selected_model,
messages=messages,
    )

# Append the AI response to the messages list
messages.append({"role": "assistant", "content": response['choices'][0]['message']['content']})

# Return the AI response
returnresponse['choices'][0]['message']['content']

# Streamlit UI
defmain():
st.title("Chat with OpenAI Assistant")

# User input for chat
user_message=st.text_input("You:")
ifst.button("Send"):
ifuser_message.lower() =="quit":
# Display conversation recap when the user quits
st.text("Conversation Recap:")
st.json(messages)
else:
# Continue the chat and display AI response
ai_response=continue_chat(user_message)
st.text(f"AI: {ai_response}")

# Run the Streamlit app
if__name__=="__main__":
main()
 
-----------------------------------------------------------------------------------
 
The problem is that I continually get this following message when I try to use the chatbot:
 
TypeError: 'ChatCompletion' object is not subscriptable
Traceback:
 
File "C:\Users\tyson\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 534, in _run_script exec(code, module.__dict__)
 
File "C:\chatGPT Practice\st.py", line 48, in <module> main()
 
File "C:\chatGPT Practice\st.py", line 43, in main ai_response = continue_chat(user_message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\chatGPT Practice\st.py", line 24, in continue_chat messages.append({"role": "assistant", "content": response['choices'][0]['message']['content']}) ~~~~~~~~^^^^^^^^^^^
 
 
Any help would be appreciated!
Tyson
 
 
Posted : 11/10/2023 8:00 pm
(@husein)
Posts: 550
Member Moderator
 

Can you please share the source code on your repository on Github, it would be much easier to go through your code and help you.

 
Posted : 11/11/2023 8:06 am
(@tyson-koska)
Posts: 3
Active Member Customer
Topic starter
 

I've figured it out! But yes, next time will use github, thanks.

 
Posted : 11/11/2023 12:01 pm
Share:
[the_ad_group id="312"]