Afshintm commited on
Commit
47e3111
·
verified ·
1 Parent(s): 178bc1d

Upload app.py with huggingface_hub

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