Next, we’ll add tools specific to healthcare assistance:
def schedule_appointment(date: str, time: str, reason: str) -> dict: """Schedules a doctor's appointment.""" # In a real app, this would connect to a scheduling system appointment_id = f"APT-{hash(date + time) % 10000}" return { "status": "success", "appointment_id": appointment_id, "confirmation": f"Appointment scheduled for {date} at {time} for {reason}", "message": "Please arrive 15 minutes early to complete paperwork." }
Now we’ll create our main agent with all the tools:
# Create the agenthealthcare_agent = Agent( name="healthcare_assistant", model="gemini-1.5-flash", # Using Gemini for healthcare assistant description="Healthcare assistant that helps patients with health information and appointment scheduling.", instruction="""You are a helpful Healthcare Assistant with memory capabilities.Your primary responsibilities are to:1. Remember patient information using the 'save_patient_info' tool when they share symptoms, conditions, or preferences.2. Retrieve past patient information using the 'retrieve_patient_info' tool when relevant to the current conversation.3. Help schedule appointments using the 'schedule_appointment' tool.IMPORTANT GUIDELINES:- Always be empathetic, professional, and helpful.- Save important patient information like symptoms, conditions, allergies, and preferences.- Check if you have relevant patient information before asking for details they may have shared previously.- Make it clear you are not a doctor and cannot provide medical diagnosis or treatment.- For serious symptoms, always recommend consulting a healthcare professional.- Keep all patient information confidential.""", tools=[save_patient_info, retrieve_patient_info, schedule_appointment])
# Set up Session Service and Runnersession_service = InMemorySessionService()# Define constants for the conversationAPP_NAME = "healthcare_assistant_app"USER_ID = "Alex"SESSION_ID = "session_001"# Create a sessionsession = session_service.create_session( app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)# Create the runnerrunner = Runner( agent=healthcare_agent, app_name=APP_NAME, session_service=session_service)
# Function to interact with the agentasync def call_agent_async(query, runner, user_id, session_id): """Sends a query to the agent and returns the final response.""" print(f"\n>>> Patient: {query}") # Format the user's message content = types.Content( role='user', parts=[types.Part(text=query)] ) # Set user_id for tools to access save_patient_info.user_id = user_id retrieve_patient_info.user_id = user_id # Run the agent async for event in runner.run_async( user_id=user_id, session_id=session_id, new_message=content ): if event.is_final_response(): if event.content and event.content.parts: response = event.content.parts[0].text print(f"<<< Assistant: {response}") return response return "No response received."# Example conversation flowasync def run_conversation(): # First interaction - patient introduces themselves with key information await call_agent_async( "Hi, I'm Alex. I've been having headaches for the past week, and I have a penicillin allergy.", runner=runner, user_id=USER_ID, session_id=SESSION_ID ) # Request for health information await call_agent_async( "Can you tell me more about what might be causing my headaches?", runner=runner, user_id=USER_ID, session_id=SESSION_ID ) # Schedule an appointment await call_agent_async( "I think I should see a doctor. Can you help me schedule an appointment for next Monday at 2pm?", runner=runner, user_id=USER_ID, session_id=SESSION_ID ) # Test memory - should remember patient name, symptoms, and allergy await call_agent_async( "What medications should I avoid for my headaches?", runner=runner, user_id=USER_ID, session_id=SESSION_ID )# Run the conversation exampleif __name__ == "__main__": asyncio.run(run_conversation())
This healthcare assistant demonstrates several key capabilities:
Memory Storage: When Alex mentions her headaches and penicillin allergy, the agent stores this information in Mem0 using the save_patient_info tool.
Contextual Retrieval: When Alex asks about headache causes, the agent uses the retrieve_patient_info tool to recall her specific situation.
Memory Application: When discussing medications, the agent remembers Alex’s penicillin allergy without her needing to repeat it, providing safer and more personalized advice.
Conversation Continuity: The agent maintains context across the entire conversation session, creating a more natural and efficient interaction.
Instead of passing the user ID as a parameter to the memory tools (which would require modifying the ADK’s tool calling system), we attach it directly to the function object:
# Set user_id for tools to accesssave_patient_info.user_id = user_idretrieve_patient_info.user_id = user_id
Inside the tool functions, we retrieve this attribute:
# Get user_id from session state or use defaultuser_id = getattr(save_patient_info, 'user_id', 'default_user')
This approach allows our tools to maintain user context without complicating their parameter signatures.
This example demonstrates how to build a healthcare assistant with persistent memory using Google ADK and Mem0. The integration allows for a more personalized patient experience by maintaining context across conversation turns, which is particularly valuable in healthcare scenarios where continuity of information is crucial.By storing and retrieving patient information intelligently, the assistant provides more relevant responses without requiring the patient to repeat their medical history, symptoms, or preferences.
Tag and Organize Memories
Categorize patient data by symptoms, history, and visit context.
Support Inbox with Mem0
Apply similar memory patterns to customer support workflows.