app.py
Browse files
app.py
CHANGED
@@ -1,54 +1,62 @@
|
|
1 |
-
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
st.
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
#
|
27 |
-
|
28 |
-
st.
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
st.chat_message(
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from openai import OpenAI
|
3 |
+
|
4 |
+
st.set_page_config(page_title="Streamlit + OpenAI Assistant")
|
5 |
+
|
6 |
+
st.title("Basic Chatbot with Streamlit and OpenAI Assistant")
|
7 |
+
st.caption("Features text streaming using OpenAI Assistants API")
|
8 |
+
|
9 |
+
# Text input to enter OpenAI API key
|
10 |
+
with st.sidebar:
|
11 |
+
OPENAI_API_KEY = st.text_input("Enter your OpenAI API Key", type="password")
|
12 |
+
|
13 |
+
# Initialize OpenAI client
|
14 |
+
if OPENAI_API_KEY:
|
15 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
16 |
+
else:
|
17 |
+
st.error("Please enter your OpenAI API key to continue.")
|
18 |
+
st.stop()
|
19 |
+
|
20 |
+
ASSISTANT_ID = "asst_rd9h8PfYuOmHbkvOF3RTmVfn"
|
21 |
+
|
22 |
+
# Streamlit session state
|
23 |
+
if "messages" not in st.session_state:
|
24 |
+
st.session_state["messages"] = []
|
25 |
+
|
26 |
+
# Display all chat messages from session state
|
27 |
+
for message in st.session_state.messages:
|
28 |
+
st.chat_message(message["role"]).write(message["content"])
|
29 |
+
|
30 |
+
# User input
|
31 |
+
if prompt := st.chat_input():
|
32 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
33 |
+
st.chat_message("user").write(prompt)
|
34 |
+
|
35 |
+
# Send message to OpenAI Assistant
|
36 |
+
try:
|
37 |
+
thread = client.beta.threads.create()
|
38 |
+
thread_id = thread.id
|
39 |
+
client.beta.threads.messages.create(
|
40 |
+
thread_id=thread_id,
|
41 |
+
role="user",
|
42 |
+
content=prompt
|
43 |
+
)
|
44 |
+
|
45 |
+
run = client.beta.threads.runs.create(
|
46 |
+
thread_id=thread_id,
|
47 |
+
assistant_id=ASSISTANT_ID
|
48 |
+
)
|
49 |
+
|
50 |
+
while True:
|
51 |
+
run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
|
52 |
+
if run_status.status == "completed":
|
53 |
+
break
|
54 |
+
|
55 |
+
messages = client.beta.threads.messages.list(thread_id=thread_id)
|
56 |
+
assistant_message = messages.data[0].content[0].text.value
|
57 |
+
|
58 |
+
st.chat_message("assistant").write(assistant_message)
|
59 |
+
st.session_state.messages.append({"role": "assistant", "content": assistant_message})
|
60 |
+
|
61 |
+
except Exception as e:
|
62 |
+
st.error(f"Error: {str(e)}")
|