jenngang commited on
Commit
f7dcb1a
·
verified ·
1 Parent(s): 4bcc897

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +28 -5
app.py CHANGED
@@ -572,19 +572,22 @@ class NutritionBot:
572
  """
573
  Initialize the NutritionBot class, setting up memory, the LLM client, tools, and the agent executor.
574
  """
575
-
576
  # Initialize a memory client to store and retrieve customer interactions
577
  self.memory = MemoryClient(api_key=MEM0_api_key) # userdata.get("mem0")) # Complete the code to define the memory client API key
 
578
 
579
  # Initialize the OpenAI client using the provided credentials
580
  self.client = ChatOpenAI(
581
  model_name="gpt-4o", # Used gpt-4o to get improved results; Specify the model to use (e.g., GPT-4 optimized version)
582
- api_key=api_key, # API key for authentication
583
  temperature=0 # Controls randomness in responses; 0 ensures deterministic results
584
  )
 
585
 
586
  # Define tools available to the chatbot, such as web search
587
  tools = [agentic_rag]
 
588
 
589
  # Define the system prompt to set the behavior of the chatbot
590
  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.
@@ -600,6 +603,7 @@ class NutritionBot:
600
  Your primary goal is to help customers make informed nutrition decisions that align with their health conditions and personal preferences.
601
 
602
  """
 
603
 
604
  # Build the prompt template for the agent
605
  prompt = ChatPromptTemplate.from_messages([
@@ -607,12 +611,15 @@ class NutritionBot:
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):
@@ -678,6 +685,7 @@ class NutritionBot:
678
 
679
  # Retrieve relevant past interactions for context
680
  relevant_history = self.get_relevant_history(user_id, query)
 
681
 
682
  # Build a context string from the relevant history
683
  context = "Previous relevant interactions:\n"
@@ -698,9 +706,11 @@ class NutritionBot:
698
 
699
  Provide a helpful response that takes into account any relevant past interactions.
700
  """
 
701
 
702
  # Generate a response using the agent
703
  response = self.agent_executor.invoke({"input": prompt})
 
704
 
705
  # Store the current interaction for future reference
706
  self.store_customer_interaction(
@@ -709,6 +719,8 @@ class NutritionBot:
709
  response=response["output"],
710
  metadata={"type": "support_query"}
711
  )
 
 
712
 
713
  # Return the chatbot's response
714
  return response['output']
@@ -775,10 +787,17 @@ def nutrition_disorder_streamlit():
775
 
776
  # Check if input is safe based on allowed statuses
777
  if filtered_result in ["safe", "safe S7", "safe S6"]: # Blanks #3, #4, #5: Fill in with allowed safe statuses (e.g., "safe", "unsafe S7", "unsafe S6")
 
778
  try:
779
  if 'chatbot' not in st.session_state:
 
780
  st.session_state.chatbot = NutritionBot() # Blank #6: Fill in with the chatbot class initialization (e.g., NutritionBot)
 
 
 
 
781
  response = st.session_state.chatbot.handle_customer_query(st.session_state.user_id, user_query)
 
782
  # Blank #7: Fill in with the method to handle queries (e.g., handle_customer_query)
783
  st.write(response)
784
  st.session_state.chat_history.append({"role": "assistant", "content": response})
@@ -787,9 +806,13 @@ def nutrition_disorder_streamlit():
787
  st.write(error_msg)
788
  st.session_state.chat_history.append({"role": "assistant", "content": error_msg})
789
  else:
790
- inappropriate_msg = "I apologize, but I cannot process that input as it may be inappropriate. Please try again."
791
- st.write(inappropriate_msg)
792
- st.session_state.chat_history.append({"role": "assistant", "content": inappropriate_msg})
 
 
 
 
793
 
794
  if __name__ == "__main__":
795
  nutrition_disorder_streamlit()
 
572
  """
573
  Initialize the NutritionBot class, setting up memory, the LLM client, tools, and the agent executor.
574
  """
575
+ print("Entered NutritionBot...")
576
  # Initialize a memory client to store and retrieve customer interactions
577
  self.memory = MemoryClient(api_key=MEM0_api_key) # userdata.get("mem0")) # Complete the code to define the memory client API key
578
+ print("Got memory...")
579
 
580
  # Initialize the OpenAI client using the provided credentials
581
  self.client = ChatOpenAI(
582
  model_name="gpt-4o", # Used gpt-4o to get improved results; Specify the model to use (e.g., GPT-4 optimized version)
583
+ api_key=my_api_key, # API key for authentication
584
  temperature=0 # Controls randomness in responses; 0 ensures deterministic results
585
  )
586
+ print("Got client...")
587
 
588
  # Define tools available to the chatbot, such as web search
589
  tools = [agentic_rag]
590
+ print("Got tools...")
591
 
592
  # Define the system prompt to set the behavior of the chatbot
593
  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.
 
603
  Your primary goal is to help customers make informed nutrition decisions that align with their health conditions and personal preferences.
604
 
605
  """
606
+ print("Got system prompt...")
607
 
608
  # Build the prompt template for the agent
609
  prompt = ChatPromptTemplate.from_messages([
 
611
  ("human", "{input}"), # Placeholder for human input
612
  ("placeholder", "{agent_scratchpad}") # Placeholder for intermediate reasoning steps
613
  ])
614
+ print("Got user prompt...")
615
 
616
  # Create an agent capable of interacting with tools and executing tasks
617
  agent = create_tool_calling_agent(self.client, tools, prompt)
618
+ print("Got agent...")
619
 
620
  # Wrap the agent in an executor to manage tool interactions and execution flow
621
  self.agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
622
+ print("Got executor...")
623
 
624
 
625
  def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):
 
685
 
686
  # Retrieve relevant past interactions for context
687
  relevant_history = self.get_relevant_history(user_id, query)
688
+ print("Got history...")
689
 
690
  # Build a context string from the relevant history
691
  context = "Previous relevant interactions:\n"
 
706
 
707
  Provide a helpful response that takes into account any relevant past interactions.
708
  """
709
+ print("Got prepare for invoke...")
710
 
711
  # Generate a response using the agent
712
  response = self.agent_executor.invoke({"input": prompt})
713
+ print("Got response...")
714
 
715
  # Store the current interaction for future reference
716
  self.store_customer_interaction(
 
719
  response=response["output"],
720
  metadata={"type": "support_query"}
721
  )
722
+ print("Got output...")
723
+
724
 
725
  # Return the chatbot's response
726
  return response['output']
 
787
 
788
  # Check if input is safe based on allowed statuses
789
  if filtered_result in ["safe", "safe S7", "safe S6"]: # Blanks #3, #4, #5: Fill in with allowed safe statuses (e.g., "safe", "unsafe S7", "unsafe S6")
790
+ print("Got a safe input...")
791
  try:
792
  if 'chatbot' not in st.session_state:
793
+ print("In not in st.session_state...")
794
  st.session_state.chatbot = NutritionBot() # Blank #6: Fill in with the chatbot class initialization (e.g., NutritionBot)
795
+ else:
796
+ print("In st.session_state...")
797
+
798
+ print("Getting response...")
799
  response = st.session_state.chatbot.handle_customer_query(st.session_state.user_id, user_query)
800
+ print(f"Got response: {response}")
801
  # Blank #7: Fill in with the method to handle queries (e.g., handle_customer_query)
802
  st.write(response)
803
  st.session_state.chat_history.append({"role": "assistant", "content": response})
 
806
  st.write(error_msg)
807
  st.session_state.chat_history.append({"role": "assistant", "content": error_msg})
808
  else:
809
+ try:
810
+ inappropriate_msg = "I apologize, but I cannot process that input as it may be inappropriate. Please try again."
811
+ st.write(inappropriate_msg)
812
+ st.session_state.chat_history.append({"role": "assistant", "content": inappropriate_msg})
813
+ except Exception as e:
814
+ st.write(str(e))
815
+ st.session_state.chat_history.append({"role": "assistant", "content": str(e)})
816
 
817
  if __name__ == "__main__":
818
  nutrition_disorder_streamlit()