Spaces:
Sleeping
Sleeping
Lauredecaudin
commited on
Commit
•
9f528f8
1
Parent(s):
0104cf8
Update pages/1-Using Chat GPT (beginner).py
Browse files
pages/1-Using Chat GPT (beginner).py
CHANGED
@@ -1,3 +1,31 @@
|
|
1 |
import streamlit as st
|
|
|
2 |
|
|
|
|
|
|
|
|
|
|
|
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from openai import OpenAI
|
3 |
|
4 |
+
with st.sidebar:
|
5 |
+
openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
|
6 |
+
"[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
|
7 |
+
"[View the source code](https://github.com/streamlit/llm-examples/blob/main/Chatbot.py)"
|
8 |
+
"[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/streamlit/llm-examples?quickstart=1)"
|
9 |
|
10 |
+
st.title("💬 Chatbot")
|
11 |
+
|
12 |
+
if "messages" not in st.session_state:
|
13 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
14 |
+
|
15 |
+
for msg in st.session_state.messages:
|
16 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
17 |
+
|
18 |
+
if prompt := st.chat_input():
|
19 |
+
if not openai_api_key:
|
20 |
+
st.info("Please add your OpenAI API key to continue.")
|
21 |
+
st.stop()
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
client = OpenAI(api_key=openai_api_key)
|
26 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
27 |
+
st.chat_message("user").write(prompt)
|
28 |
+
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
|
29 |
+
msg = response.choices[0].message.content
|
30 |
+
st.session_state.messages.append({"role": "assistant", "content": msg})
|
31 |
+
st.chat_message("assistant").write(msg)
|