repositories
loading repo index
repositories
loading repo index
repository
loading code, commits, and activity
public Clawd ADK gateway launch mirror
stars
latest
clone command
git clone gitlawb://did:key:z6Mkq5mY...iFZ5/my-project-publ...git clone gitlawb://did:key:z6Mkq5mY.../my-project-publ...2fa351d6docs: add automaton and perps launch sources16d ago| #1 | --- |
| #2 | title: Healthcare Coach with ADK |
| #3 | description: "Guide patients with an assistant that remembers history across ADK sessions." |
| #4 | --- |
| #5 | |
| #6 | |
| #7 | This example demonstrates how to build a healthcare assistant that remembers patient information across conversations using Google ADK and Mem0. |
| #8 | |
| #9 | ## Overview |
| #10 | |
| #11 | The Healthcare Assistant helps patients by: |
| #12 | - Remembering their medical history and symptoms |
| #13 | - Providing general health information |
| #14 | - Scheduling appointment reminders |
| #15 | - Maintaining a personalized experience across conversations |
| #16 | |
| #17 | By integrating Mem0's memory layer with Google ADK, the assistant maintains context about the patient without requiring them to repeat information. |
| #18 | |
| #19 | ## Setup |
| #20 | |
| #21 | Before you begin, make sure you have: |
| #22 | |
| #23 | Installed Google ADK and Mem0 SDK: |
| #24 | ```bash |
| #25 | pip install google-adk mem0ai python-dotenv |
| #26 | ``` |
| #27 | |
| #28 | ## Code Breakdown |
| #29 | |
| #30 | Let's get started and understand the different components required in building a healthcare assistant powered by memory |
| #31 | |
| #32 | ```python |
| #33 | # Import dependencies |
| #34 | import os |
| #35 | import asyncio |
| #36 | from google.adk.agents import Agent |
| #37 | from google.adk.runners import Runner |
| #38 | from google.adk.sessions import InMemorySessionService |
| #39 | from google.genai import types |
| #40 | from mem0 import MemoryClient |
| #41 | from dotenv import load_dotenv |
| #42 | |
| #43 | load_dotenv() |
| #44 | |
| #45 | # Set up environment variables |
| #46 | # os.environ["GOOGLE_API_KEY"] = "your-google-api-key" |
| #47 | # os.environ["MEM0_API_KEY"] = "your-mem0-api-key" |
| #48 | |
| #49 | # Define a global user ID for simplicity |
| #50 | USER_ID = "Alex" |
| #51 | |
| #52 | # Initialize Mem0 client |
| #53 | mem0 = MemoryClient() |
| #54 | ``` |
| #55 | |
| #56 | ## Define Memory Tools |
| #57 | |
| #58 | First, we'll create tools that allow our agent to store and retrieve information using Mem0: |
| #59 | |
| #60 | ```python |
| #61 | def save_patient_info(information: str) -> dict: |
| #62 | """Saves important patient information to memory.""" |
| #63 | |
| #64 | # Store in Mem0 |
| #65 | response = mem0_client.add( |
| #66 | [{"role": "user", "content": information}], |
| #67 | user_id=USER_ID, |
| #68 | run_id="healthcare_session", |
| #69 | metadata={"type": "patient_information"} |
| #70 | ) |
| #71 | |
| #72 | |
| #73 | def retrieve_patient_info(query: str) -> dict: |
| #74 | """Retrieves relevant patient information from memory.""" |
| #75 | |
| #76 | # Search Mem0 |
| #77 | results = mem0_client.search( |
| #78 | query, |
| #79 | user_id=USER_ID, |
| #80 | limit=5, |
| #81 | threshold=0.7 # Higher threshold for more relevant results |
| #82 | ) |
| #83 | |
| #84 | # Format and return the results |
| #85 | if results and len(results) > 0: |
| #86 | memories = [memory["memory"] for memory in results.get('results', [])] |
| #87 | return { |
| #88 | "status": "success", |
| #89 | "memories": memories, |
| #90 | "count": len(memories) |
| #91 | } |
| #92 | else: |
| #93 | return { |
| #94 | "status": "no_results", |
| #95 | "memories": [], |
| #96 | "count": 0 |
| #97 | } |
| #98 | ``` |
| #99 | |
| #100 | ## Define Healthcare Tools |
| #101 | |
| #102 | Next, we'll add tools specific to healthcare assistance: |
| #103 | |
| #104 | ```python |
| #105 | def schedule_appointment(date: str, time: str, reason: str) -> dict: |
| #106 | """Schedules a doctor's appointment.""" |
| #107 | # In a real app, this would connect to a scheduling system |
| #108 | appointment_id = f"APT-{hash(date + time) % 10000}" |
| #109 | |
| #110 | return { |
| #111 | "status": "success", |
| #112 | "appointment_id": appointment_id, |
| #113 | "confirmation": f"Appointment scheduled for {date} at {time} for {reason}", |
| #114 | "message": "Please arrive 15 minutes early to complete paperwork." |
| #115 | } |
| #116 | ``` |
| #117 | |
| #118 | ## Create the Healthcare Assistant Agent |
| #119 | |
| #120 | Now we'll create our main agent with all the tools: |
| #121 | |
| #122 | ```python |
| #123 | # Create the agent |
| #124 | healthcare_agent = Agent( |
| #125 | name="healthcare_assistant", |
| #126 | model="gemini-1.5-flash", # Using Gemini for healthcare assistant |
| #127 | description="Healthcare assistant that helps patients with health information and appointment scheduling.", |
| #128 | instruction="""You are a helpful Healthcare Assistant with memory capabilities. |
| #129 | |
| #130 | Your primary responsibilities are to: |
| #131 | 1. Remember patient information using the 'save_patient_info' tool when they share symptoms, conditions, or preferences. |
| #132 | 2. Retrieve past patient information using the 'retrieve_patient_info' tool when relevant to the current conversation. |
| #133 | 3. Help schedule appointments using the 'schedule_appointment' tool. |
| #134 | |
| #135 | IMPORTANT GUIDELINES: |
| #136 | - Always be empathetic, professional, and helpful. |
| #137 | - Save important patient information like symptoms, conditions, allergies, and preferences. |
| #138 | - Check if you have relevant patient information before asking for details they may have shared previously. |
| #139 | - Make it clear you are not a doctor and cannot provide medical diagnosis or treatment. |
| #140 | - For serious symptoms, always recommend consulting a healthcare professional. |
| #141 | - Keep all patient information confidential. |
| #142 | """, |
| #143 | tools=[save_patient_info, retrieve_patient_info, schedule_appointment] |
| #144 | ) |
| #145 | ``` |
| #146 | |
| #147 | ## Set Up Session and Runner |
| #148 | |
| #149 | ```python |
| #150 | # Set up Session Service and Runner |
| #151 | session_service = InMemorySessionService() |
| #152 | |
| #153 | # Define constants for the conversation |
| #154 | APP_NAME = "healthcare_assistant_app" |
| #155 | USER_ID = "Alex" |
| #156 | SESSION_ID = "session_001" |
| #157 | |
| #158 | # Create a session |
| #159 | session = session_service.create_session( |
| #160 | app_name=APP_NAME, |
| #161 | user_id=USER_ID, |
| #162 | session_id=SESSION_ID |
| #163 | ) |
| #164 | |
| #165 | # Create the runner |
| #166 | runner = Runner( |
| #167 | agent=healthcare_agent, |
| #168 | app_name=APP_NAME, |
| #169 | session_service=session_service |
| #170 | ) |
| #171 | ``` |
| #172 | |
| #173 | ## Interact with the Healthcare Assistant |
| #174 | |
| #175 | ```python |
| #176 | # Function to interact with the agent |
| #177 | async def call_agent_async(query, runner, user_id, session_id): |
| #178 | """Sends a query to the agent and returns the final response.""" |
| #179 | print(f"\n>>> Patient: {query}") |
| #180 | |
| #181 | # Format the user's message |
| #182 | content = types.Content( |
| #183 | role='user', |
| #184 | parts=[types.Part(text=query)] |
| #185 | ) |
| #186 | |
| #187 | # Set user_id for tools to access |
| #188 | save_patient_info.user_id = user_id |
| #189 | retrieve_patient_info.user_id = user_id |
| #190 | |
| #191 | # Run the agent |
| #192 | async for event in runner.run_async( |
| #193 | user_id=user_id, |
| #194 | session_id=session_id, |
| #195 | new_message=content |
| #196 | ): |
| #197 | if event.is_final_response(): |
| #198 | if event.content and event.content.parts: |
| #199 | response = event.content.parts[0].text |
| #200 | print(f"<<< Assistant: {response}") |
| #201 | return response |
| #202 | |
| #203 | return "No response received." |
| #204 | |
| #205 | # Example conversation flow |
| #206 | async def run_conversation(): |
| #207 | # First interaction - patient introduces themselves with key information |
| #208 | await call_agent_async( |
| #209 | "Hi, I'm Alex. I've been having headaches for the past week, and I have a penicillin allergy.", |
| #210 | runner=runner, |
| #211 | user_id=USER_ID, |
| #212 | session_id=SESSION_ID |
| #213 | ) |
| #214 | |
| #215 | # Request for health information |
| #216 | await call_agent_async( |
| #217 | "Can you tell me more about what might be causing my headaches?", |
| #218 | runner=runner, |
| #219 | user_id=USER_ID, |
| #220 | session_id=SESSION_ID |
| #221 | ) |
| #222 | |
| #223 | # Schedule an appointment |
| #224 | await call_agent_async( |
| #225 | "I think I should see a doctor. Can you help me schedule an appointment for next Monday at 2pm?", |
| #226 | runner=runner, |
| #227 | user_id=USER_ID, |
| #228 | session_id=SESSION_ID |
| #229 | ) |
| #230 | |
| #231 | # Test memory - should remember patient name, symptoms, and allergy |
| #232 | await call_agent_async( |
| #233 | "What medications should I avoid for my headaches?", |
| #234 | runner=runner, |
| #235 | user_id=USER_ID, |
| #236 | session_id=SESSION_ID |
| #237 | ) |
| #238 | |
| #239 | # Run the conversation example |
| #240 | if __name__ == "__main__": |
| #241 | asyncio.run(run_conversation()) |
| #242 | ``` |
| #243 | |
| #244 | ## How It Works |
| #245 | |
| #246 | This healthcare assistant demonstrates several key capabilities: |
| #247 | |
| #248 | 1. **Memory Storage**: When Alex mentions her headaches and penicillin allergy, the agent stores this information in Mem0 using the `save_patient_info` tool. |
| #249 | |
| #250 | 2. **Contextual Retrieval**: When Alex asks about headache causes, the agent uses the `retrieve_patient_info` tool to recall her specific situation. |
| #251 | |
| #252 | 3. **Memory Application**: When discussing medications, the agent remembers Alex's penicillin allergy without her needing to repeat it, providing safer and more personalized advice. |
| #253 | |
| #254 | 4. **Conversation Continuity**: The agent maintains context across the entire conversation session, creating a more natural and efficient interaction. |
| #255 | |
| #256 | ## Key Implementation Details |
| #257 | |
| #258 | ## User ID Management |
| #259 | |
| #260 | 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: |
| #261 | |
| #262 | ```python |
| #263 | # Set user_id for tools to access |
| #264 | save_patient_info.user_id = user_id |
| #265 | retrieve_patient_info.user_id = user_id |
| #266 | ``` |
| #267 | |
| #268 | Inside the tool functions, we retrieve this attribute: |
| #269 | |
| #270 | ```python |
| #271 | # Get user_id from session state or use default |
| #272 | user_id = getattr(save_patient_info, 'user_id', 'default_user') |
| #273 | ``` |
| #274 | |
| #275 | This approach allows our tools to maintain user context without complicating their parameter signatures. |
| #276 | |
| #277 | ## Mem0 Integration |
| #278 | |
| #279 | The integration with Mem0 happens through two primary functions: |
| #280 | |
| #281 | 1. `mem0_client.add()` - Stores new information with appropriate metadata |
| #282 | 2. `mem0_client.search()` - Retrieves relevant memories using semantic search |
| #283 | |
| #284 | The `threshold` parameter in the search function ensures that only highly relevant memories are returned. |
| #285 | |
| #286 | ## Conclusion |
| #287 | |
| #288 | 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. |
| #289 | |
| #290 | 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. |
| #291 | |
| #292 | --- |
| #293 | |
| #294 | <CardGroup cols={2}> |
| #295 | <Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories"> |
| #296 | Categorize patient data by symptoms, history, and visit context. |
| #297 | </Card> |
| #298 | <Card title="Support Inbox with Mem0" icon="headset" href="/cookbooks/operations/support-inbox"> |
| #299 | Apply similar memory patterns to customer support workflows. |
| #300 | </Card> |
| #301 | </CardGroup> |
| #302 |