######################## FINAL APP.PY (Streamlit Version) ######################### # 07032025 import streamlit as st from datetime import datetime from typing import Dict, List import os import json # ✅ Fix for Hugging Face write permission os.environ["MEM0_HOME"] = "./.mem0" from mem0 import MemoryClient from langchain_core.prompts import ChatPromptTemplate from langchain.agents import create_tool_calling_agent, AgentExecutor from langchain.chat_models import ChatOpenAI # ✅ Update: Use local config path (not Colab path) with open("config.json") as f: config = json.load(f) # Optional placeholder if agentic_rag is not defined try: from agentic_rag_workflow import agentic_rag except ImportError: def agentic_rag(*args, **kwargs): return "This is a placeholder for agentic_rag tool." # ------------------------ Define NutritionBot ------------------------ #07042025 from mem0 import MemoryClient class NutritionBot: #07042025 Start # def __init__(self): # self.memory = MemoryClient(api_key=os.getenv("MEM0_API_KEY", "m0-qYbYxa325DtWw8cJoEZyWivE9HMPY74hfX5UHdVl")) def __init__(self): """ Initialize the NutritionBot class with memory, LLM client, tools, and the agent executor. """ # Memory to store/retrieve customer interactions self.memory = MemoryClient(api_key=os.getenv("Mem0")) #07042025 End self.client = ChatOpenAI( model_name="gpt-4o-mini", api_key=config.get("API_KEY"), endpoint=config.get("OPENAI_API_BASE"), temperature=0 ) tools = [agentic_rag] 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.""" prompt = ChatPromptTemplate.from_messages([ ("system", system_prompt), ("human", "{input}"), ("placeholder", "{agent_scratchpad}") ]) agent = create_tool_calling_agent(self.client, tools, prompt) 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): if metadata is None: metadata = {} metadata["timestamp"] = datetime.now().isoformat() conversation = [ {"role": "user", "content": message}, {"role": "assistant", "content": response} ] 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]: return self.memory.search(query=query, user_id=user_id, limit=5) def handle_customer_query(self, user_id: str, query: str) -> str: relevant_history = self.get_relevant_history(user_id, query) context = "Previous relevant interactions:\n" for memory in relevant_history: context += f"Customer: {memory['memory']}\n" context += f"Support: {memory['memory']}\n" context += "---\n" prompt = f""" Context: {context} Current customer query: {query} Provide a helpful response that takes into account any relevant past interactions. """ response = self.agent_executor.invoke({"input": prompt}) self.store_customer_interaction(user_id, query, response["output"], metadata={"type": "support_query"}) return response["output"] # ------------------------ Streamlit Interface ------------------------ st.set_page_config(page_title="Nutrition Disorder Specialist Agent") st.title("🩺 Nutrition Disorder Specialist Agent") st.write("Ask anything about nutrition-related disorders, treatments, or dietary recommendations.") user_id = st.text_input("👤 User ID", placeholder="Enter your name or ID") query = st.text_area("💬 Your Question", placeholder="Ask about a nutrition disorder...") if st.button("🔍 Submit") and user_id and query: with st.spinner("Thinking..."): bot = NutritionBot() try: response = bot.handle_customer_query(user_id, query) st.success("✅ Agent Response:") st.write(response) except Exception as e: st.error("❌ Error occurred while processing your request.") st.text(str(e))