Hashim998 commited on
Commit
bbf1b06
·
verified ·
1 Parent(s): b783a74

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import json
4
+ import time
5
+ import gradio as gr
6
+ import logging
7
+
8
+ # Load local .env only if it exists
9
+ from dotenv import load_dotenv
10
+ load_dotenv()
11
+
12
+ import google.generativeai as genai
13
+
14
+ from langgraph.graph import START, MessagesState, StateGraph
15
+ from langgraph.checkpoint.memory import MemorySaver
16
+ from langchain_core.messages import HumanMessage, AIMessage
17
+ from langchain_core.prompts.chat import (
18
+ ChatPromptTemplate,
19
+ SystemMessagePromptTemplate,
20
+ MessagesPlaceholder,
21
+ HumanMessagePromptTemplate,
22
+ )
23
+ from langchain_google_genai import ChatGoogleGenerativeAI
24
+
25
+ # === Logging ===
26
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # === Load API Key ===
30
+ os.environ["GOOGLE_API_KEY"] = os.getenv["GEMINI_API_KEY"]
31
+
32
+ # GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
33
+ # if not GEMINI_API_KEY:
34
+ #raise ValueError("GEMINI_API_KEY is missing. Set it as an environment variable or Hugging Face Secret.")
35
+
36
+ genai.configure(api_key=GEMINI_API_KEY)
37
+
38
+ # === Chat Storage ===
39
+ HISTORY_FILE = "chat_history.json"
40
+
41
+ def load_all_sessions():
42
+ if os.path.exists(HISTORY_FILE):
43
+ with open(HISTORY_FILE, "r", encoding="utf-8") as f:
44
+ return json.load(f)
45
+ return {}
46
+
47
+ def save_all_sessions(sessions):
48
+ with open(HISTORY_FILE, "w", encoding="utf-8") as f:
49
+ json.dump(sessions, f, indent=2)
50
+
51
+ sessions = load_all_sessions()
52
+
53
+ # === Gemini LLM Chatbot ===
54
+ class GeminiChatbot:
55
+ def __init__(self):
56
+ self.setup_model()
57
+
58
+ def setup_model(self):
59
+ system_template = """
60
+ You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.
61
+ Your answers should be informative, engaging, and accurate. If a question doesn't make any sense, or isn't factually coherent, explain why.
62
+ If you don't know the answer to a question, please don't share false information.
63
+ """
64
+
65
+ self.prompt = ChatPromptTemplate.from_messages([
66
+ SystemMessagePromptTemplate.from_template(system_template),
67
+ MessagesPlaceholder(variable_name="chat_history"),
68
+ HumanMessagePromptTemplate.from_template("{input}")
69
+ ])
70
+
71
+ self.model = ChatGoogleGenerativeAI(
72
+ model="gemini-2.0-flash",
73
+ temperature=0.7,
74
+ top_p=0.95,
75
+ google_api_key=GEMINI_API_KEY,
76
+ convert_system_message_to_human=True
77
+ )
78
+
79
+ def call_model(state: MessagesState):
80
+ chat_history = state["messages"][:-1]
81
+ user_input = state["messages"][-1].content
82
+ formatted_messages = self.prompt.format_messages(chat_history=chat_history, input=user_input)
83
+ response = self.model.invoke(formatted_messages)
84
+ return {"messages": response}
85
+
86
+ workflow = StateGraph(state_schema=MessagesState)
87
+ workflow.add_node("model", call_model)
88
+ workflow.add_edge(START, "model")
89
+
90
+ self.memory = MemorySaver()
91
+ self.app = workflow.compile(checkpointer=self.memory)
92
+
93
+ def get_response(self, user_message, history, thread_id):
94
+ from langchain_core.messages import HumanMessage, AIMessage
95
+
96
+ try:
97
+ # Format chat history for LangChain
98
+ langchain_history = []
99
+ for user, bot in history:
100
+ langchain_history.append(HumanMessage(content=user))
101
+ langchain_history.append(AIMessage(content=bot))
102
+
103
+ input_msg = HumanMessage(content=user_message)
104
+ full_history = langchain_history + [input_msg]
105
+ config = {"configurable": {"thread_id": thread_id}}
106
+
107
+ # Get final response
108
+ response = self.app.invoke({"messages": full_history}, config)
109
+ full_text = response["messages"][-1].content
110
+
111
+ full_response = ""
112
+ for char in full_text:
113
+ full_response += char
114
+ yield full_response
115
+ time.sleep(0.01)
116
+
117
+ except Exception as e:
118
+ logger.error(f"Response error: {e}")
119
+ yield f"⚠ Error: {type(e).__name__} — {str(e)}"
120
+
121
+
122
+ chatbot = GeminiChatbot()
123
+
124
+ # === Gradio UI ===
125
+ def launch_interface():
126
+ with gr.Blocks(
127
+ theme=gr.themes.Base(),
128
+ css="""
129
+ body { background-color: black; }
130
+ .gr-textbox textarea { background-color: #2f2f2f; color: white; }
131
+ .gr-chatbot { background-color: #2f2f2f; color: white; }
132
+ .gr-button, .gr-dropdown {
133
+ margin: 5px auto;
134
+ display: block;
135
+ width: 50%;
136
+ }
137
+ .gr-markdown h2 { text-align: center; color: white; }
138
+ """
139
+ ) as demo:
140
+ demo.title = "LangChain Powered ChatBot"
141
+ gr.Markdown("## LangChain Powered ChatBot")
142
+
143
+ current_thread_id = gr.State()
144
+ session_names = gr.State()
145
+ history = gr.State([])
146
+
147
+ if not sessions:
148
+ new_id = str(uuid.uuid4())
149
+ sessions[new_id] = []
150
+ save_all_sessions(sessions)
151
+ current_thread_id.value = new_id
152
+ session_names.value = [f"NEW: {new_id}"]
153
+ else:
154
+ current_thread_id.value = next(iter(sessions))
155
+ session_names.value = [f"PREVIOUS: {k}" for k in sessions if sessions[k]]
156
+
157
+ def get_dropdown_choices():
158
+ return [f"PREVIOUS: {k}" for k in sessions if sessions[k]] + [f"NEW: {current_thread_id.value}"]
159
+
160
+ # UI
161
+ new_chat_btn = gr.Button("New Chat", variant="primary")
162
+ session_selector = gr.Dropdown(
163
+ label="Chats",
164
+ choices=get_dropdown_choices(),
165
+ value=f"NEW: {current_thread_id.value}",
166
+ interactive=True
167
+ )
168
+
169
+ chatbot_ui = gr.Chatbot(label="Conversation", height=350)
170
+
171
+ with gr.Row():
172
+ msg = gr.Textbox(placeholder="Ask a question...", container=False, scale=9)
173
+ send = gr.Button("Send", variant="primary", scale=1)
174
+
175
+ clear = gr.Button("Clear Current Chat")
176
+
177
+ # === Event Functions ===
178
+ def start_new_chat():
179
+ new_id = str(uuid.uuid4())
180
+ sessions[new_id] = []
181
+ save_all_sessions(sessions)
182
+ display = f"NEW: {new_id}"
183
+ updated = [f"PREVIOUS: {k}" for k in sessions if sessions[k]] + [display]
184
+ return new_id, [], gr.update(choices=updated, value=display), display
185
+
186
+ def switch_chat(display_id):
187
+ true_id = display_id.split(": ", 1)[-1]
188
+ return true_id, sessions.get(true_id, []), display_id
189
+
190
+ def respond(message, history, thread_id):
191
+ if not message.strip():
192
+ yield history
193
+ return
194
+ history.append((message, ""))
195
+ yield history
196
+
197
+ for chunk in chatbot.get_response(message, history[:-1], thread_id):
198
+ history[-1] = (message, chunk)
199
+ yield history
200
+
201
+ sessions[thread_id] = history
202
+ save_all_sessions(sessions)
203
+
204
+ def clear_chat(thread_id):
205
+ sessions[thread_id] = []
206
+ save_all_sessions(sessions)
207
+ return []
208
+
209
+ # === Bind Events ===
210
+ new_chat_btn.click(start_new_chat, outputs=[current_thread_id, chatbot_ui, session_selector, session_selector])
211
+ session_selector.change(switch_chat, inputs=session_selector, outputs=[current_thread_id, chatbot_ui, session_selector])
212
+ send.click(respond, [msg, chatbot_ui, current_thread_id], [chatbot_ui]).then(lambda: "", None, msg)
213
+ msg.submit(respond, [msg, chatbot_ui, current_thread_id], [chatbot_ui]).then(lambda: "", None, msg)
214
+ clear.click(clear_chat, inputs=[current_thread_id], outputs=[chatbot_ui])
215
+
216
+ return demo
217
+
218
+ # === Run App ===
219
+ if __name__ == "__main__":
220
+ try:
221
+ demo = launch_interface()
222
+ demo.launch()
223
+ except Exception as e:
224
+ logger.critical(f"App failed: {e}")