add the first chatbot
Browse files- app.py +180 -0
- requirements.txt +12 -0
app.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
3 |
+
import streamlit as st
|
4 |
+
from langchain_core.prompts import PromptTemplate
|
5 |
+
from langchain_core.output_parsers import StrOutputParser
|
6 |
+
from os.path import join, dirname
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
|
9 |
+
# Load the environment variables
|
10 |
+
dotenv_path = join(dirname(__file__), ".env")
|
11 |
+
load_dotenv(dotenv_path)
|
12 |
+
|
13 |
+
|
14 |
+
list_model=["mistralai/Mistral-7B-Instruct-v0.3",
|
15 |
+
"allenai/Llama-3.1-Tulu-3-8B",
|
16 |
+
"Qwen/Qwen2.5-1.5B-Instruct"]
|
17 |
+
|
18 |
+
def get_llm_hf_inference(model_id="mistralai/Mistral-7B-Instruct-v0.3", max_new_tokens=128, temperature=0.1):
|
19 |
+
"""
|
20 |
+
Returns a language model for HuggingFace inference.
|
21 |
+
|
22 |
+
Parameters:
|
23 |
+
- model_id (str): The ID of the HuggingFace model repository.
|
24 |
+
- max_new_tokens (int): The maximum number of new tokens to generate.
|
25 |
+
- temperature (float): The temperature for sampling from the model.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
- llm (HuggingFaceEndpoint): The language model for HuggingFace inference.
|
29 |
+
"""
|
30 |
+
llm = HuggingFaceEndpoint(
|
31 |
+
repo_id=model_id,
|
32 |
+
max_new_tokens=max_new_tokens,
|
33 |
+
temperature=temperature,
|
34 |
+
token = os.environ["HF_TOKEN"]
|
35 |
+
)
|
36 |
+
return llm
|
37 |
+
|
38 |
+
# Configure the Streamlit app
|
39 |
+
st.set_page_config(page_title="Chatbot HF", page_icon="π€")
|
40 |
+
st.title("Personal ChatBot")
|
41 |
+
st.markdown(f"*This is a simple chatbot to generate responses to your text input.*")
|
42 |
+
|
43 |
+
# Initialize session state for avatars
|
44 |
+
if "avatars" not in st.session_state:
|
45 |
+
st.session_state.avatars = {'user': None, 'assistant': None}
|
46 |
+
|
47 |
+
# Initialize session state for user text input
|
48 |
+
if 'user_text' not in st.session_state:
|
49 |
+
st.session_state.user_text = None
|
50 |
+
|
51 |
+
# Initialize session state for model parameters
|
52 |
+
if "max_response_length" not in st.session_state:
|
53 |
+
st.session_state.max_response_length = 256
|
54 |
+
|
55 |
+
if "system_message" not in st.session_state:
|
56 |
+
st.session_state.system_message = "friendly AI conversing with a human user"
|
57 |
+
|
58 |
+
if "starter_message" not in st.session_state:
|
59 |
+
st.session_state.starter_message = "Hello, there! How can I help you today?"
|
60 |
+
|
61 |
+
|
62 |
+
# Sidebar for settings
|
63 |
+
with st.sidebar:
|
64 |
+
st.header("System Settings")
|
65 |
+
|
66 |
+
st.session_state.system_message = st.text_area(
|
67 |
+
"System Message", value="You are a friendly AI conversing with a human user."
|
68 |
+
)
|
69 |
+
st.session_state.starter_message = st.text_area(
|
70 |
+
'First AI Message', value="Hello, there! How can I help you today?"
|
71 |
+
)
|
72 |
+
|
73 |
+
|
74 |
+
model_id = st.selectbox("Select Model", list_model)
|
75 |
+
|
76 |
+
# Model Settings
|
77 |
+
st.session_state.max_response_length = st.number_input(
|
78 |
+
"Max Response Length", value=128
|
79 |
+
)
|
80 |
+
|
81 |
+
temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.1, step=0.01)
|
82 |
+
# Avatar Selection
|
83 |
+
st.markdown("*Select Avatars:*")
|
84 |
+
col1, col2 = st.columns(2)
|
85 |
+
with col1:
|
86 |
+
st.session_state.avatars['assistant'] = st.selectbox(
|
87 |
+
"AI Avatar", options=["π€", "π¬", "π€"], index=0
|
88 |
+
)
|
89 |
+
with col2:
|
90 |
+
st.session_state.avatars['user'] = st.selectbox(
|
91 |
+
"User Avatar", options=["π€", "π±ββοΈ", "π¨πΎ", "π©", "π§πΎ"], index=0
|
92 |
+
)
|
93 |
+
# Reset Chat History
|
94 |
+
reset_history = st.button("Reset Chat History")
|
95 |
+
|
96 |
+
# Initialize or reset chat history
|
97 |
+
if "chat_history" not in st.session_state or reset_history:
|
98 |
+
st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
|
99 |
+
|
100 |
+
def get_response(system_message, chat_history, user_text,
|
101 |
+
eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):
|
102 |
+
"""
|
103 |
+
Generates a response from the chatbot model.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
system_message (str): The system message for the conversation.
|
107 |
+
chat_history (list): The list of previous chat messages.
|
108 |
+
user_text (str): The user's input text.
|
109 |
+
model_id (str, optional): The ID of the HuggingFace model to use.
|
110 |
+
eos_token_id (list, optional): The list of end-of-sentence token IDs.
|
111 |
+
max_new_tokens (int, optional): The maximum number of new tokens to generate.
|
112 |
+
get_llm_hf_kws (dict, optional): Additional keyword arguments for the get_llm_hf function.
|
113 |
+
|
114 |
+
Returns:
|
115 |
+
tuple: A tuple containing the generated response and the updated chat history.
|
116 |
+
"""
|
117 |
+
# Set up the model
|
118 |
+
hf = get_llm_hf_inference(model_id=model_id, max_new_tokens=max_new_tokens, temperature=temperature)
|
119 |
+
|
120 |
+
# Create the prompt template
|
121 |
+
prompt = PromptTemplate.from_template(
|
122 |
+
(
|
123 |
+
"[INST] {system_message}"
|
124 |
+
"\nCurrent Conversation:\n{chat_history}\n\n"
|
125 |
+
"\nUser: {user_text}.\n [/INST]"
|
126 |
+
"\nAI:"
|
127 |
+
)
|
128 |
+
)
|
129 |
+
# Make the chain and bind the prompt
|
130 |
+
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
131 |
+
|
132 |
+
# Generate the response
|
133 |
+
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
|
134 |
+
response = response.split("AI:")[-1]
|
135 |
+
|
136 |
+
# Update the chat history
|
137 |
+
chat_history.append({'role': 'user', 'content': user_text})
|
138 |
+
chat_history.append({'role': 'assistant', 'content': response})
|
139 |
+
return response, chat_history
|
140 |
+
|
141 |
+
# Chat interface
|
142 |
+
chat_interface = st.container(border=True)
|
143 |
+
with chat_interface:
|
144 |
+
output_container = st.container()
|
145 |
+
st.session_state.user_text = st.chat_input(placeholder="Enter your text here.")
|
146 |
+
|
147 |
+
# Display chat messages
|
148 |
+
with output_container:
|
149 |
+
# For every message in the history
|
150 |
+
for message in st.session_state.chat_history:
|
151 |
+
# Skip the system message
|
152 |
+
if message['role'] == 'system':
|
153 |
+
continue
|
154 |
+
|
155 |
+
# Display the chat message using the correct avatar
|
156 |
+
with st.chat_message(message['role'],
|
157 |
+
avatar=st.session_state['avatars'][message['role']]):
|
158 |
+
st.markdown(message['content'])
|
159 |
+
|
160 |
+
# When the user enter new text:
|
161 |
+
if st.session_state.user_text:
|
162 |
+
|
163 |
+
# Display the user's new message immediately
|
164 |
+
with st.chat_message("user",
|
165 |
+
avatar=st.session_state.avatars['user']):
|
166 |
+
st.markdown(st.session_state.user_text)
|
167 |
+
|
168 |
+
# Display a spinner status bar while waiting for the response
|
169 |
+
with st.chat_message("assistant",
|
170 |
+
avatar=st.session_state.avatars['assistant']):
|
171 |
+
|
172 |
+
with st.spinner("Thinking..."):
|
173 |
+
# Call the Inference API with the system_prompt, user text, and history
|
174 |
+
response, st.session_state.chat_history = get_response(
|
175 |
+
system_message=st.session_state.system_message,
|
176 |
+
user_text=st.session_state.user_text,
|
177 |
+
chat_history=st.session_state.chat_history,
|
178 |
+
max_new_tokens=st.session_state.max_response_length,
|
179 |
+
)
|
180 |
+
st.markdown(response)
|
requirements.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
langchain==0.3.16
|
2 |
+
langchain-community==0.3.16
|
3 |
+
langchain-core==0.3.32
|
4 |
+
langchain-huggingface==0.1.2
|
5 |
+
langchain-text-splitters==0.3.5
|
6 |
+
torch==2.5.1
|
7 |
+
langsmith==0.3.2
|
8 |
+
transformers==4.48.1
|
9 |
+
tokenizers==0.21.0
|
10 |
+
huggingface-hub==0.28.0
|
11 |
+
numpy==1.24.2
|
12 |
+
pandas==2.2.3
|