Dharma20 commited on
Commit
a7e19d9
·
verified ·
1 Parent(s): 1badade

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +426 -426
app.py CHANGED
@@ -1,426 +1,426 @@
1
- from setup import *
2
- from embedding import *
3
- import gradio as gr
4
- from setup import *
5
- from embedding import*
6
-
7
-
8
- from typing import Annotated, Sequence, Literal, List, Dict
9
- from typing_extensions import TypedDict
10
- from langgraph.graph import MessagesState
11
- from langchain_core.documents import Document
12
- from pydantic import BaseModel, Field
13
-
14
- from langchain_core.messages import BaseMessage, AnyMessage
15
- from langgraph.graph.message import add_messages
16
- from langchain_core.messages import SystemMessage, HumanMessage
17
- from langchain_core.runnables.config import RunnableConfig
18
- import uuid
19
- from langgraph.store.base import BaseStore
20
- from langchain_core.prompts import ChatPromptTemplate,SystemMessagePromptTemplate, HumanMessagePromptTemplate
21
- from langgraph.graph import END, StateGraph, START
22
- from langgraph.prebuilt import ToolNode
23
- from langgraph.checkpoint.memory import MemorySaver
24
- from langgraph.store.memory import InMemoryStore
25
-
26
- persist_directory = "D:\\Education\\AI\\AI-Agents\\Agentic-RAG"
27
-
28
- loaded_db = Chroma(
29
- persist_directory=persist_directory,
30
- embedding_function=embeddings,
31
- collection_name='sagemaker-chroma'
32
- )
33
-
34
- retriever = vector_store.as_retriever()
35
-
36
-
37
-
38
-
39
- in_memory_store = InMemoryStore()
40
-
41
- class AgentState(MessagesState):
42
- messages: Annotated[list, add_messages]
43
- history: List[AnyMessage]
44
- context: List[Document]
45
- length : int
46
- query : str
47
- summary : str
48
-
49
-
50
-
51
-
52
- def agent(state, config: RunnableConfig, store: BaseStore):
53
-
54
- print("----CALL AGENT----")
55
- messages = state['messages']
56
- context = state['context']
57
- previous_conversation_summary = state['summary']
58
- last_messages=state["messages"][-4:]
59
-
60
- system_template = '''You are a friendly and knowledgeable conversational assistant with memory specializing in AWS SageMaker. Your job is to answer questions about SageMaker clearly, accurately, and in a human-like, natural way—like a helpful teammate. Keep your tone polite, engaging, and professional.
61
- You can help with:
62
- SageMaker features, pricing, and capabilities
63
- Model training, deployment, tuning, and monitoring in SageMaker
64
- Integration with other AWS services in the context of SageMaker
65
- Troubleshooting common SageMaker issues
66
-
67
- You must not answer questions unrelated to AWS SageMaker. If asked, briefly and politely respond with something like:
68
- "Sorry, I can only help with AWS SageMaker. Let me know if you have any questions about that!"
69
-
70
- Take into consideration the summary of the conversation so far and last 4 messages
71
- Summary of the conversation so far: {previous_conversation_summary}
72
- last 4 messages : {last_messages}
73
-
74
- Also use the context from the docs retrieved for the user query:
75
- {context}
76
-
77
- Here is the memory (it may be empty): {memory}"""
78
- Keep responses concise, correct, and helpful. Make the conversation feel smooth and human, like chatting with a skilled colleague who knows SageMaker inside out.'''
79
-
80
-
81
-
82
- # Get the user ID from the config
83
- user_id = config["configurable"]["user_id"]
84
-
85
- # Retrieve memory from the store
86
- namespace = ("memory", user_id)
87
- key = "user_memory"
88
- existing_memory = store.get(namespace, key)
89
-
90
- # Extract the actual memory content if it exists and add a prefix
91
- if existing_memory:
92
- # Value is a dictionary with a memory key
93
- existing_memory_content = existing_memory.value.get('memory')
94
- else:
95
- existing_memory_content = "No existing memory found."
96
-
97
-
98
- system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
99
-
100
- human_template = '''User last reply: {user_reply}'''
101
- human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
102
-
103
- chat_prompt = ChatPromptTemplate.from_messages([
104
- system_message_prompt,
105
- human_message_prompt
106
- ])
107
-
108
- formatted_messages = chat_prompt.format_messages(
109
- previous_conversation_summary=previous_conversation_summary,
110
- last_messages = last_messages,
111
- context = context,
112
- memory = existing_memory_content,
113
- user_reply = messages[-1].content
114
- )
115
- print('---------Message------', messages)
116
-
117
- response = llm.invoke(formatted_messages)
118
-
119
- return {'messages':[response]}
120
-
121
-
122
- def rewrite_query(state):
123
-
124
- print("----REWRITE QUERY----")
125
- previous_summary = state['summary']
126
- last_messages=state["history"][-4:]
127
- sys_msg_query = '''TASK: Rewrite the user's query to improve retrieval performance.
128
- CONTEXT:
129
- - Conversation Summary: {previous_summary}
130
- - User's Last Message: {last_messages}
131
-
132
- INSTRUCTIONS:
133
- 1. Identify the core information need in the user's message
134
- 2. Extract key entities, concepts, and relationships
135
- 3. Add relevant context from the conversation summary
136
- 4. Remove conversational fillers and ambiguous references
137
- 5. Use specific terminology that would match relevant documents
138
- 6. Expand abbreviations and clarify ambiguous terms
139
- 7. Format as a concise, search-optimized query
140
-
141
- Your rewritten query should:
142
- - Maintain the original intent
143
- - Be self-contained (not require conversation context to understand)
144
- - Include specific details that would match relevant documents
145
- - Be under 100 words
146
-
147
- OUTPUT FORMAT:
148
- Rewritten Query: '''
149
-
150
- rewritten = llm.invoke([SystemMessage(content=sys_msg_query.format(previous_summary=previous_summary,last_messages=last_messages))])
151
- rewritten_query = rewritten.content
152
- print('---QUERY---', rewritten_query)
153
-
154
- return {'query': rewritten_query}
155
-
156
-
157
- def summary_function(state):
158
- previous_summary = state['summary']
159
- last_messages=state["history"][-4:]
160
-
161
- sys_msg_summary = '''You are an AI that creates concise summaries of chat conversations. When summarizing:
162
- 1. Capture all named entities (people, organizations, products, locations) and their relationships.
163
- 2. Preserve explicit information, technical terms, and quantitative data.
164
- 3. Identify the conversation's intent, requirements, and underlying needs.
165
- 4. Incorporate previous summaries, resolving contradictions and updating information.
166
- 5. Structure information logically, omitting small talk while retaining critical details.
167
-
168
- Your summary should begin with the conversation purpose, include all key points, and end with the conversation outcome or status. Remain neutral and accurate, ensuring someone can understand what happened without reading the entire transcript.
169
-
170
- Previous summary:
171
- {previous_summary}
172
-
173
- Last 4 messages:
174
- {last_messages}
175
-
176
- Summary:
177
-
178
- '''
179
-
180
- summarised = llm.invoke([SystemMessage(content=sys_msg_summary.format(previous_summary=previous_summary,last_messages=last_messages))])
181
- summarised_content = summarised.content
182
- print('SUUUUUUU', summarised_content)
183
-
184
- return {'summary' : summarised_content}
185
-
186
-
187
- def summary_or_not(state):
188
- if len(state['history']) % 4 == 0:
189
- return True
190
- else:
191
- return False
192
-
193
- def write_memory(state: MessagesState, config: RunnableConfig, store: BaseStore):
194
-
195
- """Reflect on the chat history and save a memory to the store."""
196
- CREATE_MEMORY_INSTRUCTION = """"You are collecting information about the user to personalize your responses.
197
-
198
- CURRENT USER INFORMATION:
199
- {memory}
200
-
201
- INSTRUCTIONS:
202
- 1. Review the chat history below carefully
203
- 2. Identify new information about the user, such as:
204
- - Personal details (name, location)
205
- - Preferences (likes, dislikes)
206
- - Interests and hobbies
207
- - Past experiences
208
- - Goals or future plans
209
- 3. Merge any new information with existing memory
210
- 4. Format the memory as a clear, bulleted list
211
- 5. If new information conflicts with existing memory, keep the most recent version
212
-
213
- Remember: Only include factual information directly stated by the user. Do not make assumptions or inferences.
214
-
215
- Based on the chat history below, please update the user information:"""
216
-
217
- # Get the user ID from the config
218
- user_id = config["configurable"]["user_id"]
219
-
220
- # Retrieve existing memory from the store
221
- namespace = ("memory", user_id)
222
- existing_memory = store.get(namespace, "user_memory")
223
-
224
- # Extract the memory
225
- if existing_memory:
226
- existing_memory_content = existing_memory.value.get('memory')
227
- else:
228
- existing_memory_content = "No existing memory found."
229
-
230
- # Format the memory in the system prompt
231
- system_msg = CREATE_MEMORY_INSTRUCTION.format(memory=existing_memory_content)
232
- new_memory = llm.invoke([SystemMessage(content=system_msg)]+state['messages'])
233
-
234
- # Overwrite the existing memory in the store
235
- key = "user_memory"
236
-
237
- # Write value as a dictionary with a memory key
238
- store.put(namespace, key, {"memory": new_memory.content})
239
-
240
-
241
- def retrieve_or_not(state) -> Literal["yes", "no"]:
242
-
243
- print("----RETREIVE or NOT----")
244
- messages = state["messages"]
245
- previous_summary = state['summary']
246
- last_messages=state["history"][-4:]
247
- user_reply = messages[-1].content
248
-
249
- sys_msg = '''You are a specialized decision-making system that evaluates whether retrieval is needed for the current conversation.
250
-
251
- Your only task is to determine if external information retrieval is necessary based on:
252
- 1. The user's most recent message
253
- 2. Recent conversation turns (if provided)
254
- 3. Conversation summary (if provided)
255
-
256
- **You MUST respond ONLY with "yes" or "no".**
257
-
258
- Guidelines for your decision:
259
- - Reply "yes" if:
260
- - The query requests specific factual information (dates, statistics, events, etc.)
261
- - The query asks about real-world entities, events, or concepts that require precise information
262
- - The query references documents or data that would need to be retrieved
263
- - The query asks about recent or current events that may not be in your training data
264
- - The query explicitly asks for citations, references, or sources
265
- - The query contains specific dates, locations, or proper nouns that might require additional context
266
- - The query appears to be searching for specific information
267
-
268
- - Reply "no" if:
269
- - The query is a clarification about something previously explained
270
- - The query asks for creative content (stories, poems, etc.)
271
- - The query asks for general advice or opinions
272
- - The query is conversational in nature (greetings, thanks, etc.)
273
- - The query is about general concepts that don't require specific factual information
274
- - The query can be sufficiently answered with your existing knowledge
275
- - The query is a simple follow-up that doesn't introduce new topics requiring retrieval
276
-
277
- Remember: Your response must be EXACTLY "yes" or "no" with no additional text, explanation, or punctuation.
278
- Previous summary: {previous_summary}
279
- Last 4 messages: {last_messages}
280
- The user sent the reply as {user_reply}.
281
- Should we need retrieval: '''
282
-
283
- class decide(BaseModel):
284
- '''Decision for retrival - yes or no'''
285
- decision: str = Field(description="Relevance score 'yes' or 'no'")
286
-
287
- structured_llm= llm.with_structured_output(decide)
288
-
289
- retrive_decision = structured_llm.invoke([SystemMessage(content=sys_msg.format(previous_summary=previous_summary,last_messages=last_messages,user_reply=user_reply))])
290
-
291
- print('-------retrievedecisde---------', retrive_decision)
292
- if retrive_decision == 'yes':
293
- return True
294
-
295
- return False
296
-
297
- def pass_node(state):
298
- # Update the fill value
299
- new_length = len(state["history"])
300
-
301
- # Return the updated state without making branch decisions
302
- return {"length": new_length}
303
-
304
-
305
- def retrieve_docs(state):
306
- query = state['query']
307
- retrieved_docs = loaded_db.similarity_search(query=query, k=5)
308
- return {'context' : retrieved_docs}
309
-
310
-
311
-
312
-
313
-
314
- workflow = StateGraph(AgentState)
315
-
316
-
317
- workflow.add_node('assistant', agent)
318
- workflow.add_node('summary_fn', summary_function)
319
- workflow.add_node('retrieve_bool', pass_node)
320
- workflow.add_node('rewrite_query',rewrite_query)
321
- workflow.add_node('retriever',retrieve_docs)
322
- workflow.add_node("write_memory", write_memory)
323
-
324
-
325
- workflow.add_conditional_edges(START, summary_or_not, {True: 'summary_fn', False:'retrieve_bool'})
326
- workflow.add_edge('summary_fn', 'retrieve_bool')
327
- workflow.add_conditional_edges('retrieve_bool', retrieve_or_not, {True: 'rewrite_query', False:'write_memory'})
328
- workflow.add_edge('rewrite_query', 'retriever')
329
- workflow.add_edge('retriever', 'write_memory')
330
- workflow.add_edge('write_memory', 'assistant')
331
- workflow.add_edge('assistant', END)
332
-
333
- within_thread_memory = MemorySaver()
334
- across_thread_memory = InMemoryStore()
335
- chat_graph = workflow.compile(checkpointer=within_thread_memory, store=across_thread_memory)
336
-
337
-
338
- within_thread_memory = MemorySaver()
339
- across_thread_memory = InMemoryStore()
340
- chat_graph = workflow.compile(checkpointer=within_thread_memory, store=across_thread_memory)
341
-
342
-
343
-
344
- import time
345
- import gradio as gr
346
-
347
- def main(conv_history, user_reply):
348
- # Don't recreate the config each time
349
- config = {"configurable": {"thread_id": "1", "user_id": "1"}}
350
-
351
- # Get the current state
352
- state = chat_graph.get_state(config).values
353
-
354
- # Initialize state if it doesn't exist yet
355
- if not state:
356
- state = {
357
- 'messages': [],
358
- 'summary': '',
359
- 'length': 0
360
- }
361
-
362
- # Process the new message using LangGraph
363
- chat_graph.invoke({
364
- 'messages': [('user', user_reply)],
365
- 'history': state['messages'],
366
- 'summary': state['summary'],
367
- 'length': state['length'],
368
- 'context': 'None'
369
- }, config)
370
-
371
- # Get the updated state after processing
372
- output = chat_graph.get_state(config)
373
- new_messages = output.values['messages']
374
-
375
- # Initialize conv_history if None
376
- if conv_history is None:
377
- conv_history = []
378
-
379
- # Get the latest bot message
380
- bot_message = new_messages[-1].content # Get the last message
381
-
382
- # Stream the response (optional feature)
383
- streamed_message = ""
384
- for token in bot_message.split():
385
- streamed_message += f"{token} "
386
- yield conv_history + [(user_reply, streamed_message.strip())], " "
387
- time.sleep(0.05)
388
-
389
- # Add the final conversation pair to history
390
- conv_history.append((user_reply, bot_message))
391
-
392
- yield conv_history, " "
393
-
394
-
395
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
396
- gr.HTML("<center><h1>FAQ Chatbot! 📂📄</h1><center>")
397
- gr.Markdown("""##### This AI chatbot🤖 can answer your FAQ questions about """)
398
-
399
- with gr.Column():
400
- chatbot = gr.Chatbot(label='ChatBot')
401
- user_reply = gr.Textbox(label='Enter your query', placeholder='Type here...')
402
-
403
- with gr.Row():
404
- submit_button = gr.Button("Submit")
405
- clear_btn = gr.ClearButton([user_reply, chatbot], value='Clear')
406
-
407
- # Use the gr.State to store conversation history between refreshes
408
- state = gr.State([])
409
-
410
- # Update the click event to include state
411
- submit_button.click(
412
- main,
413
- inputs=[chatbot, user_reply],
414
- outputs=[chatbot, user_reply]
415
- )
416
-
417
- # Add an event handler for the clear button to reset the LangGraph state
418
- def reset_langgraph_state():
419
- config = {"configurable": {"thread_id": "1", "user_id": "1"}}
420
- # Reset the state in LangGraph (if your implementation supports this)
421
- # If not, you might need to implement a reset method in your graph
422
- return []
423
-
424
- clear_btn.click(reset_langgraph_state, inputs=[], outputs=[chatbot])
425
-
426
- demo.launch()
 
1
+ from setup import *
2
+ from embedding import *
3
+ import gradio as gr
4
+ from setup import *
5
+ from gradio_embedding import*
6
+
7
+
8
+ from typing import Annotated, Sequence, Literal, List, Dict
9
+ from typing_extensions import TypedDict
10
+ from langgraph.graph import MessagesState
11
+ from langchain_core.documents import Document
12
+ from pydantic import BaseModel, Field
13
+
14
+ from langchain_core.messages import BaseMessage, AnyMessage
15
+ from langgraph.graph.message import add_messages
16
+ from langchain_core.messages import SystemMessage, HumanMessage
17
+ from langchain_core.runnables.config import RunnableConfig
18
+ import uuid
19
+ from langgraph.store.base import BaseStore
20
+ from langchain_core.prompts import ChatPromptTemplate,SystemMessagePromptTemplate, HumanMessagePromptTemplate
21
+ from langgraph.graph import END, StateGraph, START
22
+ from langgraph.prebuilt import ToolNode
23
+ from langgraph.checkpoint.memory import MemorySaver
24
+ from langgraph.store.memory import InMemoryStore
25
+
26
+ persist_directory = "D:\\Education\\AI\\AI-Agents\\Agentic-RAG"
27
+
28
+ loaded_db = Chroma(
29
+ persist_directory=persist_directory,
30
+ embedding_function=embeddings,
31
+ collection_name='sagemaker-chroma'
32
+ )
33
+
34
+ retriever = vector_store.as_retriever()
35
+
36
+
37
+
38
+
39
+ in_memory_store = InMemoryStore()
40
+
41
+ class AgentState(MessagesState):
42
+ messages: Annotated[list, add_messages]
43
+ history: List[AnyMessage]
44
+ context: List[Document]
45
+ length : int
46
+ query : str
47
+ summary : str
48
+
49
+
50
+
51
+
52
+ def agent(state, config: RunnableConfig, store: BaseStore):
53
+
54
+ print("----CALL AGENT----")
55
+ messages = state['messages']
56
+ context = state['context']
57
+ previous_conversation_summary = state['summary']
58
+ last_messages=state["messages"][-4:]
59
+
60
+ system_template = '''You are a friendly and knowledgeable conversational assistant with memory specializing in AWS SageMaker. Your job is to answer questions about SageMaker clearly, accurately, and in a human-like, natural way—like a helpful teammate. Keep your tone polite, engaging, and professional.
61
+ You can help with:
62
+ SageMaker features, pricing, and capabilities
63
+ Model training, deployment, tuning, and monitoring in SageMaker
64
+ Integration with other AWS services in the context of SageMaker
65
+ Troubleshooting common SageMaker issues
66
+
67
+ You must not answer questions unrelated to AWS SageMaker. If asked, briefly and politely respond with something like:
68
+ "Sorry, I can only help with AWS SageMaker. Let me know if you have any questions about that!"
69
+
70
+ Take into consideration the summary of the conversation so far and last 4 messages
71
+ Summary of the conversation so far: {previous_conversation_summary}
72
+ last 4 messages : {last_messages}
73
+
74
+ Also use the context from the docs retrieved for the user query:
75
+ {context}
76
+
77
+ Here is the memory (it may be empty): {memory}"""
78
+ Keep responses concise, correct, and helpful. Make the conversation feel smooth and human, like chatting with a skilled colleague who knows SageMaker inside out.'''
79
+
80
+
81
+
82
+ # Get the user ID from the config
83
+ user_id = config["configurable"]["user_id"]
84
+
85
+ # Retrieve memory from the store
86
+ namespace = ("memory", user_id)
87
+ key = "user_memory"
88
+ existing_memory = store.get(namespace, key)
89
+
90
+ # Extract the actual memory content if it exists and add a prefix
91
+ if existing_memory:
92
+ # Value is a dictionary with a memory key
93
+ existing_memory_content = existing_memory.value.get('memory')
94
+ else:
95
+ existing_memory_content = "No existing memory found."
96
+
97
+
98
+ system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
99
+
100
+ human_template = '''User last reply: {user_reply}'''
101
+ human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
102
+
103
+ chat_prompt = ChatPromptTemplate.from_messages([
104
+ system_message_prompt,
105
+ human_message_prompt
106
+ ])
107
+
108
+ formatted_messages = chat_prompt.format_messages(
109
+ previous_conversation_summary=previous_conversation_summary,
110
+ last_messages = last_messages,
111
+ context = context,
112
+ memory = existing_memory_content,
113
+ user_reply = messages[-1].content
114
+ )
115
+ print('---------Message------', messages)
116
+
117
+ response = llm.invoke(formatted_messages)
118
+
119
+ return {'messages':[response]}
120
+
121
+
122
+ def rewrite_query(state):
123
+
124
+ print("----REWRITE QUERY----")
125
+ previous_summary = state['summary']
126
+ last_messages=state["history"][-4:]
127
+ sys_msg_query = '''TASK: Rewrite the user's query to improve retrieval performance.
128
+ CONTEXT:
129
+ - Conversation Summary: {previous_summary}
130
+ - User's Last Message: {last_messages}
131
+
132
+ INSTRUCTIONS:
133
+ 1. Identify the core information need in the user's message
134
+ 2. Extract key entities, concepts, and relationships
135
+ 3. Add relevant context from the conversation summary
136
+ 4. Remove conversational fillers and ambiguous references
137
+ 5. Use specific terminology that would match relevant documents
138
+ 6. Expand abbreviations and clarify ambiguous terms
139
+ 7. Format as a concise, search-optimized query
140
+
141
+ Your rewritten query should:
142
+ - Maintain the original intent
143
+ - Be self-contained (not require conversation context to understand)
144
+ - Include specific details that would match relevant documents
145
+ - Be under 100 words
146
+
147
+ OUTPUT FORMAT:
148
+ Rewritten Query: '''
149
+
150
+ rewritten = llm.invoke([SystemMessage(content=sys_msg_query.format(previous_summary=previous_summary,last_messages=last_messages))])
151
+ rewritten_query = rewritten.content
152
+ print('---QUERY---', rewritten_query)
153
+
154
+ return {'query': rewritten_query}
155
+
156
+
157
+ def summary_function(state):
158
+ previous_summary = state['summary']
159
+ last_messages=state["history"][-4:]
160
+
161
+ sys_msg_summary = '''You are an AI that creates concise summaries of chat conversations. When summarizing:
162
+ 1. Capture all named entities (people, organizations, products, locations) and their relationships.
163
+ 2. Preserve explicit information, technical terms, and quantitative data.
164
+ 3. Identify the conversation's intent, requirements, and underlying needs.
165
+ 4. Incorporate previous summaries, resolving contradictions and updating information.
166
+ 5. Structure information logically, omitting small talk while retaining critical details.
167
+
168
+ Your summary should begin with the conversation purpose, include all key points, and end with the conversation outcome or status. Remain neutral and accurate, ensuring someone can understand what happened without reading the entire transcript.
169
+
170
+ Previous summary:
171
+ {previous_summary}
172
+
173
+ Last 4 messages:
174
+ {last_messages}
175
+
176
+ Summary:
177
+
178
+ '''
179
+
180
+ summarised = llm.invoke([SystemMessage(content=sys_msg_summary.format(previous_summary=previous_summary,last_messages=last_messages))])
181
+ summarised_content = summarised.content
182
+ print('SUUUUUUU', summarised_content)
183
+
184
+ return {'summary' : summarised_content}
185
+
186
+
187
+ def summary_or_not(state):
188
+ if len(state['history']) % 4 == 0:
189
+ return True
190
+ else:
191
+ return False
192
+
193
+ def write_memory(state: MessagesState, config: RunnableConfig, store: BaseStore):
194
+
195
+ """Reflect on the chat history and save a memory to the store."""
196
+ CREATE_MEMORY_INSTRUCTION = """"You are collecting information about the user to personalize your responses.
197
+
198
+ CURRENT USER INFORMATION:
199
+ {memory}
200
+
201
+ INSTRUCTIONS:
202
+ 1. Review the chat history below carefully
203
+ 2. Identify new information about the user, such as:
204
+ - Personal details (name, location)
205
+ - Preferences (likes, dislikes)
206
+ - Interests and hobbies
207
+ - Past experiences
208
+ - Goals or future plans
209
+ 3. Merge any new information with existing memory
210
+ 4. Format the memory as a clear, bulleted list
211
+ 5. If new information conflicts with existing memory, keep the most recent version
212
+
213
+ Remember: Only include factual information directly stated by the user. Do not make assumptions or inferences.
214
+
215
+ Based on the chat history below, please update the user information:"""
216
+
217
+ # Get the user ID from the config
218
+ user_id = config["configurable"]["user_id"]
219
+
220
+ # Retrieve existing memory from the store
221
+ namespace = ("memory", user_id)
222
+ existing_memory = store.get(namespace, "user_memory")
223
+
224
+ # Extract the memory
225
+ if existing_memory:
226
+ existing_memory_content = existing_memory.value.get('memory')
227
+ else:
228
+ existing_memory_content = "No existing memory found."
229
+
230
+ # Format the memory in the system prompt
231
+ system_msg = CREATE_MEMORY_INSTRUCTION.format(memory=existing_memory_content)
232
+ new_memory = llm.invoke([SystemMessage(content=system_msg)]+state['messages'])
233
+
234
+ # Overwrite the existing memory in the store
235
+ key = "user_memory"
236
+
237
+ # Write value as a dictionary with a memory key
238
+ store.put(namespace, key, {"memory": new_memory.content})
239
+
240
+
241
+ def retrieve_or_not(state) -> Literal["yes", "no"]:
242
+
243
+ print("----RETREIVE or NOT----")
244
+ messages = state["messages"]
245
+ previous_summary = state['summary']
246
+ last_messages=state["history"][-4:]
247
+ user_reply = messages[-1].content
248
+
249
+ sys_msg = '''You are a specialized decision-making system that evaluates whether retrieval is needed for the current conversation.
250
+
251
+ Your only task is to determine if external information retrieval is necessary based on:
252
+ 1. The user's most recent message
253
+ 2. Recent conversation turns (if provided)
254
+ 3. Conversation summary (if provided)
255
+
256
+ **You MUST respond ONLY with "yes" or "no".**
257
+
258
+ Guidelines for your decision:
259
+ - Reply "yes" if:
260
+ - The query requests specific factual information (dates, statistics, events, etc.)
261
+ - The query asks about real-world entities, events, or concepts that require precise information
262
+ - The query references documents or data that would need to be retrieved
263
+ - The query asks about recent or current events that may not be in your training data
264
+ - The query explicitly asks for citations, references, or sources
265
+ - The query contains specific dates, locations, or proper nouns that might require additional context
266
+ - The query appears to be searching for specific information
267
+
268
+ - Reply "no" if:
269
+ - The query is a clarification about something previously explained
270
+ - The query asks for creative content (stories, poems, etc.)
271
+ - The query asks for general advice or opinions
272
+ - The query is conversational in nature (greetings, thanks, etc.)
273
+ - The query is about general concepts that don't require specific factual information
274
+ - The query can be sufficiently answered with your existing knowledge
275
+ - The query is a simple follow-up that doesn't introduce new topics requiring retrieval
276
+
277
+ Remember: Your response must be EXACTLY "yes" or "no" with no additional text, explanation, or punctuation.
278
+ Previous summary: {previous_summary}
279
+ Last 4 messages: {last_messages}
280
+ The user sent the reply as {user_reply}.
281
+ Should we need retrieval: '''
282
+
283
+ class decide(BaseModel):
284
+ '''Decision for retrival - yes or no'''
285
+ decision: str = Field(description="Relevance score 'yes' or 'no'")
286
+
287
+ structured_llm= llm.with_structured_output(decide)
288
+
289
+ retrive_decision = structured_llm.invoke([SystemMessage(content=sys_msg.format(previous_summary=previous_summary,last_messages=last_messages,user_reply=user_reply))])
290
+
291
+ print('-------retrievedecisde---------', retrive_decision)
292
+ if retrive_decision == 'yes':
293
+ return True
294
+
295
+ return False
296
+
297
+ def pass_node(state):
298
+ # Update the fill value
299
+ new_length = len(state["history"])
300
+
301
+ # Return the updated state without making branch decisions
302
+ return {"length": new_length}
303
+
304
+
305
+ def retrieve_docs(state):
306
+ query = state['query']
307
+ retrieved_docs = loaded_db.similarity_search(query=query, k=5)
308
+ return {'context' : retrieved_docs}
309
+
310
+
311
+
312
+
313
+
314
+ workflow = StateGraph(AgentState)
315
+
316
+
317
+ workflow.add_node('assistant', agent)
318
+ workflow.add_node('summary_fn', summary_function)
319
+ workflow.add_node('retrieve_bool', pass_node)
320
+ workflow.add_node('rewrite_query',rewrite_query)
321
+ workflow.add_node('retriever',retrieve_docs)
322
+ workflow.add_node("write_memory", write_memory)
323
+
324
+
325
+ workflow.add_conditional_edges(START, summary_or_not, {True: 'summary_fn', False:'retrieve_bool'})
326
+ workflow.add_edge('summary_fn', 'retrieve_bool')
327
+ workflow.add_conditional_edges('retrieve_bool', retrieve_or_not, {True: 'rewrite_query', False:'write_memory'})
328
+ workflow.add_edge('rewrite_query', 'retriever')
329
+ workflow.add_edge('retriever', 'write_memory')
330
+ workflow.add_edge('write_memory', 'assistant')
331
+ workflow.add_edge('assistant', END)
332
+
333
+ within_thread_memory = MemorySaver()
334
+ across_thread_memory = InMemoryStore()
335
+ chat_graph = workflow.compile(checkpointer=within_thread_memory, store=across_thread_memory)
336
+
337
+
338
+ within_thread_memory = MemorySaver()
339
+ across_thread_memory = InMemoryStore()
340
+ chat_graph = workflow.compile(checkpointer=within_thread_memory, store=across_thread_memory)
341
+
342
+
343
+
344
+ import time
345
+ import gradio as gr
346
+
347
+ def main(conv_history, user_reply):
348
+ # Don't recreate the config each time
349
+ config = {"configurable": {"thread_id": "1", "user_id": "1"}}
350
+
351
+ # Get the current state
352
+ state = chat_graph.get_state(config).values
353
+
354
+ # Initialize state if it doesn't exist yet
355
+ if not state:
356
+ state = {
357
+ 'messages': [],
358
+ 'summary': '',
359
+ 'length': 0
360
+ }
361
+
362
+ # Process the new message using LangGraph
363
+ chat_graph.invoke({
364
+ 'messages': [('user', user_reply)],
365
+ 'history': state['messages'],
366
+ 'summary': state['summary'],
367
+ 'length': state['length'],
368
+ 'context': 'None'
369
+ }, config)
370
+
371
+ # Get the updated state after processing
372
+ output = chat_graph.get_state(config)
373
+ new_messages = output.values['messages']
374
+
375
+ # Initialize conv_history if None
376
+ if conv_history is None:
377
+ conv_history = []
378
+
379
+ # Get the latest bot message
380
+ bot_message = new_messages[-1].content # Get the last message
381
+
382
+ # Stream the response (optional feature)
383
+ streamed_message = ""
384
+ for token in bot_message.split():
385
+ streamed_message += f"{token} "
386
+ yield conv_history + [(user_reply, streamed_message.strip())], " "
387
+ time.sleep(0.05)
388
+
389
+ # Add the final conversation pair to history
390
+ conv_history.append((user_reply, bot_message))
391
+
392
+ yield conv_history, " "
393
+
394
+
395
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
396
+ gr.HTML("<center><h1>FAQ Chatbot! 📂📄</h1><center>")
397
+ gr.Markdown("""##### This AI chatbot🤖 can answer your FAQ questions about """)
398
+
399
+ with gr.Column():
400
+ chatbot = gr.Chatbot(label='ChatBot')
401
+ user_reply = gr.Textbox(label='Enter your query', placeholder='Type here...')
402
+
403
+ with gr.Row():
404
+ submit_button = gr.Button("Submit")
405
+ clear_btn = gr.ClearButton([user_reply, chatbot], value='Clear')
406
+
407
+ # Use the gr.State to store conversation history between refreshes
408
+ state = gr.State([])
409
+
410
+ # Update the click event to include state
411
+ submit_button.click(
412
+ main,
413
+ inputs=[chatbot, user_reply],
414
+ outputs=[chatbot, user_reply]
415
+ )
416
+
417
+ # Add an event handler for the clear button to reset the LangGraph state
418
+ def reset_langgraph_state():
419
+ config = {"configurable": {"thread_id": "1", "user_id": "1"}}
420
+ # Reset the state in LangGraph (if your implementation supports this)
421
+ # If not, you might need to implement a reset method in your graph
422
+ return []
423
+
424
+ clear_btn.click(reset_langgraph_state, inputs=[], outputs=[chatbot])
425
+
426
+ demo.launch()