yuanjunchai commited on
Commit
4438982
·
1 Parent(s): f0358bb

Add application file

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import the necessary libraries
2
+ import streamlit as st
3
+ from openai import OpenAI # TODO: Install the OpenAI library using pip install openai
4
+
5
+ st.title("Mini Project 2: Streamlit Chatbot")
6
+
7
+ # TODO: Replace with your actual OpenAI API key
8
+ openai_key = "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"
9
+ client = OpenAI(api_key=openai_key)
10
+
11
+ # Define a function to get the conversation history (Not required for Part-2, will be useful in Part-3)
12
+ def get_conversation() -> str:
13
+ # return: A formatted string representation of the conversation.
14
+ conversation = ""
15
+ for message in st.session_state.messages:
16
+ role = message["role"]
17
+ content = message["content"]
18
+ conversation += f"{role}: {content}\n"
19
+ return conversation
20
+
21
+ # Check for existing session state variables
22
+ if "openai_model" not in st.session_state:
23
+ st.session_state["openai_model"] = "gpt-3.5-turbo" # Initialize model
24
+
25
+ if "messages" not in st.session_state:
26
+ st.session_state.messages = [] # Initialize messages as an empty list
27
+
28
+ # Display existing chat messages
29
+ for message in st.session_state.messages:
30
+ with st.chat_message(message["role"]):
31
+ st.markdown(message["content"])
32
+
33
+ # Wait for user input
34
+ if prompt := st.chat_input("What would you like to chat about?"):
35
+ # Append user message to messages
36
+ st.session_state.messages.append({"role": "user", "content": prompt})
37
+
38
+ # Display user message
39
+ with st.chat_message("user"):
40
+ st.markdown(prompt)
41
+
42
+ # Generate AI response
43
+ with st.chat_message("assistant"):
44
+ # Send request to OpenAI API
45
+ response = client.chat.completions.create(
46
+ model=st.session_state["openai_model"],
47
+ messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages]
48
+ )
49
+ ai_response = response.choices[0].message.content
50
+
51
+ # Display AI response
52
+ st.markdown(ai_response)
53
+
54
+ # Append AI response to messages
55
+ st.session_state.messages.append({"role": "assistant", "content": ai_response})