prernasingh commited on
Commit
be1e12d
·
verified ·
1 Parent(s): ea89755

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +784 -0
app.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = config.get("API_KEY")
58
+ # endpoint = config.get("OPENAI_API_BASE")
59
+ api_key = os.environ['API_KEY']
60
+ endpoint = os.environ['OPENAI_API_BASE']
61
+ llama_api_key = os.environ['GROQ_API_KEY']
62
+ MEM0_api_key = os.environ['MEM0_API_KEY']
63
+
64
+ # Initialize the OpenAI embedding function for Chroma
65
+ embedding_function = chromadb.utils.embedding_functions.OpenAIEmbeddingFunction(
66
+ api_base=endpoint, # Complete the code to define the API base endpoint
67
+ api_key=api_key, # Complete the code to define the API key
68
+ model_name='text-embedding-ada-002' # This is a fixed value and does not need modification
69
+ )
70
+
71
+ # This initializes the OpenAI embedding function for the Chroma vectorstore, using the provided endpoint and API key.
72
+
73
+ # Initialize the OpenAI Embeddings
74
+ embedding_model = OpenAIEmbeddings(
75
+ openai_api_base=endpoint,
76
+ openai_api_key=api_key,
77
+ model='text-embedding-ada-002'
78
+ )
79
+
80
+
81
+ # Initialize the Chat OpenAI model
82
+ llm = ChatOpenAI(
83
+ openai_api_base=endpoint,
84
+ openai_api_key=api_key,
85
+ model="gpt-4o-mini",
86
+ streaming=False
87
+ )
88
+ # This initializes the Chat OpenAI model with the provided endpoint, API key, deployment name, and a temperature setting of 0 (to control response variability).
89
+
90
+ # set the LLM and embedding model in the LlamaIndex settings.
91
+ Settings.llm = llm # Complete the code to define the LLM model
92
+ Settings.embedding = embedding_model # Complete the code to define the embedding model
93
+
94
+ #================================Creating Langgraph agent======================#
95
+
96
+ class AgentState(TypedDict):
97
+ query: str # The current user query
98
+ expanded_query: str # The expanded version of the user query
99
+ context: List[Dict[str, Any]] # Retrieved documents (content and metadata)
100
+ response: str # The generated response to the user query
101
+ precision_score: float # The precision score of the response
102
+ groundedness_score: float # The groundedness score of the response
103
+ groundedness_loop_count: int # Counter for groundedness refinement loops
104
+ precision_loop_count: int # Counter for precision refinement loops
105
+ feedback: str
106
+ query_feedback: str
107
+ groundedness_check: bool
108
+ loop_max_iter: int
109
+
110
+ def expand_query(state):
111
+ """
112
+ Expands the user query to improve retrieval of nutrition disorder-related information.
113
+
114
+ Args:
115
+ state (Dict): The current state of the workflow, containing the user query.
116
+
117
+ Returns:
118
+ Dict: The updated state with the expanded query.
119
+ """
120
+ print("---------Expanding Query---------")
121
+ system_message = '''You an expert medical assistant in answering questions to questions related to Nutritional Disorders.
122
+ Your goal is to specialize in improving search queries enable healthcare providers to access information regarding symptoms, prognosis, diagnoses, treatment plans.
123
+ Perform query expansion on the questions received.
124
+ If you are not familiar with the answer, mention - I don't know the answer.
125
+ Just answer the question. Do not try to just rephrase the question.'''
126
+
127
+
128
+ expand_prompt = ChatPromptTemplate.from_messages([
129
+ ("system", system_message),
130
+ ("user", "Expand this query: {query} using the feedback: {query_feedback}")
131
+
132
+ ])
133
+
134
+ chain = expand_prompt | llm | StrOutputParser()
135
+ expanded_query = chain.invoke({"query": state['query'], "query_feedback":state["query_feedback"]})
136
+ print("expanded_query", expanded_query)
137
+ state["expanded_query"] = expanded_query
138
+ return state
139
+
140
+
141
+ # Initialize the Chroma vector store for retrieving documents
142
+ vector_store = Chroma(
143
+ collection_name="nutritional_hypotheticals",
144
+ persist_directory="/nutritional_db",
145
+ embedding_function=embedding_model
146
+
147
+ )
148
+
149
+ # Create a retriever from the vector store
150
+ retriever = vector_store.as_retriever(
151
+ search_type='similarity',
152
+ search_kwargs={'k': 3}
153
+ )
154
+
155
+ def retrieve_context(state):
156
+ """
157
+ Retrieves context from the vector store using the expanded or original query.
158
+
159
+ Args:
160
+ state (Dict): The current state of the workflow, containing the query and expanded query.
161
+
162
+ Returns:
163
+ Dict: The updated state with the retrieved context.
164
+ """
165
+ print("---------retrieve_context---------")
166
+ query = state['expanded_query'] # Complete the code to define the key for the expanded query
167
+ #print("Query used for retrieval:", query) # Debugging: Print the query
168
+
169
+ # Retrieve documents from the vector store
170
+ docs = retriever.invoke(query)
171
+ print("Retrieved documents:", docs) # Debugging: Print the raw docs object
172
+
173
+ # Extract both page_content and metadata from each document
174
+ context= [
175
+ {
176
+ "content": doc.page_content, # The actual content of the document
177
+ "metadata": doc.metadata # The metadata (e.g., source, page number, etc.)
178
+ }
179
+ for doc in docs
180
+ ]
181
+ state['context'] = context # Complete the code to define the key for storing the context
182
+ print("Extracted context with metadata:", context) # Debugging: Print the extracted context
183
+ #print(f"Groundedness loop count: {state['groundedness_loop_count']}")
184
+ return state
185
+
186
+
187
+
188
+ def craft_response(state: Dict) -> Dict:
189
+ """
190
+ Generates a response using the retrieved context, focusing on nutrition disorders.
191
+
192
+ Args:
193
+ state (Dict): The current state of the workflow, containing the query and retrieved context.
194
+
195
+ Returns:
196
+ Dict: The updated state with the generated response.
197
+ """
198
+ print("---------craft_response---------")
199
+ system_message = '''You an expert medical assistant in answering questions to questions related to Nutritional Disorders.
200
+ Your goal is to specialize in improving search queries enable healthcare providers to access information regarding symptoms, prognosis, diagnoses, treatment plans based on nutritional disorder.
201
+ Questions are specific to Nutritional disorders, dietary deficiencies, metabolic disorders, vitamin and mineral imbalances, obesity, and related health conditions. The answer you provide must come from the information provided above.
202
+ Example:
203
+
204
+ user_input_example1 = """
205
+ What is Pathophysiology?
206
+ """
207
+ assistant_output_example1 = """ The initial metabolic response is decreased metabolic rate. To supply energy, the body first breaks down adipose tissue. However, later when these tissues are depleted, the body may use protein for energy, resulting in a negative nitrogen balance. Visceral organs and muscle are broken down and decrease in
208
+ weight. Loss of organ weight is greatest in the liver and intestine, intermediate in the heart and kidneys, and least in the nervous system
209
+ """
210
+ user_input_example2 = """
211
+ what is Protein-Energy Undernutrition?
212
+ """
213
+ assistant_output_example2 = """
214
+ Protein-energy undernutrition (PEU), previously called protein-energy malnutrition, is an energy deficit due to chronic deficiency of all macronutrients. It commonly includes deficiencies of
215
+ many micronutrients. PEU can be sudden and total (starvation) or gradual. Severity ranges from subclinical deficiencies to obvious wasting (with edema, hair loss, and skin atrophy) to starvation. Multiple organ systems are often impaired. Diagnosis usually involves laboratory
216
+ testing, including serum albumin. Treatment consists of correcting fluid and electrolyte deficits with IV solutions, then gradually replenishing nutrients, orally if possible.'''
217
+
218
+ response_prompt = ChatPromptTemplate.from_messages([
219
+ ("system", system_message),
220
+ ("user", "Query: {query}\nContext: {context}\n\nfeedback: {feedback}")
221
+ ])
222
+
223
+ chain = response_prompt | llm
224
+ response = chain.invoke({
225
+ "query": state['query'],
226
+ "context": "\n".join([doc["content"] for doc in state['context']]),
227
+ "feedback": state['feedback'] # add feedback to the prompt
228
+ })
229
+ state['response'] = response
230
+ print("intermediate response: ", response)
231
+
232
+ return state
233
+
234
+
235
+
236
+ def score_groundedness(state: Dict) -> Dict:
237
+ """
238
+ Checks whether the response is grounded in the retrieved context.
239
+
240
+ Args:
241
+ state (Dict): The current state of the workflow, containing the response and context.
242
+
243
+ Returns:
244
+ Dict: The updated state with the groundedness score.
245
+ """
246
+ print("---------check_groundedness---------")
247
+ system_message = '''Given the context and the response, score the response's groundedness,
248
+ which represents its factual alignment with the context.
249
+ A score of 1.0 represents perfect alignment with the context,
250
+ while a score of 0.0 represents a complete lack of alignment.
251
+
252
+ Context: {context}
253
+
254
+ Response: {response}
255
+
256
+ ## Instructions:
257
+ - Please provide a groundedness score.
258
+ - The groundedness score should be a floating point number between 0.0 and 1.0 inclusive.
259
+ - Please focus on evaluating the factual consistency and support for the claims
260
+ in the response with information provided in the context.
261
+ - If the response introduces or hallucinates information not found in the context,
262
+ consider it as evidence for a lower score.
263
+ - If any facts presented in the response are contradicted or unsupported by the context,
264
+ consider it as evidence for a lower score.
265
+
266
+ Groundedness Score:
267
+ '''
268
+
269
+ groundedness_prompt = ChatPromptTemplate.from_messages([
270
+ ("system", system_message),
271
+ ("user", "Context: {context}\nResponse: {response}\n\nGroundedness score:")
272
+ ])
273
+
274
+ chain = groundedness_prompt | llm | StrOutputParser()
275
+ groundedness_score = float(chain.invoke({
276
+ "context": "\n".join([doc["content"] for doc in state['context']]),
277
+ "response": state['response'] # Complete the code to define the response
278
+ }))
279
+ print("groundedness_score: ", groundedness_score)
280
+ state['groundedness_loop_count'] += 1
281
+ print("#########Groundedness Incremented###########")
282
+ state['groundedness_score'] = groundedness_score
283
+
284
+ return state
285
+
286
+
287
+
288
+ def check_precision(state: Dict) -> Dict:
289
+ """
290
+ Checks whether the response precisely addresses the user’s query.
291
+
292
+ Args:
293
+ state (Dict): The current state of the workflow, containing the query and response.
294
+
295
+ Returns:
296
+ Dict: The updated state with the precision score.
297
+ """
298
+ print("---------check_precision---------")
299
+ system_message = '''Given question, answer and context verify if the context was useful in arriving at the given answer.
300
+ ## Instructions:
301
+ - Please provide a precision score.
302
+ - The precision score should be a floating point number between 0.0 and 1.0 inclusive.
303
+ - Please focus on evaluating the factual consistency and support for the claims
304
+ in the response with information provided in the context.
305
+ - If the response introduces or hallucinates information not found in the context,
306
+ consider it as evidence for a lower score.
307
+ - If any facts presented in the response are contradicted or unsupported by the context,
308
+ consider it as evidence for a lower score.
309
+
310
+ Precision score:
311
+
312
+ '''
313
+
314
+ precision_prompt = ChatPromptTemplate.from_messages([
315
+ ("system", system_message),
316
+ ("user", "Query: {query}\nResponse: {response}\n\nPrecision score:")
317
+ ])
318
+
319
+ chain = precision_prompt | llm | StrOutputParser() # Complete the code to define the chain of processing
320
+ precision_score = float(chain.invoke({
321
+ "query": state['query'],
322
+ "response":state['response'] # Complete the code to access the response from the state
323
+ }))
324
+ state['precision_score'] = precision_score
325
+ print("precision_score:", precision_score)
326
+ state['precision_loop_count'] +=1
327
+ print("#########Precision Incremented###########")
328
+ return state
329
+
330
+
331
+
332
+ def refine_response(state: Dict) -> Dict:
333
+ """
334
+ Suggests improvements for the generated response.
335
+
336
+ Args:
337
+ state (Dict): The current state of the workflow, containing the query and response.
338
+
339
+ Returns:
340
+ Dict: The updated state with response refinement suggestions.
341
+ """
342
+ print("---------refine_response---------")
343
+
344
+ system_message = '''You an expert medical assistant in answering questions to questions related to Nutritional Disorders.
345
+ {docs}
346
+
347
+ Your goal is to specialize in improving search queries enable healthcare providers to access information regarding symptoms, prognosis, diagnoses, treatment plans based on nutritional disorder.
348
+ Questions are specific to Nutritional disorders, dietary deficiencies, metabolic disorders, vitamin and mineral imbalances, obesity, and related health conditions.
349
+ Refer to the provided context for more information when answering questions. The answer you provide must come from the information provided above.
350
+ If you are not familiar with the answer or if information provided is not enough to answer the query response, respond - ‘I don't know the answer.'''
351
+
352
+ refine_response_prompt = ChatPromptTemplate.from_messages([
353
+ ("system", system_message),
354
+ ("user", "Query: {query}\nResponse: {response}\n\n"
355
+ "What improvements can be made to enhance accuracy and completeness?")
356
+ ])
357
+
358
+ chain = refine_response_prompt | llm| StrOutputParser()
359
+
360
+ # Store response suggestions in a structured format
361
+ feedback = f"Previous Response: {state['response']}\nSuggestions: {chain.invoke({'query': state['query'], 'response': state['response']})}"
362
+ print("feedback: ", feedback)
363
+ print(f"State: {state}")
364
+ state['feedback'] = feedback
365
+ return state
366
+
367
+
368
+
369
+ def refine_query(state: Dict) -> Dict:
370
+ """
371
+ Suggests improvements for the expanded query.
372
+
373
+ Args:
374
+ state (Dict): The current state of the workflow, containing the query and expanded query.
375
+
376
+ Returns:
377
+ Dict: The updated state with query refinement suggestions.
378
+ """
379
+ print("---------refine_query---------")
380
+ system_message = '''Your are a refinement assistant. Provide the information about eating disorders, including types, syptoms, causes, treatement and options.'''
381
+
382
+ refine_query_prompt = ChatPromptTemplate.from_messages([
383
+ ("system", system_message),
384
+ ("user", "Original Query: {query}\nExpanded Query: {expanded_query}\n\n"
385
+ "What improvements can be made for a better search?")
386
+ ])
387
+
388
+ chain = refine_query_prompt | llm | StrOutputParser()
389
+
390
+ # Store refinement suggestions without modifying the original expanded query
391
+ query_feedback = f"Previous Expanded Query: {state['expanded_query']}\nSuggestions: {chain.invoke({'query': state['query'], 'expanded_query': state['expanded_query']})}"
392
+ print("query_feedback: ", query_feedback)
393
+ print(f"Groundedness loop count: {state['groundedness_loop_count']}")
394
+ state['query_feedback'] = query_feedback
395
+ return state
396
+
397
+
398
+
399
+ def should_continue_groundedness(state):
400
+ """Decides if groundedness is sufficient or needs improvement."""
401
+ print("---------should_continue_groundedness---------")
402
+ print("groundedness loop count: ", state['groundedness_loop_count'])
403
+ if state['groundedness_score'] >= 0.4: # Complete the code to define the threshold for groundedness
404
+ print("Moving to precision")
405
+ return "check_precision"
406
+ else:
407
+ if state["groundedness_loop_count"] > state['loop_max_iter']:
408
+ return "max_iterations_reached"
409
+ else:
410
+ print(f"---------Groundedness Score Threshold Not met. Refining Response-----------")
411
+ return "refine_response"
412
+
413
+
414
+ def should_continue_precision(state: Dict) -> str:
415
+ """Decides if precision is sufficient or needs improvement."""
416
+ print("---------should_continue_precision---------")
417
+ print("precision loop count: ", state['precision_loop_count'])
418
+ if state['precision_score'] >=0.7: # Threshold for precision
419
+ return "pass" # Complete the workflow
420
+ else:
421
+ if state["precision_loop_count"] > state['loop_max_iter']: # Maximum allowed loops
422
+ return "max_iterations_reached"
423
+ else:
424
+ print(f"---------Precision Score Threshold Not met. Refining Query-----------") # Debugging
425
+ return "refine_query" # Refine the query
426
+
427
+
428
+
429
+ def max_iterations_reached(state: Dict) -> Dict:
430
+ """Handles the case when the maximum number of iterations is reached."""
431
+ print("---------max_iterations_reached---------")
432
+ """Handles the case when the maximum number of iterations is reached."""
433
+ response = "I'm unable to refine the response further. Please provide more context or clarify your question."
434
+ state['response'] = response
435
+ return state
436
+
437
+
438
+
439
+ from langgraph.graph import END, StateGraph, START
440
+
441
+ def create_workflow() -> StateGraph:
442
+ """Creates the updated workflow for the AI nutrition agent."""
443
+ workflow = StateGraph(AgentState) # Complete the code to define the initial state of the agent
444
+
445
+ # Add processing nodes
446
+ workflow.add_node("expand_query", expand_query ) # Step 1: Expand user query. Complete with the function to expand the query
447
+ workflow.add_node("retrieve_context", retrieve_context ) # Step 2: Retrieve relevant documents. Complete with the function to retrieve context
448
+ workflow.add_node("craft_response", craft_response ) # Step 3: Generate a response based on retrieved data. Complete with the function to craft a response
449
+ workflow.add_node("score_groundedness", score_groundedness ) # Step 4: Evaluate response grounding. Complete with the function to score groundedness
450
+ workflow.add_node("refine_response", refine_response ) # Step 5: Improve response if it's weakly grounded. Complete with the function to refine the response
451
+ workflow.add_node("check_precision", check_precision ) # Step 6: Evaluate response precision. Complete with the function to check precision
452
+ workflow.add_node("refine_query", refine_query ) # Step 7: Improve query if response lacks precision. Complete with the function to refine the query
453
+ workflow.add_node("max_iterations_reached", max_iterations_reached ) # Step 8: Handle max iterations. Complete with the function to handle max iterations
454
+
455
+ # Main flow edges
456
+ workflow.add_edge(START, "expand_query")
457
+ workflow.add_edge("expand_query", "retrieve_context")
458
+ workflow.add_edge("retrieve_context", "craft_response")
459
+ workflow.add_edge("craft_response", "score_groundedness")
460
+
461
+ # Conditional edges based on groundedness check
462
+ workflow.add_conditional_edges(
463
+ "score_groundedness",
464
+ should_continue_groundedness, # Use the conditional function
465
+ {
466
+ "check_precision": "check_precision", # If well-grounded, proceed to precision check.
467
+ "refine_response": "refine_response", # If not, refine the response.
468
+ "max_iterations_reached": "max_iterations_reached" # If max loops reached, exit.
469
+ }
470
+ )
471
+
472
+ workflow.add_edge("refine_response", "craft_response") # Refined responses are reprocessed.
473
+
474
+ # Conditional edges based on precision check
475
+ workflow.add_conditional_edges(
476
+ "check_precision",
477
+ should_continue_precision, # Use the conditional function
478
+ {
479
+ "pass": END, # If precise, complete the workflow.
480
+ "refine_query": "refine_query", # If imprecise, refine the query.
481
+ "max_iterations_reached": "max_iterations_reached" # If max loops reached, exit.
482
+ }
483
+ )
484
+
485
+ workflow.add_edge("refine_query", "expand_query") # Refined queries go through expansion again.
486
+
487
+ workflow.add_edge("max_iterations_reached", END)
488
+
489
+ return workflow
490
+
491
+
492
+
493
+
494
+ #=========================== Defining the agentic rag tool ====================#
495
+ WORKFLOW_APP = create_workflow().compile()
496
+ @tool
497
+ def agentic_rag(query: str):
498
+ """
499
+ Runs the RAG-based agent with conversation history for context-aware responses.
500
+
501
+ Args:
502
+ query (str): The current user query.
503
+
504
+ Returns:
505
+ Dict[str, Any]: The updated state with the generated response and conversation history.
506
+ """
507
+ # Initialize state with necessary parameters
508
+ inputs = {
509
+ "query": query, # Current user query
510
+ "expanded_query": "", # Complete the code to define the expanded version of the query
511
+ "context": [], # Retrieved documents (initially empty)
512
+ "response": "", # Complete the code to define the AI-generated response
513
+ "precision_score": 0, # Complete the code to define the precision score of the response
514
+ "groundedness_score": 0.0, # Complete the code to define the groundedness score of the response
515
+ "groundedness_loop_count": 0, # Complete the code to define the counter for groundedness loops
516
+ "precision_loop_count": 0, # Complete the code to define the counter for precision loops
517
+ "feedback": "", # Complete the code to define the feedback
518
+ "query_feedback": "", # Complete the code to define the query feedback
519
+ "loop_max_iter": 0 # Complete the code to define the maximum number of iterations for loops
520
+ }
521
+
522
+ output = WORKFLOW_APP.invoke(inputs)
523
+
524
+ return output
525
+
526
+
527
+ #================================ Guardrails ===========================#
528
+ llama_guard_client = Groq(api_key=llama_api_key)
529
+ # Function to filter user input with Llama Guard
530
+ def filter_input_with_llama_guard(user_input, model="llama-guard-3-8b"):
531
+ """
532
+ Filters user input using Llama Guard to ensure it is safe.
533
+
534
+ Parameters:
535
+ - user_input: The input provided by the user.
536
+ - model: The Llama Guard model to be used for filtering (default is "llama-guard-3-8b").
537
+
538
+ Returns:
539
+ - The filtered and safe input.
540
+ """
541
+ try:
542
+ # Create a request to Llama Guard to filter the user input
543
+ response = llama_guard_client.chat.completions.create(
544
+ messages=[{"role": "user", "content": user_input}],
545
+ model=model,
546
+ )
547
+ # Return the filtered input
548
+ return response.choices[0].message.content.strip()
549
+ except Exception as e:
550
+ print(f"Error with Llama Guard: {e}")
551
+ return None
552
+
553
+
554
+ #============================= Adding Memory to the agent using mem0 ===============================#
555
+
556
+ class NutritionBot:
557
+ def __init__(self):
558
+ """
559
+ Initialize the NutritionBot class, setting up memory, the LLM client, tools, and the agent executor.
560
+ """
561
+
562
+ # Initialize a memory client to store and retrieve customer interactions
563
+ # self.memory = MemoryClient(api_key=userdata.get("MEM0_API_KEY")) # Complete the code to define the memory client API key
564
+
565
+ self.memory = MemoryClient(api_key=MEM0_api_key) # Complete the code to define the memory client API key
566
+
567
+ # Initialize the OpenAI client using the provided credentials
568
+ self.client = ChatOpenAI(
569
+ model_name="gpt-4o-mini", # Specify the model to use (e.g., GPT-4 optimized version)
570
+ api_key=api_key, # API key for authentication
571
+ endpoint = endpoint,
572
+ temperature=0 # Controls randomness in responses; 0 ensures deterministic results
573
+ )
574
+
575
+ # Define tools available to the chatbot, such as web search
576
+ tools = [agentic_rag]
577
+
578
+ # Define the system prompt to set the behavior of the chatbot
579
+ 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.
580
+ Guidelines for Interaction:
581
+ Maintain a polite, professional, and reassuring tone.
582
+ Show genuine empathy for customer concerns and health challenges.
583
+ Reference past interactions to provide personalized and consistent advice.
584
+ Engage with the customer by asking about their food preferences, dietary restrictions, and lifestyle before offering recommendations.
585
+ Ensure consistent and accurate information across conversations.
586
+ If any detail is unclear or missing, proactively ask for clarification.
587
+ Always use the agentic_rag tool to retrieve up-to-date and evidence-based nutrition insights.
588
+ Keep track of ongoing issues and follow-ups to ensure continuity in support.
589
+ Your primary goal is to help customers make informed nutrition decisions that align with their health conditions and personal preferences.
590
+
591
+ """
592
+
593
+ # Build the prompt template for the agent
594
+ prompt = ChatPromptTemplate.from_messages([
595
+ ("system", system_prompt), # System instructions
596
+ ("human", "{input}"), # Placeholder for human input
597
+ ("placeholder", "{agent_scratchpad}") # Placeholder for intermediate reasoning steps
598
+ ])
599
+
600
+ # Create an agent capable of interacting with tools and executing tasks
601
+ agent = create_tool_calling_agent(self.client, tools, prompt)
602
+
603
+ # Wrap the agent in an executor to manage tool interactions and execution flow
604
+ self.agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
605
+
606
+
607
+ def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):
608
+ """
609
+ Store customer interaction in memory for future reference.
610
+
611
+ Args:
612
+ user_id (str): Unique identifier for the customer.
613
+ message (str): Customer's query or message.
614
+ response (str): Chatbot's response.
615
+ metadata (Dict, optional): Additional metadata for the interaction.
616
+ """
617
+ if metadata is None:
618
+ metadata = {}
619
+
620
+ # Add a timestamp to the metadata for tracking purposes
621
+ metadata["timestamp"] = datetime.now().isoformat()
622
+
623
+ # Format the conversation for storage
624
+ conversation = [
625
+ {"role": "user", "content": message},
626
+ {"role": "assistant", "content": response}
627
+ ]
628
+
629
+ # Store the interaction in the memory client
630
+ self.memory.add(
631
+ conversation,
632
+ user_id=user_id,
633
+ output_format="v1.1",
634
+ metadata=metadata
635
+ )
636
+
637
+
638
+ def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:
639
+ """
640
+ Retrieve past interactions relevant to the current query.
641
+
642
+ Args:
643
+ user_id (str): Unique identifier for the customer.
644
+ query (str): The customer's current query.
645
+
646
+ Returns:
647
+ List[Dict]: A list of relevant past interactions.
648
+ """
649
+ return self.memory.search(
650
+ query=query, # Search for interactions related to the query
651
+ user_id=user_id, # Restrict search to the specific user
652
+ limit=3 # Complete the code to define the limit for retrieved interactions
653
+ )
654
+
655
+
656
+ def handle_customer_query(self, user_id: str, query: str) -> str:
657
+ """
658
+ Process a customer's query and provide a response, taking into account past interactions.
659
+
660
+ Args:
661
+ user_id (str): Unique identifier for the customer.
662
+ query (str): Customer's query.
663
+
664
+ Returns:
665
+ str: Chatbot's response.
666
+ """
667
+
668
+ # Retrieve relevant past interactions for context
669
+ relevant_history = self.get_relevant_history(user_id, query)
670
+
671
+ # Build a context string from the relevant history
672
+ context = "Previous relevant interactions:\n"
673
+ for memory in relevant_history:
674
+ context += f"Customer: {memory['memory']}\n" # Customer's past messages
675
+ context += f"Support: {memory['memory']}\n" # Chatbot's past responses
676
+ context += "---\n"
677
+
678
+ # Print context for debugging purposes
679
+ print("Context: ", context)
680
+
681
+ # Prepare a prompt combining past context and the current query
682
+ prompt = f"""
683
+ Context:
684
+ {context}
685
+
686
+ Current customer query: {query}
687
+
688
+ Provide a helpful response that takes into account any relevant past interactions.
689
+ """
690
+
691
+ # Generate a response using the agent
692
+ response = self.agent_executor.invoke({"input": prompt})
693
+
694
+ # Store the current interaction for future reference
695
+ self.store_customer_interaction(
696
+ user_id=user_id,
697
+ message=query,
698
+ response=response["output"],
699
+ metadata={"type": "support_query"}
700
+ )
701
+
702
+ # Return the chatbot's response
703
+ return response['output']
704
+
705
+
706
+ #=====================User Interface using streamlit ===========================#
707
+ def nutrition_disorder_streamlit():
708
+ """
709
+ A Streamlit-based UI for the Nutrition Disorder Specialist Agent.
710
+ """
711
+ st.title("Nutrition Disorder Specialist")
712
+ st.write("Ask me anything about nutrition disorders, symptoms, causes, treatments, and more.")
713
+ st.write("Type 'exit' to end the conversation.")
714
+
715
+ # Initialize session state for chat history and user_id if they don't exist
716
+ if 'chat_history' not in st.session_state:
717
+ st.session_state.chat_history = []
718
+ if 'user_id' not in st.session_state:
719
+ st.session_state.user_id = None
720
+
721
+ # Login form: Only if user is not logged in
722
+ if st.session_state.user_id is None:
723
+ with st.form("login_form", clear_on_submit=True):
724
+ user_id = st.text_input("Please enter your name to begin:")
725
+ submit_button = st.form_submit_button("Login")
726
+ if submit_button and user_id:
727
+ st.session_state.user_id = user_id
728
+ st.session_state.chat_history.append({
729
+ "role": "assistant",
730
+ "content": f"Welcome, {user_id}! How can I help you with nutrition disorders today?"
731
+ })
732
+ st.session_state.login_submitted = True # Set flag to trigger rerun
733
+ if st.session_state.get("login_submitted", False):
734
+ st.session_state.pop("login_submitted")
735
+ st.rerun()
736
+ else:
737
+ # Display chat history
738
+ for message in st.session_state.chat_history:
739
+ with st.chat_message(message["role"]):
740
+ st.write(message["content"])
741
+
742
+ # Chat input with custom placeholder text
743
+ user_query = st.chat_input("Type your question here (or 'exit' to end") # Blank #1: Fill in the chat input prompt (e.g., "Type your question here (or 'exit' to end)...")
744
+ if user_query:
745
+ if user_query.lower() == "exit":
746
+ st.session_state.chat_history.append({"role": "user", "content": "exit"})
747
+ with st.chat_message("user"):
748
+ st.write("exit")
749
+ goodbye_msg = "Goodbye! Feel free to return if you have more questions about nutrition disorders."
750
+ st.session_state.chat_history.append({"role": "assistant", "content": goodbye_msg})
751
+ with st.chat_message("assistant"):
752
+ st.write(goodbye_msg)
753
+ st.session_state.user_id = None
754
+ st.rerun()
755
+ return
756
+
757
+ st.session_state.chat_history.append({"role": "user", "content": user_query})
758
+ with st.chat_message("user"):
759
+ st.write(user_query)
760
+
761
+ # Filter input using Llama Guard
762
+ filtered_result = filter_input_with_llama_guard(user_query) # Blank #2: Fill in with the function name for filtering input (e.g., filter_input_with_llama_guard)
763
+ filtered_result = filtered_result.replace("\n", " ") # Normalize the result
764
+
765
+ # Check if input is safe based on allowed statuses
766
+ if filtered_result in ["safe", "unsafe S7", "unsafe S6"]: # Blanks #3, #4, #5: Fill in with allowed safe statuses (e.g., "safe", "unsafe S7", "unsafe S6")
767
+ try:
768
+ if 'chatbot' not in st.session_state:
769
+ st.session_state.chatbot = NutritionBot() # Blank #6: Fill in with the chatbot class initialization (e.g., NutritionBot)
770
+ response = st.session_state.chatbot.handle_customer_query(st.session_state.user_id, user_query)
771
+ # Blank #7: Fill in with the method to handle queries (e.g., handle_customer_query)
772
+ st.write(response)
773
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
774
+ except Exception as e:
775
+ error_msg = f"Sorry, I encountered an error while processing your query. Please try again. Error: {str(e)}"
776
+ st.write(error_msg)
777
+ st.session_state.chat_history.append({"role": "assistant", "content": error_msg})
778
+ else:
779
+ inappropriate_msg = "I apologize, but I cannot process that input as it may be inappropriate. Please try again."
780
+ st.write(inappropriate_msg)
781
+ st.session_state.chat_history.append({"role": "assistant", "content": inappropriate_msg})
782
+
783
+ if __name__ == "__main__":
784
+ nutrition_disorder_streamlit()