IAMTFRMZA commited on
Commit
ead511a
·
verified ·
1 Parent(s): 5ed07e1
Files changed (1) hide show
  1. app.py +62 -54
app.py CHANGED
@@ -1,54 +1,62 @@
1
- from langchain.callbacks.base import BaseCallbackHandler
2
- from langchain.schema import ChatMessage
3
- from langchain_openai import ChatOpenAI
4
- import streamlit as st
5
-
6
- st.set_page_config(page_title="Streamlit + Langchain")
7
-
8
- st.title("Basic Chatbot with Streamlit and Langchain")
9
- st.caption("Features text streaming")
10
-
11
-
12
- class StreamHandler(BaseCallbackHandler):
13
- def __init__(self, container, text=""):
14
- self.container = container
15
- self.text = text
16
-
17
- def on_llm_new_token(self, token: str, **kwargs) -> None:
18
- self.text += token
19
- self.container.markdown(self.text)
20
-
21
-
22
- # Text input to enter OpenAI API key
23
- with st.sidebar:
24
- OPENAI_API_KEY = st.text_input("Enter your OpenAI API Key", type="password")
25
-
26
- # Streamlit session state
27
- if "messages" not in st.session_state:
28
- st.session_state["messages"] = [
29
- ChatMessage(role="assistant", content="How can I help you?")
30
- ]
31
- # Display all chat messages from session state
32
- for message in st.session_state.messages:
33
- st.chat_message(message.role).write(message.content)
34
- # If user submits a prompt in the text input, continue
35
- if prompt := st.chat_input():
36
- if not OPENAI_API_KEY:
37
- st.error("Please add your OpenAI API key to continue.")
38
- st.stop()
39
- # Add user's prompt to the chat messages
40
- st.session_state.messages.append(ChatMessage(role="user", content=prompt))
41
- st.chat_message("user").write(prompt)
42
- # Display the assistant's response with langchain query
43
- with st.chat_message("assistant"):
44
- stream_handler = StreamHandler(st.empty())
45
- llm = ChatOpenAI(
46
- model="gpt-4o-mini",
47
- openai_api_key=OPENAI_API_KEY,
48
- streaming=True,
49
- callbacks=[stream_handler],
50
- )
51
- response = llm.invoke(st.session_state.messages)
52
- st.session_state.messages.append(
53
- ChatMessage(role="assistant", content=response.content)
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)}")