Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,292 @@
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
61 |
|
62 |
|
|
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import uuid
|
3 |
+
import json
|
4 |
+
import time
|
5 |
import gradio as gr
|
6 |
+
import logging
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
import google.generativeai as genai
|
9 |
+
|
10 |
+
from langgraph.graph import START, MessagesState, StateGraph
|
11 |
+
from langgraph.checkpoint.memory import MemorySaver
|
12 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
13 |
+
from langchain_core.prompts.chat import (
|
14 |
+
ChatPromptTemplate,
|
15 |
+
SystemMessagePromptTemplate,
|
16 |
+
MessagesPlaceholder,
|
17 |
+
HumanMessagePromptTemplate,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
)
|
19 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
20 |
+
from langchain_core.messages import BaseMessage
|
21 |
+
|
22 |
+
|
23 |
+
# === Logging & .env ===
|
24 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
25 |
+
logger = logging.getLogger(__name__)
|
26 |
+
load_dotenv()
|
27 |
+
|
28 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
29 |
+
if not GEMINI_API_KEY:
|
30 |
+
raise ValueError("Missing GEMINI_API_KEY")
|
31 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
32 |
+
|
33 |
+
HISTORY_FILE = "chat_history.json"
|
34 |
+
|
35 |
+
# === Persistent Storage ===
|
36 |
+
def load_all_sessions():
|
37 |
+
if os.path.exists(HISTORY_FILE):
|
38 |
+
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
|
39 |
+
return json.load(f)
|
40 |
+
return {}
|
41 |
+
|
42 |
+
def save_all_sessions(sessions):
|
43 |
+
with open(HISTORY_FILE, "w", encoding="utf-8") as f:
|
44 |
+
json.dump(sessions, f, indent=2)
|
45 |
+
|
46 |
+
# === Chatbot Class ===
|
47 |
+
class GeminiChatbot:
|
48 |
+
def __init__(self):
|
49 |
+
self.setup_model()
|
50 |
+
|
51 |
+
def setup_model(self):
|
52 |
+
system_template = """
|
53 |
+
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.
|
54 |
+
Your answers should be informative, engaging, and accurate. If a question doesn't make any sense, or isn't factually coherent, explain why instead of answering something not correct.
|
55 |
+
If you don't know the answer to a question, please don't share false information.
|
56 |
+
"""
|
57 |
+
|
58 |
+
self.prompt = ChatPromptTemplate.from_messages([
|
59 |
+
SystemMessagePromptTemplate.from_template(system_template),
|
60 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
61 |
+
HumanMessagePromptTemplate.from_template("{input}")
|
62 |
+
])
|
63 |
+
|
64 |
+
self.model = ChatGoogleGenerativeAI(
|
65 |
+
model="gemini-2.0-flash",
|
66 |
+
temperature=0.7,
|
67 |
+
top_p=0.95,
|
68 |
+
google_api_key=GEMINI_API_KEY,
|
69 |
+
convert_system_message_to_human=True
|
70 |
+
)
|
71 |
+
|
72 |
+
def call_model(state: MessagesState):
|
73 |
+
chat_history = state["messages"][:-1]
|
74 |
+
user_input = state["messages"][-1].content
|
75 |
+
|
76 |
+
formatted_messages = self.prompt.format_messages(
|
77 |
+
chat_history=chat_history,
|
78 |
+
input=user_input
|
79 |
+
)
|
80 |
+
|
81 |
+
response = self.model.invoke(formatted_messages)
|
82 |
+
return {"messages": response}
|
83 |
+
|
84 |
+
workflow = StateGraph(state_schema=MessagesState)
|
85 |
+
workflow.add_node("model", call_model)
|
86 |
+
workflow.add_edge(START, "model")
|
87 |
+
|
88 |
+
self.memory = MemorySaver()
|
89 |
+
self.app = workflow.compile(checkpointer=self.memory)
|
90 |
+
|
91 |
+
def get_response(self, user_message, history, thread_id):
|
92 |
+
try:
|
93 |
+
# Convert string history into LangChain message objects
|
94 |
+
langchain_history = []
|
95 |
+
for user, bot in history:
|
96 |
+
langchain_history.append(HumanMessage(content=user))
|
97 |
+
langchain_history.append(AIMessage(content=bot))
|
98 |
+
|
99 |
+
# Add the new user message
|
100 |
+
input_message = HumanMessage(content=user_message)
|
101 |
+
full_history = langchain_history + [input_message]
|
102 |
+
|
103 |
+
full_response = ""
|
104 |
+
config = {"configurable": {"thread_id": thread_id}}
|
105 |
+
|
106 |
+
# Invoke the model with full conversation
|
107 |
+
response = self.app.invoke({"messages": full_history}, config)
|
108 |
+
complete_response = response["messages"][-1].content
|
109 |
+
|
110 |
+
for char in complete_response:
|
111 |
+
full_response += char
|
112 |
+
yield full_response
|
113 |
+
time.sleep(0.01)
|
114 |
+
|
115 |
+
except Exception as e:
|
116 |
+
logger.error(f"LangGraph Error: {e}")
|
117 |
+
yield f"⚠ Error: {type(e).__name__} — {str(e)}"
|
118 |
+
|
119 |
+
|
120 |
+
# === Gradio UI ===
|
121 |
+
chatbot = GeminiChatbot()
|
122 |
+
sessions = load_all_sessions()
|
123 |
+
|
124 |
+
|
125 |
+
def launch_interface():
|
126 |
+
with gr.Blocks(
|
127 |
+
theme=gr.themes.Base(),
|
128 |
+
css="""
|
129 |
+
body {
|
130 |
+
background-color: black;
|
131 |
+
}
|
132 |
+
.gr-block.gr-textbox textarea {
|
133 |
+
background-color: #2f2f2f;
|
134 |
+
color: white;
|
135 |
+
}
|
136 |
+
.gr-chatbot {
|
137 |
+
background-color: #2f2f2f;
|
138 |
+
color: white;
|
139 |
+
}
|
140 |
+
.gr-button, .gr-dropdown {
|
141 |
+
margin: 5px auto;
|
142 |
+
display: block;
|
143 |
+
width: 50%;
|
144 |
+
}
|
145 |
+
.gr-markdown h2 {
|
146 |
+
text-align: center;
|
147 |
+
color: white;
|
148 |
+
}
|
149 |
+
"""
|
150 |
+
) as demo:
|
151 |
+
demo.title = "LangChain Powered ChatBot"
|
152 |
+
gr.Markdown("## LangChain Powered ChatBot")
|
153 |
+
|
154 |
+
current_thread_id = gr.State()
|
155 |
+
session_names = gr.State()
|
156 |
+
history = gr.State([])
|
157 |
+
|
158 |
+
# Initialize with first session or create new
|
159 |
+
if not sessions:
|
160 |
+
new_id = str(uuid.uuid4())
|
161 |
+
sessions[new_id] = []
|
162 |
+
save_all_sessions(sessions)
|
163 |
+
current_thread_id.value = new_id
|
164 |
+
session_names.value = [f"NEW: {new_id}"]
|
165 |
+
else:
|
166 |
+
current_thread_id.value = next(iter(sessions.keys()))
|
167 |
+
session_names.value = [f"PREVIOUS: {k}" for k in sessions.keys()]
|
168 |
+
|
169 |
+
def get_dropdown_choices():
|
170 |
+
"""Get current dropdown choices including active sessions and new chat"""
|
171 |
+
choices = []
|
172 |
+
for session_id in sessions:
|
173 |
+
if sessions[session_id]: # Only show sessions with history
|
174 |
+
choices.append(f"PREVIOUS: {session_id}")
|
175 |
+
choices.append(f"NEW: {current_thread_id.value}")
|
176 |
+
return choices
|
177 |
+
|
178 |
+
with gr.Column():
|
179 |
+
new_chat_btn = gr.Button("New Chat", variant="primary")
|
180 |
+
session_selector = gr.Dropdown(
|
181 |
+
label="Chats",
|
182 |
+
choices=get_dropdown_choices(),
|
183 |
+
value=f"NEW: {current_thread_id.value}",
|
184 |
+
interactive=True
|
185 |
+
)
|
186 |
+
|
187 |
+
chatbot_ui = gr.Chatbot(label="Conversation", height=320)
|
188 |
+
|
189 |
+
with gr.Row():
|
190 |
+
msg = gr.Textbox(placeholder="Ask a question...", container=False, scale=9)
|
191 |
+
send = gr.Button("Send", variant="primary", scale=1)
|
192 |
+
|
193 |
+
clear = gr.Button("Clear Current Chat")
|
194 |
+
|
195 |
+
def start_new_chat():
|
196 |
+
new_id = str(uuid.uuid4())
|
197 |
+
sessions[new_id] = []
|
198 |
+
save_all_sessions(sessions)
|
199 |
+
|
200 |
+
# Format for dropdown
|
201 |
+
display_name = f"NEW: {new_id}"
|
202 |
+
updated_choices = [f"PREVIOUS: {k}" for k in sessions if sessions[k]] + [display_name]
|
203 |
+
|
204 |
+
return (
|
205 |
+
new_id, # thread ID state
|
206 |
+
[], # history
|
207 |
+
gr.update(choices=updated_choices, value=display_name), # update dropdown
|
208 |
+
display_name # visible value
|
209 |
+
)
|
210 |
+
|
211 |
+
|
212 |
+
|
213 |
+
def switch_chat(selected_display_id):
|
214 |
+
"""Switch between different chat sessions"""
|
215 |
+
if not selected_display_id:
|
216 |
+
return current_thread_id.value, [], ""
|
217 |
+
|
218 |
+
true_id = selected_display_id.split(": ", 1)[-1]
|
219 |
+
chat_history = sessions.get(true_id, [])
|
220 |
+
return true_id, chat_history, selected_display_id
|
221 |
+
|
222 |
+
def respond(message, history, thread_id):
|
223 |
+
"""Generate response and update chat history"""
|
224 |
+
if not message.strip():
|
225 |
+
yield history
|
226 |
+
return
|
227 |
+
|
228 |
+
# Add user message to history
|
229 |
+
history.append((message, ""))
|
230 |
+
yield history
|
231 |
+
|
232 |
+
# Stream response
|
233 |
+
full_response = ""
|
234 |
+
for chunk in chatbot.get_response(message, history[:-1], thread_id):
|
235 |
+
full_response = chunk
|
236 |
+
history[-1] = (message, full_response)
|
237 |
+
yield history
|
238 |
+
|
239 |
+
# Save updated session
|
240 |
+
sessions[thread_id] = history
|
241 |
+
save_all_sessions(sessions)
|
242 |
+
|
243 |
+
def clear_current(thread_id):
|
244 |
+
"""Clear current chat history"""
|
245 |
+
sessions[thread_id] = []
|
246 |
+
save_all_sessions(sessions)
|
247 |
+
return []
|
248 |
+
|
249 |
+
new_chat_btn.click(
|
250 |
+
start_new_chat,
|
251 |
+
outputs=[current_thread_id, chatbot_ui, session_selector, session_selector]
|
252 |
+
)
|
253 |
+
|
254 |
+
session_selector.change(
|
255 |
+
switch_chat,
|
256 |
+
inputs=session_selector,
|
257 |
+
outputs=[current_thread_id, chatbot_ui, session_selector]
|
258 |
+
)
|
259 |
+
|
260 |
+
send.click(
|
261 |
+
respond,
|
262 |
+
inputs=[msg, chatbot_ui, current_thread_id],
|
263 |
+
outputs=[chatbot_ui]
|
264 |
+
).then(
|
265 |
+
lambda: "", None, msg # Clear input after sending
|
266 |
+
)
|
267 |
+
|
268 |
+
msg.submit(
|
269 |
+
respond,
|
270 |
+
inputs=[msg, chatbot_ui, current_thread_id],
|
271 |
+
outputs=[chatbot_ui]
|
272 |
+
).then(
|
273 |
+
lambda: "", None, msg # Clear input after sending
|
274 |
+
)
|
275 |
+
|
276 |
+
clear.click(
|
277 |
+
clear_current,
|
278 |
+
inputs=[current_thread_id],
|
279 |
+
outputs=[chatbot_ui]
|
280 |
+
)
|
281 |
+
|
282 |
+
return demo
|
283 |
+
|
284 |
|
285 |
|
286 |
+
# === Run App ===
|
287 |
if __name__ == "__main__":
|
288 |
+
try:
|
289 |
+
demo = launch_interface()
|
290 |
+
demo.launch(share=True)
|
291 |
+
except Exception as e:
|
292 |
+
logger.critical(f"App failed: {e}")
|