Jamalshahid commited on
Commit
f5aea1d
·
1 Parent(s): 7c8ab65

chatGPT integration

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from openai import OpenAI
3
+
4
+ st.title("ChatGPT-like clone")
5
+
6
+ # Set OpenAI API key from Streamlit secrets
7
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
8
+
9
+ # Set a default model
10
+ if "openai_model" not in st.session_state:
11
+ st.session_state["openai_model"] = "gpt-3.5-turbo"
12
+
13
+ # Initialize chat history
14
+ if "messages" not in st.session_state:
15
+ st.session_state.messages = []
16
+
17
+ # Display chat messages from history on app rerun
18
+ for message in st.session_state.messages:
19
+ with st.chat_message(message["role"]):
20
+ st.markdown(message["content"])
21
+
22
+ # Accept user input
23
+ if prompt := st.chat_input("What is up?"):
24
+ # Add user message to chat history
25
+ st.session_state.messages.append({"role": "user", "content": prompt})
26
+ # Display user message in chat message container
27
+ with st.chat_message("user"):
28
+ st.markdown(prompt)
29
+
30
+
31
+ # Display assistant response in chat message container
32
+ with st.chat_message("assistant"):
33
+ stream = client.chat.completions.create(
34
+ model=st.session_state["openai_model"],
35
+ messages=[
36
+ {"role": m["role"], "content": m["content"]}
37
+ for m in st.session_state.messages
38
+ ],
39
+ stream=True,
40
+ )
41
+ response = st.write_stream(stream)
42
+ st.session_state.messages.append({"role": "assistant", "content": response})