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: Google ADK |
| #3 | --- |
| #4 | |
| #5 | Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Google ADK (Agent Development Kit)](https://github.com/google/adk-python), an open-source framework for building multi-agent workflows. This integration enables agents to access persistent memory across conversations, enhancing context retention and personalization. |
| #6 | |
| #7 | ## Overview |
| #8 | |
| #9 | 1. Store and retrieve memories from Mem0 within Google ADK agents |
| #10 | 2. Multi-agent workflows with shared memory across hierarchies |
| #11 | 3. Retrieve relevant memories from past conversations |
| #12 | 4. Personalized responses based on user history |
| #13 | |
| #14 | ## Prerequisites |
| #15 | |
| #16 | Before setting up Mem0 with Google ADK, ensure you have: |
| #17 | |
| #18 | 1. Installed the required packages: |
| #19 | ```bash |
| #20 | pip install google-adk mem0ai python-dotenv |
| #21 | ``` |
| #22 | |
| #23 | 2. Valid API keys: |
| #24 | - [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys) |
| #25 | - Google AI Studio API Key |
| #26 | |
| #27 | ## Basic Integration Example |
| #28 | |
| #29 | The following example demonstrates how to create a Google ADK agent with Mem0 memory integration: |
| #30 | |
| #31 | ```python |
| #32 | import os |
| #33 | import asyncio |
| #34 | from google.adk.agents import Agent |
| #35 | from google.adk.runners import Runner |
| #36 | from google.adk.sessions import InMemorySessionService |
| #37 | from google.genai import types |
| #38 | from mem0 import MemoryClient |
| #39 | from dotenv import load_dotenv |
| #40 | |
| #41 | load_dotenv() |
| #42 | |
| #43 | # Set up environment variables |
| #44 | # os.environ["GOOGLE_API_KEY"] = "your-google-api-key" |
| #45 | # os.environ["MEM0_API_KEY"] = "your-mem0-api-key" |
| #46 | |
| #47 | # Initialize Mem0 client |
| #48 | mem0 = MemoryClient() |
| #49 | |
| #50 | # Define memory function tools |
| #51 | def search_memory(query: str, user_id: str) -> dict: |
| #52 | """Search through past conversations and memories""" |
| #53 | # For Platform API, user_id goes in filters |
| #54 | filters = {"user_id": user_id} |
| #55 | memories = mem0.search(query, filters=filters) |
| #56 | if memories.get('results', []): |
| #57 | memory_list = memories['results'] |
| #58 | memory_context = "\n".join([f"- {mem['memory']}" for mem in memory_list]) |
| #59 | return {"status": "success", "memories": memory_context} |
| #60 | return {"status": "no_memories", "message": "No relevant memories found"} |
| #61 | |
| #62 | def save_memory(content: str, user_id: str) -> dict: |
| #63 | """Save important information to memory""" |
| #64 | try: |
| #65 | result = mem0.add([{"role": "user", "content": content}], user_id=user_id) |
| #66 | return {"status": "success", "message": "Information saved to memory", "result": result} |
| #67 | except Exception as e: |
| #68 | return {"status": "error", "message": f"Failed to save memory: {str(e)}"} |
| #69 | |
| #70 | # Create agent with memory capabilities |
| #71 | personal_assistant = Agent( |
| #72 | name="personal_assistant", |
| #73 | model="gemini-2.0-flash", |
| #74 | instruction="""You are a helpful personal assistant with memory capabilities. |
| #75 | Use the search_memory function to recall past conversations and user preferences. |
| #76 | Use the save_memory function to store important information about the user. |
| #77 | Always personalize your responses based on available memory.""", |
| #78 | description="A personal assistant that remembers user preferences and past interactions", |
| #79 | tools=[search_memory, save_memory] |
| #80 | ) |
| #81 | |
| #82 | async def chat_with_agent(user_input: str, user_id: str) -> str: |
| #83 | """ |
| #84 | Handle user input with automatic memory integration. |
| #85 | |
| #86 | Args: |
| #87 | user_input: The user's message |
| #88 | user_id: Unique identifier for the user |
| #89 | |
| #90 | Returns: |
| #91 | The agent's response |
| #92 | """ |
| #93 | # Set up session and runner |
| #94 | session_service = InMemorySessionService() |
| #95 | session = await session_service.create_session( |
| #96 | app_name="memory_assistant", |
| #97 | user_id=user_id, |
| #98 | session_id=f"session_{user_id}" |
| #99 | ) |
| #100 | runner = Runner(agent=personal_assistant, app_name="memory_assistant", session_service=session_service) |
| #101 | |
| #102 | # Create content and run agent |
| #103 | content = types.Content(role='user', parts=[types.Part(text=user_input)]) |
| #104 | events = runner.run(user_id=user_id, session_id=session.id, new_message=content) |
| #105 | |
| #106 | # Extract final response |
| #107 | for event in events: |
| #108 | if event.is_final_response(): |
| #109 | response = event.content.parts[0].text |
| #110 | |
| #111 | return response |
| #112 | |
| #113 | return "No response generated" |
| #114 | |
| #115 | # Example usage |
| #116 | if __name__ == "__main__": |
| #117 | response = asyncio.run(chat_with_agent( |
| #118 | "I love Italian food and I'm planning a trip to Rome next month", |
| #119 | user_id="alice" |
| #120 | )) |
| #121 | print(response) |
| #122 | ``` |
| #123 | |
| #124 | ## Multi-Agent Hierarchy with Shared Memory |
| #125 | |
| #126 | Create specialized agents in a hierarchy that share memory: |
| #127 | |
| #128 | ```python |
| #129 | from google.adk.tools.agent_tool import AgentTool |
| #130 | |
| #131 | # Travel specialist agent |
| #132 | travel_agent = Agent( |
| #133 | name="travel_specialist", |
| #134 | model="gemini-2.0-flash", |
| #135 | instruction="""You are a travel planning specialist. Use search_memory to |
| #136 | understand the user's travel preferences and history before making recommendations. |
| #137 | After providing advice, use save_memory to save travel-related information.""", |
| #138 | description="Specialist in travel planning and recommendations", |
| #139 | tools=[search_memory, save_memory] |
| #140 | ) |
| #141 | |
| #142 | # Health advisor agent |
| #143 | health_agent = Agent( |
| #144 | name="health_advisor", |
| #145 | model="gemini-2.0-flash", |
| #146 | instruction="""You are a health and wellness advisor. Use search_memory to |
| #147 | understand the user's health goals and dietary preferences. |
| #148 | After providing advice, use save_memory to save health-related information.""", |
| #149 | description="Specialist in health and wellness advice", |
| #150 | tools=[search_memory, save_memory] |
| #151 | ) |
| #152 | |
| #153 | # Coordinator agent that delegates to specialists |
| #154 | coordinator_agent = Agent( |
| #155 | name="coordinator", |
| #156 | model="gemini-2.0-flash", |
| #157 | instruction="""You are a coordinator that delegates requests to specialist agents. |
| #158 | For travel-related questions (trips, hotels, flights, destinations), delegate to the travel specialist. |
| #159 | For health-related questions (fitness, diet, wellness, exercise), delegate to the health advisor. |
| #160 | Use search_memory to understand the user before delegation.""", |
| #161 | description="Coordinates requests between specialist agents", |
| #162 | tools=[ |
| #163 | AgentTool(agent=travel_agent, skip_summarization=False), |
| #164 | AgentTool(agent=health_agent, skip_summarization=False) |
| #165 | ] |
| #166 | ) |
| #167 | |
| #168 | def chat_with_specialists(user_input: str, user_id: str) -> str: |
| #169 | """ |
| #170 | Handle user input with specialist agent delegation and memory. |
| #171 | |
| #172 | Args: |
| #173 | user_input: The user's message |
| #174 | user_id: Unique identifier for the user |
| #175 | |
| #176 | Returns: |
| #177 | The specialist agent's response |
| #178 | """ |
| #179 | session_service = InMemorySessionService() |
| #180 | session = session_service.create_session( |
| #181 | app_name="specialist_system", |
| #182 | user_id=user_id, |
| #183 | session_id=f"session_{user_id}" |
| #184 | ) |
| #185 | runner = Runner(agent=coordinator_agent, app_name="specialist_system", session_service=session_service) |
| #186 | |
| #187 | content = types.Content(role='user', parts=[types.Part(text=user_input)]) |
| #188 | events = runner.run(user_id=user_id, session_id=session.id, new_message=content) |
| #189 | |
| #190 | for event in events: |
| #191 | if event.is_final_response(): |
| #192 | response = event.content.parts[0].text |
| #193 | |
| #194 | # Store the conversation in shared memory |
| #195 | conversation = [ |
| #196 | {"role": "user", "content": user_input}, |
| #197 | {"role": "assistant", "content": response} |
| #198 | ] |
| #199 | mem0.add(conversation, user_id=user_id) |
| #200 | |
| #201 | return response |
| #202 | |
| #203 | return "No response generated" |
| #204 | |
| #205 | # Example usage |
| #206 | response = chat_with_specialists("Plan a healthy meal for my Italy trip", user_id="alice") |
| #207 | print(response) |
| #208 | ``` |
| #209 | |
| #210 | |
| #211 | |
| #212 | ## Quick Start Chat Interface |
| #213 | |
| #214 | Simple interactive chat with memory and Google ADK: |
| #215 | |
| #216 | ```python |
| #217 | def interactive_chat(): |
| #218 | """Interactive chat interface with memory and ADK""" |
| #219 | user_id = input("Enter your user ID: ") or "demo_user" |
| #220 | print(f"Chat started for user: {user_id}") |
| #221 | print("Type 'quit' to exit") |
| #222 | print("=" * 50) |
| #223 | |
| #224 | while True: |
| #225 | user_input = input("\nYou: ") |
| #226 | |
| #227 | if user_input.lower() == 'quit': |
| #228 | print("Goodbye! Your conversation has been saved to memory.") |
| #229 | break |
| #230 | else: |
| #231 | response = chat_with_specialists(user_input, user_id) |
| #232 | print(f"Assistant: {response}") |
| #233 | |
| #234 | if __name__ == "__main__": |
| #235 | interactive_chat() |
| #236 | ``` |
| #237 | |
| #238 | ## Key Features |
| #239 | |
| #240 | ### 1. Memory-Enhanced Function Tools |
| #241 | - **Function Tools**: Standard Python functions that can search and save memories |
| #242 | - **Tool Context**: Access to session state and memory through function parameters |
| #243 | - **Structured Returns**: Dictionary-based returns with status indicators for better LLM understanding |
| #244 | |
| #245 | ### 2. Multi-Agent Memory Sharing |
| #246 | - **Agent-as-a-Tool**: Specialists can be called as tools while maintaining shared memory |
| #247 | - **Hierarchical Delegation**: Coordinator agents route to specialists based on context |
| #248 | - **Memory Categories**: Store interactions with metadata for better organization |
| #249 | |
| #250 | ### 3. Flexible Memory Operations |
| #251 | - **Search Capabilities**: Retrieve relevant memories through conversation history |
| #252 | - **User Segmentation**: Organize memories by user ID |
| #253 | - **Memory Management**: Built-in tools for saving and retrieving information |
| #254 | |
| #255 | ## Configuration Options |
| #256 | |
| #257 | Customize memory behavior and agent setup: |
| #258 | |
| #259 | ```python |
| #260 | # Configure memory search with filters |
| #261 | # For Platform API, all filters including user_id go in filters object |
| #262 | memories = mem0.search( |
| #263 | query="travel preferences", |
| #264 | filters={ |
| #265 | "AND": [ |
| #266 | {"user_id": "alice"}, |
| #267 | {"categories": {"contains": "travel"}} |
| #268 | ] |
| #269 | }, |
| #270 | limit=5 |
| #271 | ) |
| #272 | |
| #273 | # Configure agent with custom model settings |
| #274 | agent = Agent( |
| #275 | name="custom_agent", |
| #276 | model="gemini-2.0-flash", # or use LiteLLM for other models |
| #277 | instruction="Custom agent behavior", |
| #278 | tools=[memory_tools], |
| #279 | # Additional ADK configurations |
| #280 | ) |
| #281 | |
| #282 | # Use Google Cloud Vertex AI instead of AI Studio |
| #283 | os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True" |
| #284 | os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id" |
| #285 | os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1" |
| #286 | ``` |
| #287 | |
| #288 | <CardGroup cols={2}> |
| #289 | <Card title="Healthcare Agent Cookbook" icon="heart-pulse" href="/cookbooks/integrations/healthcare-google-adk"> |
| #290 | Build HIPAA-compliant healthcare agents with Google ADK |
| #291 | </Card> |
| #292 | <Card title="OpenAI Agents SDK" icon="cube" href="/integrations/openai-agents-sdk"> |
| #293 | Compare with OpenAI's agent framework |
| #294 | </Card> |
| #295 | </CardGroup> |
| #296 | |
| #297 |