File size: 4,517 Bytes
b32ba05 d35079a 828cbc3 b32ba05 33268d8 b32ba05 d35079a b32ba05 d35079a b32ba05 50d2bf4 b32ba05 a08f2e2 b32ba05 a08f2e2 b32ba05 a08f2e2 b32ba05 50d2bf4 b32ba05 33268d8 b32ba05 d35079a | 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 |
######################## 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))
|