forked from alexanderatallah/openrouter-streamlit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chatbot.py
51 lines (44 loc) · 1.74 KB
/
Chatbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import openai
import streamlit as st
from streamlit_chat import message
from components.Sidebar import sidebar
import json
from shared import constants
api_key, selected_model = sidebar(constants.OPENROUTER_DEFAULT_CHAT_MODEL)
st.title("💬 Streamlit GPT")
if "messages" not in st.session_state:
st.session_state["messages"] = [
{"role": "assistant", "content": "How can I help you?"}
]
# Display the initial message above the text entry
st.write("How can I help you?")
with st.form("chat_input", clear_on_submit=True):
a, b = st.columns([4, 1])
user_input = a.text_area(
label="Your message:",
placeholder="Start chatting here",
label_visibility="collapsed",
height=100 # This sets the height to approximately 3 lines
)
b.form_submit_button("Send", use_container_width=True)
for i, msg in enumerate(st.session_state.messages[1:], start=1): # Skip the first message
message(msg["content"], is_user=msg["role"] == "user", key=i)
if user_input and not api_key:
st.info("Please click Connect OpenRouter to continue.")
if user_input and api_key:
st.session_state.messages.append({"role": "user", "content": user_input})
message(user_input, is_user=True)
openai.api_key = api_key
openai.api_base = constants.OPENROUTER_API_BASE
response = openai.ChatCompletion.create(
model=selected_model,
messages=st.session_state.messages,
headers={"HTTP-Referer": constants.OPENROUTER_REFERRER},
)
# response is sometimes type str
# TODO replace this hack with a real fix
if type(response) == str:
response = json.loads(response)
msg = response["choices"][0]["message"]
st.session_state.messages.append(msg)
message(msg["content"])