Spaces:
Build error
Build error
File size: 7,728 Bytes
199c10a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
######################## WRITE YOUR CODE HERE #########################
import os
import chromadb
import numpy as np
np.float_ = np.float64
from dotenv import load_dotenv
import json
from langchain_core.documents import Document
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_openai import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain_openai import OpenAIEmbeddings
from langchain_community.document_loaders import PyPDFDirectoryLoader
from langchain_experimental.text_splitter import SemanticChunker
from langchain.chains.query_constructor.base import AttributeInfo
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import CrossEncoderReranker
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
from langchain.text_splitter import (
CharacterTextSplitter, # Splitting text by characters
RecursiveCharacterTextSplitter # Recursive splitting of text by characters
)
from llama_parse import LlamaParse
from llama_index.core import Settings, SimpleDirectoryReader
# Import the PyPDFDirectoryLoader class
from langchain_community.document_loaders import PyPDFDirectoryLoader
class NutritionBot:
def __init__(self):
"""
Initialize the NutritionBot class, setting up memory, the LLM client, tools, and the agent executor.
"""
# Initialize a memory client to store and retrieve customer interactions
self.memory = MemoryClient(api_key=userdata.get("mem0")) # Complete the code to define the memory client API key
# Initialize the OpenAI client using the provided credentials
self.client = ChatOpenAI(
model_name="gpt-4o-mini", # Specify the model to use (e.g., GPT-4 optimized version)
api_key=api_key, # API key for authentication
endpoint = endpoint,
temperature=0 # Controls randomness in responses; 0 ensures deterministic results
)
# Define tools available to the chatbot, such as web search
tools = [agentic_rag]
# Define the system prompt to set the behavior of the chatbot
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.
Guidelines for Interaction:
Maintain a polite, professional, and reassuring tone.
Show genuine empathy for customer concerns and health challenges.
Reference past interactions to provide personalized and consistent advice.
Engage with the customer by asking about their food preferences, dietary restrictions, and lifestyle before offering recommendations.
Ensure consistent and accurate information across conversations.
If any detail is unclear or missing, proactively ask for clarification.
Always use the agentic_rag tool to retrieve up-to-date and evidence-based nutrition insights.
Keep track of ongoing issues and follow-ups to ensure continuity in support.
Your primary goal is to help customers make informed nutrition decisions that align with their health conditions and personal preferences.
"""
# Build the prompt template for the agent
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt), # System instructions
("human", "{input}"), # Placeholder for human input
("placeholder", "{agent_scratchpad}") # Placeholder for intermediate reasoning steps
])
# Create an agent capable of interacting with tools and executing tasks
agent = create_tool_calling_agent(self.client, tools, prompt)
# Wrap the agent in an executor to manage tool interactions and execution flow
self.agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):
"""
Store customer interaction in memory for future reference.
Args:
user_id (str): Unique identifier for the customer.
message (str): Customer's query or message.
response (str): Chatbot's response.
metadata (Dict, optional): Additional metadata for the interaction.
"""
if metadata is None:
metadata = {}
# Add a timestamp to the metadata for tracking purposes
metadata["timestamp"] = datetime.now().isoformat()
# Format the conversation for storage
conversation = [
{"role": "user", "content": message},
{"role": "assistant", "content": response}
]
# Store the interaction in the memory client
self.memory.add(
conversation,
user_id=user_id,
output_format="v1.1",
metadata=metadata
)
def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:
"""
Retrieve past interactions relevant to the current query.
Args:
user_id (str): Unique identifier for the customer.
query (str): The customer's current query.
Returns:
List[Dict]: A list of relevant past interactions.
"""
return self.memory.search(
query=query, # Search for interactions related to the query
user_id=user_id, # Restrict search to the specific user
limit=10 # Complete the code to define the limit for retrieved interactions
)
def handle_customer_query(self, user_id: str, query: str) -> str:
"""
Process a customer's query and provide a response, taking into account past interactions.
Args:
user_id (str): Unique identifier for the customer.
query (str): Customer's query.
Returns:
str: Chatbot's response.
"""
# Retrieve relevant past interactions for context
relevant_history = self.get_relevant_history(user_id, query)
# Build a context string from the relevant history
context = "Previous relevant interactions:\n"
for memory in relevant_history:
context += f"Customer: {memory['memory']}\n" # Customer's past messages
context += f"Support: {memory['memory']}\n" # Chatbot's past responses
context += "---\n"
# Print context for debugging purposes
print("Context: ", context)
# Prepare a prompt combining past context and the current query
prompt = f"""
Context:
{context}
Current customer query: {query}
Provide a helpful response that takes into account any relevant past interactions.
"""
# Generate a response using the agent
response = self.agent_executor.invoke({"input": prompt})
# Store the current interaction for future reference
self.store_customer_interaction(
user_id=user_id,
message=query,
response=response["output"],
metadata={"type": "support_query"}
)
# Return the chatbot's response
return response['output']
|