Promotingai commited on
Commit
75dd0b0
·
verified ·
1 Parent(s): 9227a0b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -0
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import streamlit as st
3
+ import os # Import the os module
4
+
5
+ # Fetch the API key from an environment variable
6
+ openai_api_key = os.getenv("OPENAI_API_KEY")
7
+
8
+ st.title("💬 Chatbot")
9
+ st.caption("🚀 A streamlit chatbot powered by OpenAI LLM")
10
+ if "messages" not in st.session_state:
11
+ st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
12
+
13
+ for msg in st.session_state.messages:
14
+ st.chat_message(msg["role"]).write(msg["content"])
15
+
16
+ if prompt := st.chat_input():
17
+ if not openai_api_key:
18
+ st.error("No OpenAI API key found. Please set the OPENAI_API_KEY environment variable.")
19
+ st.stop()
20
+
21
+ client = OpenAI(api_key=openai_api_key)
22
+ st.session_state.messages.append({"role": "user", "content": prompt})
23
+ st.chat_message("user").write(prompt)
24
+ response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
25
+ msg = response.choices[0].message.content
26
+ st.session_state.messages.append({"role": "assistant", "content": msg})
27
+ st.chat_message("assistant").write(msg)
28
+
29
+ # Links and additional information in the sidebar
30
+ with st.sidebar:
31
+ "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
32
+ "[View the source code](https://github.com/streamlit/llm-examples/blob/main/Chatbot.py)"
33
+ "[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/streamlit/llm-examples?quickstart=1)"