Spaces:
Runtime error
Runtime error
ogegadavis254
commited on
Commit
•
61ef3bc
1
Parent(s):
2398106
Update app.py
Browse files
app.py
CHANGED
@@ -1,70 +1,10 @@
|
|
1 |
-
""" Simple Chatbot
|
2 |
-
@author: Nigel Gebodh
|
3 |
-
@email: nigel.gebodh@gmail.com
|
4 |
-
|
5 |
-
"""
|
6 |
-
|
7 |
import streamlit as st
|
8 |
-
|
|
|
9 |
import os
|
10 |
-
import
|
11 |
-
from dotenv import load_dotenv, dotenv_values
|
12 |
-
load_dotenv()
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
# initialize the client
|
19 |
-
client = OpenAI(
|
20 |
-
base_url="https://api-inference.huggingface.co/v1",
|
21 |
-
api_key=os.environ.get('HUGGINGFACEHUB_API_TOKEN')#"hf_xxx" # Replace with your token
|
22 |
-
)
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
|
27 |
-
|
28 |
-
model_links ={
|
29 |
-
"Mistral":"mistralai/Mistral-7B-Instruct-v0.2",
|
30 |
-
"Gemma-7B":"google/gemma-7b-it",
|
31 |
-
"Gemma-2B":"google/gemma-2b-it",
|
32 |
-
"Zephyr-7B-β":"HuggingFaceH4/zephyr-7b-beta",
|
33 |
-
|
34 |
-
}
|
35 |
-
|
36 |
-
#Pull info about the model to display
|
37 |
-
model_info ={
|
38 |
-
"Mistral":
|
39 |
-
{'description':"""The Mistral model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
|
40 |
-
\nIt was created by the [**Mistral AI**](https://mistral.ai/news/announcing-mistral-7b/) team as has over **7 billion parameters.** \n""",
|
41 |
-
'logo':'https://mistral.ai/images/logo_hubc88c4ece131b91c7cb753f40e9e1cc5_2589_256x0_resize_q97_h2_lanczos_3.webp'},
|
42 |
-
"Gemma-7B":
|
43 |
-
{'description':"""The Gemma model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
|
44 |
-
\nIt was created by the [**Google's AI Team**](https://blog.google/technology/developers/gemma-open-models/) team as has over **7 billion parameters.** \n""",
|
45 |
-
'logo':'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'},
|
46 |
-
"Gemma-2B":
|
47 |
-
{'description':"""The Gemma model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
|
48 |
-
\nIt was created by the [**Google's AI Team**](https://blog.google/technology/developers/gemma-open-models/) team as has over **2 billion parameters.** \n""",
|
49 |
-
'logo':'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'},
|
50 |
-
"Zephyr-7B":
|
51 |
-
{'description':"""The Zephyr model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
|
52 |
-
\nFrom Huggingface: \n\
|
53 |
-
Zephyr is a series of language models that are trained to act as helpful assistants. \
|
54 |
-
[Zephyr 7B Gemma](https://huggingface.co/HuggingFaceH4/zephyr-7b-gemma-v0.1)\
|
55 |
-
is the third model in the series, and is a fine-tuned version of google/gemma-7b \
|
56 |
-
that was trained on on a mix of publicly available, synthetic datasets using Direct Preference Optimization (DPO)\n""",
|
57 |
-
'logo':'https://huggingface.co/HuggingFaceH4/zephyr-7b-gemma-v0.1/resolve/main/thumbnail.png'},
|
58 |
-
"Zephyr-7B-β":
|
59 |
-
{'description':"""The Zephyr model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
|
60 |
-
\nFrom Huggingface: \n\
|
61 |
-
Zephyr is a series of language models that are trained to act as helpful assistants. \
|
62 |
-
[Zephyr-7B-β](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta)\
|
63 |
-
is the second model in the series, and is a fine-tuned version of mistralai/Mistral-7B-v0.1 \
|
64 |
-
that was trained on on a mix of publicly available, synthetic datasets using Direct Preference Optimization (DPO)\n""",
|
65 |
-
'logo':'https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha/resolve/main/thumbnail.png'},
|
66 |
-
|
67 |
-
}
|
68 |
|
69 |
def reset_conversation():
|
70 |
'''
|
@@ -73,25 +13,112 @@ def reset_conversation():
|
|
73 |
st.session_state.conversation = []
|
74 |
st.session_state.messages = []
|
75 |
return None
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
# Define the available models
|
81 |
-
models =[key for key in model_links.keys()]
|
82 |
-
|
83 |
-
# Create the sidebar with the dropdown for model selection
|
84 |
-
selected_model = st.sidebar.selectbox("Select Model", models)
|
85 |
|
86 |
-
#
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
st.sidebar.write(f"You're now chatting with **{selected_model}**")
|
96 |
st.sidebar.markdown(model_info[selected_model]['description'])
|
97 |
st.sidebar.image(model_info[selected_model]['logo'])
|
@@ -99,65 +126,33 @@ st.sidebar.markdown("*Generated content may be inaccurate or false.*")
|
|
99 |
st.sidebar.markdown("\nLearn how to build this chatbot [here](https://ngebodh.github.io/projects/2024-03-05/).")
|
100 |
st.sidebar.markdown("\nRun into issues? Try the [back-up](https://huggingface.co/spaces/ngebodh/SimpleChatbot-Backup).")
|
101 |
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
if "prev_option" not in st.session_state:
|
106 |
-
st.session_state.prev_option = selected_model
|
107 |
-
|
108 |
-
if st.session_state.prev_option != selected_model:
|
109 |
-
st.session_state.messages = []
|
110 |
-
# st.write(f"Changed to {selected_model}")
|
111 |
-
st.session_state.prev_option = selected_model
|
112 |
-
reset_conversation()
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
#Pull in the model we want to use
|
117 |
-
repo_id = model_links[selected_model]
|
118 |
-
|
119 |
-
|
120 |
-
st.subheader(f'AI - {selected_model}')
|
121 |
-
# st.title(f'ChatBot Using {selected_model}')
|
122 |
-
|
123 |
-
# Set a default model
|
124 |
-
if selected_model not in st.session_state:
|
125 |
-
st.session_state[selected_model] = model_links[selected_model]
|
126 |
-
|
127 |
# Initialize chat history
|
128 |
if "messages" not in st.session_state:
|
129 |
st.session_state.messages = []
|
130 |
|
131 |
-
|
132 |
# Display chat messages from history on app rerun
|
133 |
for message in st.session_state.messages:
|
134 |
with st.chat_message(message["role"]):
|
135 |
st.markdown(message["content"])
|
136 |
|
137 |
-
|
138 |
-
|
139 |
# Accept user input
|
140 |
-
if prompt := st.chat_input(f"Hi I'm {selected_model}, ask me a question"):
|
141 |
-
|
142 |
# Display user message in chat message container
|
143 |
with st.chat_message("user"):
|
144 |
st.markdown(prompt)
|
145 |
# Add user message to chat history
|
146 |
-
st.session_state.messages.append(
|
147 |
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
# Display assistant response in chat message container
|
150 |
with st.chat_message("assistant"):
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
],
|
157 |
-
temperature=temp_values,#0.5,
|
158 |
-
stream=True,
|
159 |
-
max_tokens=3000,
|
160 |
-
)
|
161 |
-
|
162 |
-
response = st.write_stream(stream)
|
163 |
-
st.session_state.messages.append({"role": "assistant", "content": response})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
import requests
|
3 |
+
import json
|
4 |
import os
|
5 |
+
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
load_dotenv()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
def reset_conversation():
|
10 |
'''
|
|
|
13 |
st.session_state.conversation = []
|
14 |
st.session_state.messages = []
|
15 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
+
# Define model links for Hugging Face models
|
18 |
+
model_links = {
|
19 |
+
"Mistral": "mistralai/Mistral-7B-Instruct-v0.2",
|
20 |
+
"Gemma-7B": "google/gemma-7b-it",
|
21 |
+
"Gemma-2B": "google/gemma-2b-it",
|
22 |
+
"Zephyr-7B-β": "HuggingFaceH4/zephyr-7b-beta",
|
23 |
+
"Nous-Hermes-2-Yi-34B": "NousResearch/Nous-Hermes-2-Yi-34B"
|
24 |
+
}
|
25 |
|
26 |
+
# Define model info for all models
|
27 |
+
model_info = {
|
28 |
+
"Mistral": {
|
29 |
+
'description': "The Mistral model is a Large Language Model (LLM) developed by Mistral AI.",
|
30 |
+
'logo': 'https://mistral.ai/images/logo_hubc88c4ece131b91c7cb753f40e9e1cc5_2589_256x0_resize_q97_h2_lanczos_3.webp'
|
31 |
+
},
|
32 |
+
"Gemma-7B": {
|
33 |
+
'description': "The Gemma-7B model is a Large Language Model (LLM) developed by Google with 7 billion parameters.",
|
34 |
+
'logo': 'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'
|
35 |
+
},
|
36 |
+
"Gemma-2B": {
|
37 |
+
'description': "The Gemma-2B model is a Large Language Model (LLM) developed by Google with 2 billion parameters.",
|
38 |
+
'logo': 'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'
|
39 |
+
},
|
40 |
+
"Zephyr-7B-β": {
|
41 |
+
'description': "The Zephyr-7B-β model is a Large Language Model (LLM) developed by HuggingFace.",
|
42 |
+
'logo': 'https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha/resolve/main/thumbnail.png'
|
43 |
+
},
|
44 |
+
"Nous-Hermes-2-Yi-34B": {
|
45 |
+
'description': "The Nous Hermes model is a Large Language Model (LLM) developed by Nous Research with 34 billion parameters.",
|
46 |
+
'logo': 'https://example.com/nous_hermes_logo.png'
|
47 |
+
}
|
48 |
+
}
|
49 |
|
50 |
+
# Function to interact with Hugging Face models
|
51 |
+
def interact_with_huggingface_model(messages, model):
|
52 |
+
# Add your code here to interact with the Hugging Face model
|
53 |
+
pass
|
54 |
+
|
55 |
+
# Function to interact with the Together API model
|
56 |
+
def interact_with_together_api(messages):
|
57 |
+
all_messages = []
|
58 |
+
|
59 |
+
if not messages: # If history is empty
|
60 |
+
all_messages.append({"role": "user", "content": ""})
|
61 |
+
history = [("", "")] # Add dummy values to prevent unpacking error
|
62 |
+
|
63 |
+
for human, assistant in messages:
|
64 |
+
all_messages.append({"role": "user", "content": human})
|
65 |
+
all_messages.append({"role": "assistant", "content": assistant})
|
66 |
+
|
67 |
+
all_messages.append({"role": "user", "content": messages[-1][1]})
|
68 |
+
|
69 |
+
url = "https://api.together.xyz/v1/chat/completions"
|
70 |
+
payload = {
|
71 |
+
"model": "NousResearch/Nous-Hermes-2-Yi-34B",
|
72 |
+
"temperature": 1.05,
|
73 |
+
"top_p": 0.9,
|
74 |
+
"top_k": 50,
|
75 |
+
"repetition_penalty": 1,
|
76 |
+
"n": 1,
|
77 |
+
"messages": all_messages,
|
78 |
+
"stream_tokens": True,
|
79 |
+
}
|
80 |
+
|
81 |
+
TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
|
82 |
+
headers = {
|
83 |
+
"accept": "application/json",
|
84 |
+
"content-type": "application/json",
|
85 |
+
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
86 |
+
}
|
87 |
+
|
88 |
+
response = requests.post(url, json=payload, headers=headers, stream=True)
|
89 |
+
response.raise_for_status() # Ensure HTTP request was successful
|
90 |
+
|
91 |
+
for line in response.iter_lines():
|
92 |
+
if line:
|
93 |
+
decoded_line = line.decode('utf-8')
|
94 |
+
|
95 |
+
# Check for the completion signal
|
96 |
+
if decoded_line == "data: [DONE]":
|
97 |
+
yield entire_assistant_response # Yield the entire response at the end
|
98 |
+
break
|
99 |
+
|
100 |
+
try:
|
101 |
+
# Decode and strip any SSE format specific prefix ("data: ")
|
102 |
+
if decoded_line.startswith("data: "):
|
103 |
+
decoded_line = decoded_line.replace("data: ", "")
|
104 |
+
chunk_data = json.loads(decoded_line)
|
105 |
+
content = chunk_data['choices'][0]['delta']['content']
|
106 |
+
entire_assistant_response += content # Aggregate content
|
107 |
+
yield entire_assistant_response
|
108 |
+
|
109 |
+
except json.JSONDecodeError:
|
110 |
+
print(f"Invalid JSON received: {decoded_line}")
|
111 |
+
continue
|
112 |
+
except KeyError as e:
|
113 |
+
print(f"KeyError encountered: {e}")
|
114 |
+
continue
|
115 |
+
|
116 |
+
# Create sidebar with model selection dropdown and temperature slider
|
117 |
+
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
|
118 |
+
temperature = st.sidebar.slider('Select Temperature', 0.0, 1.0, 0.5)
|
119 |
+
st.sidebar.button('Reset Chat', on_click=reset_conversation)
|
120 |
+
|
121 |
+
# Display model description and logo
|
122 |
st.sidebar.write(f"You're now chatting with **{selected_model}**")
|
123 |
st.sidebar.markdown(model_info[selected_model]['description'])
|
124 |
st.sidebar.image(model_info[selected_model]['logo'])
|
|
|
126 |
st.sidebar.markdown("\nLearn how to build this chatbot [here](https://ngebodh.github.io/projects/2024-03-05/).")
|
127 |
st.sidebar.markdown("\nRun into issues? Try the [back-up](https://huggingface.co/spaces/ngebodh/SimpleChatbot-Backup).")
|
128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
# Initialize chat history
|
130 |
if "messages" not in st.session_state:
|
131 |
st.session_state.messages = []
|
132 |
|
|
|
133 |
# Display chat messages from history on app rerun
|
134 |
for message in st.session_state.messages:
|
135 |
with st.chat_message(message["role"]):
|
136 |
st.markdown(message["content"])
|
137 |
|
|
|
|
|
138 |
# Accept user input
|
139 |
+
if prompt := st.chat_input(f"Hi, I'm {selected_model}, ask me a question"):
|
|
|
140 |
# Display user message in chat message container
|
141 |
with st.chat_message("user"):
|
142 |
st.markdown(prompt)
|
143 |
# Add user message to chat history
|
144 |
+
st.session_state.messages.append(("user", prompt))
|
145 |
|
146 |
+
# Interact with selected model
|
147 |
+
if selected_model == "Nous-Hermes-2-Yi-34B":
|
148 |
+
stream = interact_with_together_api(st.session_state.messages)
|
149 |
+
else:
|
150 |
+
interact_with_huggingface_model(st.session_state.messages, model_links[selected_model])
|
151 |
|
152 |
# Display assistant response in chat message container
|
153 |
with st.chat_message("assistant"):
|
154 |
+
response = ""
|
155 |
+
for chunk in stream:
|
156 |
+
response = chunk
|
157 |
+
st.markdown(response)
|
158 |
+
st.session_state.messages.append(("assistant", response))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|