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: Multi-Agent Collaboration |
| #3 | description: "Share a persistent memory layer across collaborating LlamaIndex agents." |
| #4 | --- |
| #5 | |
| #6 | |
| #7 | <Snippet file="blank-notif.mdx" /> |
| #8 | |
| #9 | Build an intelligent multi-agent learning system that uses Mem0 to maintain persistent memory across multiple specialized agents. This example demonstrates how to create a tutoring system where different agents collaborate while sharing a unified memory layer. |
| #10 | |
| #11 | ## Overview |
| #12 | |
| #13 | This example showcases a **Multi-Agent Personal Learning System** that combines: |
| #14 | - **LlamaIndex AgentWorkflow** for multi-agent orchestration |
| #15 | - **Mem0** for persistent, shared memory across agents |
| #16 | - **Multiple agents** that collaborate on teaching tasks |
| #17 | |
| #18 | The system consists of two agents: |
| #19 | - **TutorAgent**: Primary instructor for explanations and concept teaching |
| #20 | - **PracticeAgent**: Generates exercises and tracks learning progress |
| #21 | |
| #22 | Both agents share the same memory context, enabling seamless collaboration and continuous learning from student interactions. |
| #23 | |
| #24 | ## Key Features |
| #25 | |
| #26 | - **Persistent Memory**: Agents remember previous interactions across sessions |
| #27 | - **Multi-Agent Collaboration**: Agents can hand off tasks to each other |
| #28 | - **Personalized Learning**: Adapts to individual student needs and learning styles |
| #29 | - **Progress Tracking**: Monitors learning patterns and skill development |
| #30 | - **Memory-Driven Teaching**: References past struggles and successes |
| #31 | |
| #32 | ## Prerequisites |
| #33 | |
| #34 | Install the required packages: |
| #35 | |
| #36 | ```bash |
| #37 | pip install llama-index-core llama-index-memory-mem0 openai python-dotenv |
| #38 | ``` |
| #39 | |
| #40 | Set up your environment variables: |
| #41 | - `MEM0_API_KEY`: Your Mem0 Platform API key |
| #42 | - `OPENAI_API_KEY`: Your OpenAI API key |
| #43 | |
| #44 | You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai). |
| #45 | |
| #46 | ## Complete Implementation |
| #47 | |
| #48 | ```python |
| #49 | """ |
| #50 | Multi-Agent Personal Learning System: Mem0 + LlamaIndex AgentWorkflow Example |
| #51 | |
| #52 | INSTALLATIONS: |
| #53 | !pip install llama-index-core llama-index-memory-mem0 openai |
| #54 | |
| #55 | You need MEM0_API_KEY and OPENAI_API_KEY to run the example. |
| #56 | """ |
| #57 | |
| #58 | import asyncio |
| #59 | from datetime import datetime |
| #60 | from dotenv import load_dotenv |
| #61 | |
| #62 | # LlamaIndex imports |
| #63 | from llama_index.core.agent.workflow import AgentWorkflow, FunctionAgent |
| #64 | from llama_index.llms.openai import OpenAI |
| #65 | from llama_index.core.tools import FunctionTool |
| #66 | |
| #67 | # Memory integration |
| #68 | from llama_index.memory.mem0 import Mem0Memory |
| #69 | |
| #70 | import warnings |
| #71 | warnings.filterwarnings("ignore", category=DeprecationWarning) |
| #72 | |
| #73 | load_dotenv() |
| #74 | |
| #75 | |
| #76 | class MultiAgentLearningSystem: |
| #77 | """ |
| #78 | Multi-Agent Architecture: |
| #79 | - TutorAgent: Main teaching and explanations |
| #80 | - PracticeAgent: Exercises and skill reinforcement |
| #81 | - Shared Memory: Both agents learn from student interactions |
| #82 | """ |
| #83 | |
| #84 | def __init__(self, student_id: str): |
| #85 | self.student_id = student_id |
| #86 | self.llm = OpenAI(model="gpt-4.1-nano-2025-04-14", temperature=0.2) |
| #87 | |
| #88 | # Memory context for this student |
| #89 | self.memory_context = {"user_id": student_id, "app": "learning_assistant"} |
| #90 | self.memory = Mem0Memory.from_client( |
| #91 | context=self.memory_context |
| #92 | ) |
| #93 | |
| #94 | self._setup_agents() |
| #95 | |
| #96 | def _setup_agents(self): |
| #97 | """Setup two agents that work together and share memory""" |
| #98 | |
| #99 | # TOOLS |
| #100 | async def assess_understanding(topic: str, student_response: str) -> str: |
| #101 | """Assess student's understanding of a topic and save insights""" |
| #102 | # Simulate assessment logic |
| #103 | if "confused" in student_response.lower() or "don't understand" in student_response.lower(): |
| #104 | assessment = f"STRUGGLING with {topic}: {student_response}" |
| #105 | insight = f"Student needs more help with {topic}. Prefers step-by-step explanations." |
| #106 | elif "makes sense" in student_response.lower() or "got it" in student_response.lower(): |
| #107 | assessment = f"UNDERSTANDS {topic}: {student_response}" |
| #108 | insight = f"Student grasped {topic} quickly. Can move to advanced concepts." |
| #109 | else: |
| #110 | assessment = f"PARTIAL understanding of {topic}: {student_response}" |
| #111 | insight = f"Student has basic understanding of {topic}. Needs reinforcement." |
| #112 | |
| #113 | return f"Assessment: {assessment}\nInsight saved: {insight}" |
| #114 | |
| #115 | async def track_progress(topic: str, success_rate: str) -> str: |
| #116 | """Track learning progress and identify patterns""" |
| #117 | progress_note = f"Progress on {topic}: {success_rate} - {datetime.now().strftime('%Y-%m-%d')}" |
| #118 | return f"Progress tracked: {progress_note}" |
| #119 | |
| #120 | # Convert to FunctionTools |
| #121 | tools = [ |
| #122 | FunctionTool.from_defaults(async_fn=assess_understanding), |
| #123 | FunctionTool.from_defaults(async_fn=track_progress) |
| #124 | ] |
| #125 | |
| #126 | # AGENTS |
| #127 | # Tutor Agent - Main teaching and explanation |
| #128 | self.tutor_agent = FunctionAgent( |
| #129 | name="TutorAgent", |
| #130 | description="Primary instructor that explains concepts and adapts to student needs", |
| #131 | system_prompt=""" |
| #132 | You are a patient, adaptive programming tutor. Your key strength is REMEMBERING and BUILDING on previous interactions. |
| #133 | |
| #134 | Key Behaviors: |
| #135 | 1. Always check what the student has learned before (use memory context) |
| #136 | 2. Adapt explanations based on their preferred learning style |
| #137 | 3. Reference previous struggles or successes |
| #138 | 4. Build progressively on past lessons |
| #139 | 5. Use assess_understanding to evaluate responses and save insights |
| #140 | |
| #141 | MEMORY-DRIVEN TEACHING: |
| #142 | - "Last time you struggled with X, so let's approach Y differently..." |
| #143 | - "Since you prefer visual examples, here's a diagram..." |
| #144 | - "Building on the functions we covered yesterday..." |
| #145 | |
| #146 | When student shows understanding, hand off to PracticeAgent for exercises. |
| #147 | """, |
| #148 | tools=tools, |
| #149 | llm=self.llm, |
| #150 | can_handoff_to=["PracticeAgent"] |
| #151 | ) |
| #152 | |
| #153 | # Practice Agent - Exercises and reinforcement |
| #154 | self.practice_agent = FunctionAgent( |
| #155 | name="PracticeAgent", |
| #156 | description="Creates practice exercises and tracks progress based on student's learning history", |
| #157 | system_prompt=""" |
| #158 | You create personalized practice exercises based on the student's learning history and current level. |
| #159 | |
| #160 | Key Behaviors: |
| #161 | 1. Generate problems that match their skill level (from memory) |
| #162 | 2. Focus on areas they've struggled with previously |
| #163 | 3. Gradually increase difficulty based on their progress |
| #164 | 4. Use track_progress to record their performance |
| #165 | 5. Provide encouraging feedback that references their growth |
| #166 | |
| #167 | MEMORY-DRIVEN PRACTICE: |
| #168 | - "Let's practice loops again since you wanted more examples..." |
| #169 | - "Here's a harder version of the problem you solved yesterday..." |
| #170 | - "You've improved a lot in functions, ready for the next level?" |
| #171 | |
| #172 | After practice, can hand back to TutorAgent for concept review if needed. |
| #173 | """, |
| #174 | tools=tools, |
| #175 | llm=self.llm, |
| #176 | can_handoff_to=["TutorAgent"] |
| #177 | ) |
| #178 | |
| #179 | # Create the multi-agent workflow |
| #180 | self.workflow = AgentWorkflow( |
| #181 | agents=[self.tutor_agent, self.practice_agent], |
| #182 | root_agent=self.tutor_agent.name, |
| #183 | initial_state={ |
| #184 | "current_topic": "", |
| #185 | "student_level": "beginner", |
| #186 | "learning_style": "unknown", |
| #187 | "session_goals": [] |
| #188 | } |
| #189 | ) |
| #190 | |
| #191 | async def start_learning_session(self, topic: str, student_message: str = "") -> str: |
| #192 | """ |
| #193 | Start a learning session with multi-agent memory-aware teaching |
| #194 | """ |
| #195 | |
| #196 | if student_message: |
| #197 | request = f"I want to learn about {topic}. {student_message}" |
| #198 | else: |
| #199 | request = f"I want to learn about {topic}." |
| #200 | |
| #201 | # The magic happens here - multi-agent memory is automatically shared! |
| #202 | response = await self.workflow.run( |
| #203 | user_msg=request, |
| #204 | memory=self.memory |
| #205 | ) |
| #206 | |
| #207 | return str(response) |
| #208 | |
| #209 | async def get_learning_history(self) -> str: |
| #210 | """Show what the system remembers about this student""" |
| #211 | try: |
| #212 | # Search memory for learning patterns |
| #213 | memories = self.memory.search( |
| #214 | user_id=self.student_id, |
| #215 | query="learning machine learning" |
| #216 | ) |
| #217 | |
| #218 | if memories and memories.get('results'): |
| #219 | history = "\n".join(f"- {m['memory']}" for m in memories['results']) |
| #220 | return history |
| #221 | else: |
| #222 | return "No learning history found yet. Let's start building your profile!" |
| #223 | |
| #224 | except Exception as e: |
| #225 | return f"Memory retrieval error: {str(e)}" |
| #226 | |
| #227 | |
| #228 | async def run_learning_agent(): |
| #229 | |
| #230 | learning_system = MultiAgentLearningSystem(student_id="Alexander") |
| #231 | |
| #232 | # First session |
| #233 | print("Session 1:") |
| #234 | response = await learning_system.start_learning_session( |
| #235 | "Vision Language Models", |
| #236 | "I'm new to machine learning but I have good hold on Python and have 4 years of work experience.") |
| #237 | print(response) |
| #238 | |
| #239 | # Second session - multi-agent memory will remember the first |
| #240 | print("\nSession 2:") |
| #241 | response2 = await learning_system.start_learning_session( |
| #242 | "Machine Learning", "what all did I cover so far?") |
| #243 | print(response2) |
| #244 | |
| #245 | # Show what the multi-agent system remembers |
| #246 | print("\nLearning History:") |
| #247 | history = await learning_system.get_learning_history() |
| #248 | print(history) |
| #249 | |
| #250 | |
| #251 | if __name__ == "__main__": |
| #252 | """Run the example""" |
| #253 | print("Multi-agent Learning System powered by LlamaIndex and Mem0") |
| #254 | |
| #255 | async def main(): |
| #256 | await run_learning_agent() |
| #257 | |
| #258 | asyncio.run(main()) |
| #259 | ``` |
| #260 | |
| #261 | ## How It Works |
| #262 | |
| #263 | ### 1. Memory Context Setup |
| #264 | |
| #265 | ```python |
| #266 | # Memory context for this student |
| #267 | self.memory_context = {"user_id": student_id, "app": "learning_assistant"} |
| #268 | self.memory = Mem0Memory.from_client(context=self.memory_context) |
| #269 | ``` |
| #270 | |
| #271 | The memory context identifies the specific student and application, ensuring memory isolation and proper retrieval. |
| #272 | |
| #273 | ### 2. Agent Collaboration |
| #274 | |
| #275 | ```python |
| #276 | # Agents can hand off to each other |
| #277 | can_handoff_to=["PracticeAgent"] # TutorAgent can hand off to PracticeAgent |
| #278 | can_handoff_to=["TutorAgent"] # PracticeAgent can hand off back |
| #279 | ``` |
| #280 | |
| #281 | Agents collaborate seamlessly, with the TutorAgent handling explanations and the PracticeAgent managing exercises. |
| #282 | |
| #283 | ### 3. Shared Memory |
| #284 | |
| #285 | ```python |
| #286 | # Both agents share the same memory instance |
| #287 | response = await self.workflow.run( |
| #288 | user_msg=request, |
| #289 | memory=self.memory # Shared across all agents |
| #290 | ) |
| #291 | ``` |
| #292 | |
| #293 | All agents in the workflow share the same memory context, enabling true collaborative learning. |
| #294 | |
| #295 | ### 4. Memory-Driven Interactions |
| #296 | |
| #297 | The system prompts guide agents to: |
| #298 | - Reference previous learning sessions |
| #299 | - Adapt to discovered learning styles |
| #300 | - Build progressively on past lessons |
| #301 | - Track and respond to learning patterns |
| #302 | |
| #303 | ## Running the Example |
| #304 | |
| #305 | ```python |
| #306 | # Initialize the learning system |
| #307 | learning_system = MultiAgentLearningSystem(student_id="Alexander") |
| #308 | |
| #309 | # Start a learning session |
| #310 | response = await learning_system.start_learning_session( |
| #311 | "Vision Language Models", |
| #312 | "I'm new to machine learning but I have good hold on Python and have 4 years of work experience." |
| #313 | ) |
| #314 | |
| #315 | # Continue learning in a new session (memory persists) |
| #316 | response2 = await learning_system.start_learning_session( |
| #317 | "Machine Learning", |
| #318 | "what all did I cover so far?" |
| #319 | ) |
| #320 | |
| #321 | # Check learning history |
| #322 | history = await learning_system.get_learning_history() |
| #323 | ``` |
| #324 | |
| #325 | ## Expected Output |
| #326 | |
| #327 | The system will demonstrate memory-aware interactions: |
| #328 | |
| #329 | ``` |
| #330 | Session 1: |
| #331 | I understand you want to learn about Vision Language Models and you mentioned you're new to machine learning but have a strong Python background with 4 years of experience. That's a great foundation to build on! |
| #332 | |
| #333 | Let me start with an explanation tailored to your programming background... |
| #334 | [Agent provides explanation and may hand off to PracticeAgent for exercises] |
| #335 | |
| #336 | Session 2: |
| #337 | Based on our previous session, I remember we covered Vision Language Models and I noted that you have a strong Python background with 4 years of experience. You mentioned being new to machine learning, so we started with foundational concepts... |
| #338 | [Agent references previous session and builds upon it] |
| #339 | ``` |
| #340 | |
| #341 | ## Key Benefits |
| #342 | |
| #343 | 1. **Persistent Learning**: Agents remember across sessions, creating continuity |
| #344 | 2. **Collaborative Teaching**: Multiple specialized agents work together seamlessly |
| #345 | 3. **Personalized Adaptation**: System learns and adapts to individual learning styles |
| #346 | 4. **Scalable Architecture**: Easy to add more specialized agents |
| #347 | 5. **Memory Efficiency**: Shared memory prevents duplication and ensures consistency |
| #348 | |
| #349 | |
| #350 | ## Best Practices |
| #351 | |
| #352 | 1. **Clear Agent Roles**: Define specific responsibilities for each agent |
| #353 | 2. **Memory Context**: Use descriptive context for memory isolation |
| #354 | 3. **Handoff Strategy**: Design clear handoff criteria between agents |
| #355 | 4. **Memory Hygiene**: Regularly review and clean memory for optimal performance |
| #356 | |
| #357 | ## Help & Resources |
| #358 | |
| #359 | - [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/use_cases/agents/) |
| #360 | - [Mem0 Platform](https://app.mem0.ai/) |
| #361 | |
| #362 | --- |
| #363 | |
| #364 | <CardGroup cols={2}> |
| #365 | <Card title="LlamaIndex ReAct with Mem0" icon="brain" href="/cookbooks/frameworks/llamaindex-react"> |
| #366 | Start with single-agent patterns before scaling to multi-agent systems. |
| #367 | </Card> |
| #368 | <Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook"> |
| #369 | Learn how to scope memories across multiple agents, users, and sessions. |
| #370 | </Card> |
| #371 | </CardGroup> |
| #372 |