tomy007 commited on
Commit
67ebc0c
·
verified ·
1 Parent(s): caee3c9

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +720 -0
app.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Import necessary libraries
3
+ import os # Interacting with the operating system (reading/writing files)
4
+ import chromadb # High-performance vector database for storing/querying dense vectors
5
+ from dotenv import load_dotenv # Loading environment variables from a .env file
6
+ import json # Parsing and handling JSON data
7
+
8
+ # LangChain imports
9
+ from langchain_core.documents import Document # Document data structures
10
+ from langchain_core.runnables import RunnablePassthrough # LangChain core library for running pipelines
11
+ from langchain_core.output_parsers import StrOutputParser # String output parser
12
+ from langchain.prompts import ChatPromptTemplate # Template for chat prompts
13
+ from langchain.chains.query_constructor.base import AttributeInfo # Base classes for query construction
14
+ from langchain.retrievers.self_query.base import SelfQueryRetriever # Base classes for self-querying retrievers
15
+ from langchain.retrievers.document_compressors import LLMChainExtractor, CrossEncoderReranker # Document compressors
16
+ from langchain.retrievers import ContextualCompressionRetriever # Contextual compression retrievers
17
+
18
+ # LangChain community & experimental imports
19
+ from langchain_community.vectorstores import Chroma # Implementations of vector stores like Chroma
20
+ from langchain_community.document_loaders import PyPDFDirectoryLoader, PyPDFLoader # Document loaders for PDFs
21
+ from langchain_community.cross_encoders import HuggingFaceCrossEncoder # Cross-encoders from HuggingFace
22
+ from langchain_experimental.text_splitter import SemanticChunker # Experimental text splitting methods
23
+ from langchain.text_splitter import (
24
+ CharacterTextSplitter, # Splitting text by characters
25
+ RecursiveCharacterTextSplitter # Recursive splitting of text by characters
26
+ )
27
+ from langchain_core.tools import tool
28
+ from langchain.agents import create_tool_calling_agent, AgentExecutor
29
+ from langchain_core.prompts import ChatPromptTemplate
30
+
31
+ # LangChain OpenAI imports
32
+ from langchain_openai import AzureOpenAIEmbeddings, AzureChatOpenAI # OpenAI embeddings and models
33
+ from langchain.embeddings.openai import OpenAIEmbeddings # OpenAI embeddings for text vectors
34
+
35
+ # LlamaParse & LlamaIndex imports
36
+ from llama_parse import LlamaParse # Document parsing library
37
+ from llama_index.core import Settings, SimpleDirectoryReader # Core functionalities of the LlamaIndex
38
+
39
+ # LangGraph import
40
+ from langgraph.graph import StateGraph, END, START # State graph for managing states in LangChain
41
+
42
+ # Pydantic import
43
+ from pydantic import BaseModel # Pydantic for data validation
44
+
45
+ # Typing imports
46
+ from typing import Dict, List, Tuple, Any, TypedDict # Python typing for function annotations
47
+
48
+ # Other utilities
49
+ import numpy as np # Numpy for numerical operations
50
+ from groq import Groq
51
+ from mem0 import MemoryClient
52
+ import streamlit as st
53
+ from datetime import datetime
54
+
55
+ #====================================SETUP=====================================#
56
+ # Fetch secrets from Hugging Face Spaces
57
+ api_key = os.environ['OPENAI_API_KEY']
58
+ endpoint = os.environ['OPENAI_API_BASE']
59
+ llama_api_key = os.environ['GROQ_API_KEY']
60
+ MEM0_api_key = os.environ['mem0']
61
+
62
+
63
+ # Initialize the OpenAI embedding function for Chroma
64
+ embedding_function = chromadb.utils.embedding_functions.OpenAIEmbeddingFunction(
65
+ api_base=endpoint,
66
+ api_key=api_key,
67
+ model_name='text-embedding-ada-002'
68
+ )
69
+
70
+ # This initializes the OpenAI embedding function for the Chroma vectorstore, using the provided endpoint and API key.
71
+
72
+ # Initialize the OpenAI Embeddings
73
+ embedding_model = OpenAIEmbeddings(
74
+ openai_api_base=endpoint,
75
+ openai_api_key=api_key,
76
+ model='text-embedding-ada-002'
77
+ )
78
+
79
+
80
+ # Initialize the Chat OpenAI model
81
+ llm = ChatOpenAI(
82
+ openai_api_base=endpoint,
83
+ openai_api_key=api_key,
84
+ model="gpt-4o-mini",
85
+ streaming=False
86
+ )
87
+ # This initializes the Chat OpenAI model with the provided endpoint, API key, deployment name, and a temperature setting of 0 (to control response variability).
88
+
89
+ # set the LLM and embedding model in the LlamaIndex settings.
90
+ Settings.llm = llm
91
+ Settings.embedding = embedding_model
92
+
93
+ #================================Creating Langgraph agent======================#
94
+
95
+ class AgentState(TypedDict):
96
+ query: str # The current user query
97
+ expanded_query: str # The expanded version of the user query
98
+ context: List[Dict[str, Any]] # Retrieved documents (content and metadata)
99
+ response: str # The generated response to the user query
100
+ precision_score: float # The precision score of the response
101
+ groundedness_score: float # The groundedness score of the response
102
+ groundedness_loop_count: int # Counter for groundedness refinement loops
103
+ precision_loop_count: int # Counter for precision refinement loops
104
+ feedback: str
105
+ query_feedback: str
106
+ groundedness_check: bool
107
+ loop_max_iter: int
108
+
109
+ def expand_query(state):
110
+ """
111
+ Expands the user query to improve retrieval of nutrition disorder-related information.
112
+
113
+ Args:
114
+ state (Dict): The current state of the workflow, containing the user query.
115
+
116
+ Returns:
117
+ Dict: The updated state with the expanded query.
118
+ """
119
+ print("---------Expanding Query---------")
120
+ system_message = '''You are a helpful assistant that expands nutrition-related questions to include relevant keywords, concepts, and related conditions for better information retrieval from a nutritional medical reference. For example, if the user asks about "rickets", you might expand the query to include terms like "vitamin D deficiency", "bone health in children", "calcium metabolism", or "treatment of rickets". Ensure the expanded query remains focused on the original intent but covers a broader range of related terms to improve search results.'''
121
+
122
+
123
+ expand_prompt = ChatPromptTemplate.from_messages([
124
+ ("system", system_message),
125
+ ("user", "Expand this query: {query} using the feedback: {query_feedback}")
126
+
127
+ ])
128
+
129
+ chain = expand_prompt | llm | StrOutputParser()
130
+ expanded_query = chain.invoke({"query": state['query'], "query_feedback":state["query_feedback"]})
131
+ print("expanded_query", expanded_query)
132
+ state["expanded_query"] = expanded_query
133
+ return state
134
+
135
+
136
+ # Initialize the Chroma vector store for retrieving documents
137
+ vector_store = Chroma(
138
+ collection_name="nutritional_hypotheticals",
139
+ persist_directory="./nutritional_db",
140
+ embedding_function=embedding_model
141
+
142
+ )
143
+
144
+ # Create a retriever from the vector store
145
+ retriever = vector_store.as_retriever(
146
+ search_type='similarity',
147
+ search_kwargs={'k': 3}
148
+ )
149
+
150
+ def retrieve_context(state):
151
+ """
152
+ Retrieves context from the vector store using the expanded or original query.
153
+
154
+ Args:
155
+ state (Dict): The current state of the workflow, containing the query and expanded query.
156
+
157
+ Returns:
158
+ Dict: The updated state with the retrieved context.
159
+ """
160
+ print("---------retrieve_context---------")
161
+ query = state['expanded_query']
162
+ #print("Query used for retrieval:", query) # Debugging: Print the query
163
+
164
+ # Retrieve documents from the vector store
165
+ docs = retriever.invoke(query)
166
+ print("Retrieved documents:", docs) # Debugging: Print the raw docs object
167
+
168
+ # Extract both page_content and metadata from each document
169
+ context= [
170
+ {
171
+ "content": doc.page_content, # The actual content of the document
172
+ "metadata": doc.metadata # The metadata (e.g., source, page number, etc.)
173
+ }
174
+ for doc in docs
175
+ ]
176
+ state['context'] = context
177
+ print("Extracted context with metadata:", context) # Debugging: Print the extracted context
178
+ #print(f"Groundedness loop count: {state['groundedness_loop_count']}")
179
+ return state
180
+
181
+
182
+
183
+ def craft_response(state: Dict) -> Dict:
184
+ """
185
+ Generates a response using the retrieved context, focusing on nutrition disorders.
186
+
187
+ Args:
188
+ state (Dict): The current state of the workflow, containing the query and retrieved context.
189
+
190
+ Returns:
191
+ Dict: The updated state with the generated response.
192
+ """
193
+ print("---------craft_response---------")
194
+ system_message = '''You are a helpful and informative AI assistant specialized in providing information about nutrition disorders based on the provided context. Use the context to answer the user's query accurately and comprehensively. If the context does not contain enough information to answer the query, state that you cannot provide a complete answer based on the available information. Always prioritize information from the context and avoid making up information.'''
195
+
196
+ response_prompt = ChatPromptTemplate.from_messages([
197
+ ("system", system_message),
198
+ ("user", "Query: {query}\nContext: {context}\n\nfeedback: {feedback}")
199
+ ])
200
+
201
+ chain = response_prompt | llm
202
+ response = chain.invoke({
203
+ "query": state['query'],
204
+ "context": "\n".join([doc["content"] for doc in state['context']]),
205
+ "feedback": state.get('feedback', '') # add feedback to the prompt
206
+ })
207
+ state['response'] = response
208
+ print("intermediate response: ", response)
209
+
210
+ return state
211
+
212
+
213
+
214
+ def score_groundedness(state: Dict) -> Dict:
215
+ """
216
+ Checks whether the response is grounded in the retrieved context.
217
+
218
+ Args:
219
+ state (Dict): The current state of the workflow, containing the response and context.
220
+
221
+ Returns:
222
+ Dict: The updated state with the groundedness score.
223
+ """
224
+ print("---------check_groundedness---------")
225
+ system_message = '''You are an AI assistant that evaluates how well a generated response is supported by the provided context. Your task is to assign a groundedness score between 0 and 1, where 1 means the response is fully supported by the context and 0 means it is not supported at all. Consider if the response introduces information not present in the context or contradicts the context. Provide only the numerical score.'''
226
+
227
+ groundedness_prompt = ChatPromptTemplate.from_messages([
228
+ ("system", system_message),
229
+ ("user", "Context: {context}\nResponse: {response}\n\nGroundedness score:")
230
+ ])
231
+
232
+ chain = groundedness_prompt | llm | StrOutputParser()
233
+ groundedness_score = float(chain.invoke({
234
+ "context": "\n".join([doc["content"] for doc in state['context']]),
235
+ "response": state['response']
236
+ }))
237
+ print("groundedness_score: ", groundedness_score)
238
+ state['groundedness_loop_count'] += 1
239
+ print("#########Groundedness Incremented###########")
240
+ state['groundedness_score'] = groundedness_score
241
+
242
+ return state
243
+
244
+
245
+
246
+ def check_precision(state: Dict) -> Dict:
247
+ """
248
+ Checks whether the response precisely addresses the user’s query.
249
+
250
+ Args:
251
+ state (Dict): The current state of the workflow, containing the query and response.
252
+
253
+ Returns:
254
+ Dict: The updated state with the precision score.
255
+ """
256
+ print("---------check_precision---------")
257
+ system_message = '''You are an AI assistant that evaluates how well a generated response precisely addresses the user's query. Your task is to assign a precision score between 0 and 1, where 1 means the response is a precise answer to the query and 0 means it is not precise at all. Consider if the response directly answers the question and provides the specific information requested. Provide only the numerical score.'''
258
+
259
+ precision_prompt = ChatPromptTemplate.from_messages([
260
+ ("system", system_message),
261
+ ("user", "Query: {query}\nResponse: {response}\n\nPrecision score:")
262
+ ])
263
+
264
+ chain = precision_prompt | llm | StrOutputParser()
265
+ precision_score = float(chain.invoke({
266
+ "query": state['query'],
267
+ "response": state['response']
268
+ }))
269
+ state['precision_score'] = precision_score
270
+ state['precision_loop_count'] +=1
271
+ print("#########Precision Incremented###########")
272
+ return state
273
+
274
+
275
+
276
+ def refine_response(state: Dict) -> Dict:
277
+ """
278
+ Suggests improvements for the generated response.
279
+
280
+ Args:
281
+ state (Dict): The current state of the workflow, containing the query and response.
282
+
283
+ Returns:
284
+ Dict: The updated state with response refinement suggestions.
285
+ """
286
+ print("---------refine_response---------")
287
+
288
+ system_message = '''You are an AI assistant that provides constructive feedback on a generated response to a user's query about nutrition disorders. Your goal is to identify any gaps, ambiguities, or missing details in the response when compared to the original query and the retrieved context. Do not rewrite the response, but suggest specific improvements that could enhance its accuracy, completeness, and relevance to the user's question. Focus on factual correctness and adherence to the provided context.'''
289
+
290
+ refine_response_prompt = ChatPromptTemplate.from_messages([
291
+ ("system", system_message),
292
+ ("user", "Query: {query}\nResponse: {response}\n\n"
293
+ "What improvements can be made to enhance accuracy and completeness?")
294
+ ])
295
+
296
+ chain = refine_response_prompt | llm| StrOutputParser()
297
+
298
+ # Store response suggestions in a structured format
299
+ feedback = f"Previous Response: {state['response']}\nSuggestions: {chain.invoke({'query': state['query'], 'response': state['response']})}"
300
+ print("feedback: ", feedback)
301
+ print(f"State: {state}")
302
+ state['feedback'] = feedback
303
+ return state
304
+
305
+
306
+
307
+ def refine_query(state: Dict) -> Dict:
308
+ """
309
+ Suggests improvements for the expanded query.
310
+
311
+ Args:
312
+ state (Dict): The current state of the workflow, containing the query and expanded query.
313
+
314
+ Returns:
315
+ Dict: The updated state with query refinement suggestions.
316
+ """
317
+ print("---------refine_query---------")
318
+ system_message = '''You are an AI assistant that provides constructive feedback on an expanded user query for nutrition disorders. Your goal is to identify any missing details, specific keywords, or scope refinements that can enhance search precision in a nutritional medical reference. Suggest specific improvements that could lead to better retrieval of relevant information.'''
319
+
320
+ refine_query_prompt = ChatPromptTemplate.from_messages([
321
+ ("system", system_message),
322
+ ("user", "Original Query: {query}\nExpanded Query: {expanded_query}\n\n"
323
+ "What improvements can be made for a better search?")
324
+ ])
325
+
326
+ chain = refine_query_prompt | llm | StrOutputParser()
327
+
328
+ # Store refinement suggestions without modifying the original expanded query
329
+ query_feedback = f"Previous Expanded Query: {state['expanded_query']}\nSuggestions: {chain.invoke({'query': state['query'], 'expanded_query': state['expanded_query']})}"
330
+ print("query_feedback: ", query_feedback)
331
+ print(f"Groundedness loop count: {state['groundedness_loop_count']}")
332
+ state['query_feedback'] = query_feedback
333
+ return state
334
+
335
+
336
+
337
+ def should_continue_groundedness(state):
338
+ """Decides if groundedness is sufficient or needs improvement."""
339
+ print("---------should_continue_groundedness---------")
340
+ print("groundedness loop count: ", state['groundedness_loop_count'])
341
+ if state['groundedness_score'] >= 0.7: # Threshold for groundedness
342
+ print("Moving to precision")
343
+ return "check_precision"
344
+ else:
345
+ if state["groundedness_loop_count"] > state['loop_max_iter']:
346
+ return "max_iterations_reached"
347
+ else:
348
+ print(f"---------Groundedness Score Threshold Not met. Refining Response-----------")
349
+ return "refine_response"
350
+
351
+
352
+ def should_continue_precision(state: Dict) -> str:
353
+ """Decides if precision is sufficient or needs improvement."""
354
+ print("---------should_continue_precision---------")
355
+ print("precision loop count: ", state['precision_loop_count'])
356
+ if state['precision_score'] > 0.7: # Threshold for precision
357
+ return "pass" # Complete the workflow
358
+ else:
359
+ if state['precision_loop_count'] >= state['loop_max_iter']: # Maximum allowed loops
360
+ return "max_iterations_reached"
361
+ else:
362
+ print(f"---------Precision Score Threshold Not met. Refining Query-----------") # Debugging
363
+ return "refine_query" # Refine the query
364
+
365
+
366
+
367
+
368
+ def max_iterations_reached(state: Dict) -> Dict:
369
+ """Handles the case when the maximum number of iterations is reached."""
370
+ print("---------max_iterations_reached---------")
371
+ """Handles the case when the maximum number of iterations is reached."""
372
+ response = "I'm unable to refine the response further. Please provide more context or clarify your question."
373
+ state['response'] = response
374
+ return state
375
+
376
+
377
+
378
+ from langgraph.graph import END, StateGraph, START
379
+
380
+ def create_workflow() -> StateGraph:
381
+ """Creates the updated workflow for the AI nutrition agent."""
382
+ workflow = StateGraph(AgentState)
383
+
384
+ # Add processing nodes
385
+ workflow.add_node("expand_query", expand_query)
386
+ workflow.add_node("retrieve_context", retrieve_context)
387
+ workflow.add_node("craft_response", craft_response)
388
+ workflow.add_node("score_groundedness", score_groundedness)
389
+ workflow.add_node("refine_response", refine_response)
390
+ workflow.add_node("check_precision", check_precision)
391
+ workflow.add_node("refine_query", refine_query)
392
+ workflow.add_node("max_iterations_reached", max_iterations_reached)
393
+
394
+ # Main flow edges
395
+ workflow.add_edge(START, "expand_query")
396
+ workflow.add_edge("expand_query", "retrieve_context")
397
+ workflow.add_edge("retrieve_context", "craft_response")
398
+ workflow.add_edge("craft_response", "score_groundedness")
399
+
400
+ # Conditional edges based on groundedness check
401
+ workflow.add_conditional_edges(
402
+ "score_groundedness",
403
+ should_continue_groundedness,
404
+ {
405
+ "check_precision": "check_precision",
406
+ "refine_response": "refine_response",
407
+ "max_iterations_reached": "max_iterations_reached"
408
+ }
409
+ )
410
+
411
+ workflow.add_edge("refine_response", "craft_response")
412
+
413
+ # Conditional edges based on precision check
414
+ workflow.add_conditional_edges(
415
+ "check_precision",
416
+ should_continue_precision,
417
+ {
418
+ "pass": END,
419
+ "refine_query": "refine_query",
420
+ "max_iterations_reached": "max_iterations_reached"
421
+ }
422
+ )
423
+
424
+ workflow.add_edge("refine_query", "expand_query")
425
+
426
+ workflow.add_edge("max_iterations_reached", END)
427
+
428
+ return workflow
429
+
430
+
431
+
432
+
433
+ #=========================== Defining the agentic rag tool ====================#
434
+ WORKFLOW_APP = create_workflow().compile()
435
+ @tool
436
+ def agentic_rag(query: str):
437
+ """
438
+ Runs the RAG-based agent with conversation history for context-aware responses.
439
+
440
+ Args:
441
+ query (str): The current user query.
442
+
443
+ Returns:
444
+ Dict[str, Any]: The updated state with the generated response and conversation history.
445
+ """
446
+ # Initialize state with necessary parameters
447
+ inputs = {
448
+ "query": query, # Current user query
449
+ "expanded_query": "",
450
+ "context": [],
451
+ "response": "",
452
+ "precision_score": 0.0,
453
+ "groundedness_score": 0.0,
454
+ "groundedness_loop_count": 0,
455
+ "precision_loop_count": 0,
456
+ "feedback": "",
457
+ "query_feedback": "",
458
+ "loop_max_iter": 3
459
+ }
460
+
461
+ output = WORKFLOW_APP.invoke(inputs)
462
+
463
+ return output
464
+
465
+
466
+ #================================ Guardrails ===========================#
467
+ llama_guard_client = Groq(api_key=llama_api_key)
468
+ # Function to filter user input with Llama Guard
469
+ def filter_input_with_llama_guard(user_input, model="llama-guard-3-8b"):
470
+ """
471
+ Filters user input using Llama Guard to ensure it is safe.
472
+
473
+ Parameters:
474
+ - user_input: The input provided by the user.
475
+ - model: The Llama Guard model to be used for filtering (default is "llama-guard-3-8b").
476
+
477
+ Returns:
478
+ - The filtered and safe input.
479
+ """
480
+ try:
481
+ # Create a request to Llama Guard to filter the user input
482
+ response = llama_guard_client.chat.completions.create(
483
+ messages=[{"role": "user", "content": user_input}],
484
+ model=model,
485
+ )
486
+ # Return the filtered input
487
+ return response.choices[0].message.content.strip()
488
+ except Exception as e:
489
+ print(f"Error with Llama Guard: {e}")
490
+ return None
491
+
492
+
493
+ #============================= Adding Memory to the agent using mem0 ===============================#
494
+
495
+ class NutritionBot:
496
+ def __init__(self):
497
+ """
498
+ Initialize the NutritionBot class, setting up memory, the LLM client, tools, and the agent executor.
499
+ """
500
+
501
+ # Initialize a memory client to store and retrieve customer interactions
502
+ self.memory = MemoryClient(api_key=MEM0_api_key)
503
+
504
+ # Initialize the OpenAI client using the provided credentials
505
+ self.client = ChatOpenAI(
506
+ model_name="gpt-4o-mini",
507
+ api_key=api_key,
508
+ openai_api_base = endpoint,
509
+ temperature=0
510
+ )
511
+
512
+ # Define tools available to the chatbot, such as web search
513
+ tools = [agentic_rag]
514
+
515
+ # Define the system prompt to set the behavior of the chatbot
516
+ system_prompt = """You are a caring and knowledgeable Medical Support Agent, specializing in nutrition disorder-related guidance. Your goal is to provide accurate, empathetic, and tailored nutritional recommendations while ensuring a seamless customer experience.
517
+ Guidelines for Interaction:
518
+ Maintain a polite, professional, and reassuring tone.
519
+ Show genuine empathy for customer concerns and health challenges.
520
+ Reference past interactions to provide personalized and consistent advice.
521
+ Engage with the customer by asking about their food preferences, dietary restrictions, and lifestyle before offering recommendations.
522
+ Ensure consistent and accurate information across conversations.
523
+ If any detail is unclear or missing, proactively ask for clarification.
524
+ Always use the agentic_rag tool to retrieve up-to-date and evidence-based nutrition insights.
525
+ Keep track of ongoing issues and follow-ups to ensure continuity in support.
526
+ Your primary goal is to help customers make informed nutrition decisions that align with their health conditions and personal preferences.
527
+
528
+ """
529
+
530
+ # Build the prompt template for the agent
531
+ prompt = ChatPromptTemplate.from_messages([
532
+ ("system", system_prompt),
533
+ ("human", "{input}"),
534
+ ("placeholder", "{agent_scratchpad}")
535
+ ])
536
+
537
+ # Create an agent capable of interacting with tools and executing tasks
538
+ agent = create_tool_calling_agent(self.client, tools, prompt)
539
+
540
+ # Wrap the agent in an executor to manage tool interactions and execution flow
541
+ self.agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
542
+
543
+
544
+ def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):
545
+ """
546
+ Store customer interaction in memory for future reference.
547
+
548
+ Args:
549
+ user_id (str): Unique identifier for the customer.
550
+ message (str): Customer's query or message.
551
+ response (str): Chatbot's response.
552
+ metadata (Dict, optional): Additional metadata for the interaction.
553
+ """
554
+ if metadata is None:
555
+ metadata = {}
556
+
557
+ # Add a timestamp to the metadata for tracking purposes
558
+ metadata["timestamp"] = datetime.now().isoformat()
559
+
560
+ # Format the conversation for storage
561
+ conversation = [
562
+ {"role": "user", "content": message},
563
+ {"role": "assistant", "content": response}
564
+ ]
565
+
566
+ # Store the interaction in the memory client
567
+ self.memory.add(
568
+ conversation,
569
+ user_id=user_id,
570
+ output_format="v1.1",
571
+ metadata=metadata
572
+ )
573
+
574
+
575
+ def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:
576
+ """
577
+ Retrieve past interactions relevant to the current query.
578
+
579
+ Args:
580
+ user_id (str): Unique identifier for the customer.
581
+ query (str): The customer's current query.
582
+
583
+ Returns:
584
+ List[Dict]: A list of relevant past interactions.
585
+ """
586
+ return self.memory.search(
587
+ query=query, # Search for interactions related to the query
588
+ user_id=user_id, # Restrict search to the specific user
589
+ limit=5 # Set a limit for retrieved interactions
590
+ )
591
+
592
+
593
+ def handle_customer_query(self, user_id: str, query: str) -> str:
594
+ """
595
+ Process a customer's query and provide a response, taking into account past interactions.
596
+
597
+ Args:
598
+ user_id (str): Unique identifier for the customer.
599
+ query (str): Customer's query.
600
+
601
+ Returns:
602
+ str: Chatbot's response.
603
+ """
604
+
605
+ # Retrieve relevant past interactions for context
606
+ relevant_history = self.get_relevant_history(user_id, query)
607
+
608
+ # Build a context string from the relevant history
609
+ context = "Previous relevant interactions:\n"
610
+ for memory in relevant_history:
611
+ context += f"Customer: {memory['memory']}\n" # Customer's past messages
612
+ context += f"Support: {memory['memory']}\n" # Chatbot's past responses
613
+ context += "---\n"
614
+
615
+ # Print context for debugging purposes
616
+ print("Context: ", context)
617
+
618
+ # Prepare a prompt combining past context and the current query
619
+ prompt = f"""
620
+ Context:
621
+ {context}
622
+
623
+ Current customer query: {query}
624
+
625
+ Provide a helpful response that takes into account any relevant past interactions.
626
+ """
627
+
628
+ # Generate a response using the agent
629
+ response = self.agent_executor.invoke({"input": prompt})
630
+
631
+ # Store the current interaction for future reference
632
+ self.store_customer_interaction(
633
+ user_id=user_id,
634
+ message=query,
635
+ response=response["output"],
636
+ metadata={"type": "support_query"}
637
+ )
638
+
639
+ # Return the chatbot's response
640
+ return response['output']
641
+
642
+
643
+ #=====================User Interface using streamlit ===========================#
644
+ def nutrition_disorder_streamlit():
645
+ """
646
+ A Streamlit-based UI for the Nutrition Disorder Specialist Agent.
647
+ """
648
+ st.title("Nutrition Disorder Specialist")
649
+ st.write("Ask me anything about nutrition disorders, symptoms, causes, treatments, and more.")
650
+ st.write("Type 'exit' to end the conversation.")
651
+
652
+ # Initialize session state for chat history and user_id if they don't exist
653
+ if 'chat_history' not in st.session_state:
654
+ st.session_state.chat_history = []
655
+ if 'user_id' not in st.session_state:
656
+ st.session_state.user_id = None
657
+
658
+ # Login form: Only if user is not logged in
659
+ if st.session_state.user_id is None:
660
+ with st.form("login_form", clear_on_submit=True):
661
+ user_id = st.text_input("Please enter your name to begin:")
662
+ submit_button = st.form_submit_button("Login")
663
+ if submit_button and user_id:
664
+ st.session_state.user_id = user_id
665
+ st.session_state.chat_history.append({
666
+ "role": "assistant",
667
+ "content": f"Welcome, {user_id}! How can I help you with nutrition disorders today?"
668
+ })
669
+ st.session_state.login_submitted = True # Set flag to trigger rerun
670
+ if st.session_state.get("login_submitted", False):
671
+ st.session_state.pop("login_submitted")
672
+ st.rerun()
673
+ else:
674
+ # Display chat history
675
+ for message in st.session_state.chat_history:
676
+ with st.chat_message(message["role"]):
677
+ st.write(message["content"])
678
+
679
+ # Chat input with custom placeholder text
680
+ user_query = st.chat_input("Type your question here (or 'exit' to end)...")
681
+ if user_query:
682
+ if user_query.lower() == "exit":
683
+ st.session_state.chat_history.append({"role": "user", "content": "exit"})
684
+ with st.chat_message("user"):
685
+ st.write("exit")
686
+ goodbye_msg = "Goodbye! Feel free to return if you have more questions about nutrition disorders."
687
+ st.session_state.chat_history.append({"role": "assistant", "content": goodbye_msg})
688
+ with st.chat_message("assistant"):
689
+ st.write(goodbye_msg)
690
+ st.session_state.user_id = None
691
+ st.rerun()
692
+ return
693
+
694
+ st.session_state.chat_history.append({"role": "user", "content": user_query})
695
+ with st.chat_message("user"):
696
+ st.write(user_query)
697
+
698
+ # Filter input using Llama Guard
699
+ filtered_result = filter_input_with_llama_guard(user_query)
700
+ filtered_result = filtered_result.replace("\n", " ") # Normalize the result
701
+
702
+ # Check if input is safe based on allowed statuses
703
+ if filtered_result in ["SAFE", "UNSAFE S7", "UNSAFE S6"]:
704
+ try:
705
+ if 'chatbot' not in st.session_state:
706
+ st.session_state.chatbot = NutritionBot()
707
+ response = st.session_state.chatbot.handle_customer_query(st.session_state.user_id, user_query)
708
+ st.write(response)
709
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
710
+ except Exception as e:
711
+ error_msg = f"Sorry, I encountered an error while processing your query. Please try again. Error: {str(e)}"
712
+ st.write(error_msg)
713
+ st.session_state.chat_history.append({"role": "assistant", "content": error_msg})
714
+ else:
715
+ inappropriate_msg = "I apologize, but I cannot process that input as it may be inappropriate. Please try again."
716
+ st.write(inappropriate_msg)
717
+ st.session_state.chat_history.append({"role": "assistant", "content": inappropriate_msg})
718
+
719
+ if __name__ == "__main__":
720
+ nutrition_disorder_streamlit()