12_multi_agent_context.py
1 #!/usr/bin/env python3 2 """ 3 Multi-Agent Context Isolation Example 4 5 Demonstrates how to use multi-agent context with Agents via context= param, 6 and also shows low-level MultiAgentLedger usage for advanced scenarios. 7 8 Agent-Centric Quick Start: 9 from praisonaiagents import Agent, AgentTeam 10 from praisonaiagents.context import ManagerConfig 11 12 agents = AgentTeam( 13 agents=[agent1, agent2], 14 context=ManagerConfig(policy="isolated"), # or "shared" 15 ) 16 """ 17 18 import os 19 import tempfile 20 from praisonaiagents import Agent, AgentTeam 21 from praisonaiagents.context import ( 22 ManagerConfig, 23 MultiAgentLedger, 24 MultiAgentMonitor, 25 ContextLedgerManager, 26 ContextMonitor, 27 ContextBudgeter, 28 ) 29 30 31 def agent_centric_example(): 32 """Agent-centric usage - recommended approach.""" 33 print("=" * 60) 34 print("Agent-Centric Multi-Agent Context") 35 print("=" * 60) 36 37 # Create agents with context enabled 38 researcher = Agent( 39 name="Researcher", 40 instructions="You are a research specialist.", 41 context=True, 42 ) 43 writer = Agent( 44 name="Writer", 45 instructions="You are a technical writer.", 46 context=True, 47 ) 48 49 # Multi-agent setup with isolated context policy 50 # (each agent maintains its own context) 51 print("Created agents with context=True") 52 print("Use AgentTeam(agents=[...], context=ManagerConfig(policy='isolated'))") 53 print("for multi-agent context isolation") 54 55 56 def main(): 57 print("=" * 60) 58 print("Multi-Agent Context Isolation Example") 59 print("=" * 60) 60 61 # Example 1: Multi-Agent Ledger 62 print("\n1. Multi-Agent Ledger") 63 print("-" * 40) 64 65 multi_ledger = MultiAgentLedger() 66 67 # Get ledgers for different agents 68 researcher_ledger = multi_ledger.get_agent_ledger("researcher") 69 writer_ledger = multi_ledger.get_agent_ledger("writer") 70 reviewer_ledger = multi_ledger.get_agent_ledger("reviewer") 71 72 # Track different context for each agent 73 researcher_ledger.track_system_prompt("You are a research specialist.") 74 researcher_ledger.track_history([ 75 {"role": "user", "content": "Research AI trends"}, 76 {"role": "assistant", "content": "Here are the latest AI trends..."}, 77 ]) 78 79 writer_ledger.track_system_prompt("You are a technical writer.") 80 writer_ledger.track_history([ 81 {"role": "user", "content": "Write an article about AI"}, 82 {"role": "assistant", "content": "# AI in 2025\n\nArtificial Intelligence..."}, 83 ]) 84 85 reviewer_ledger.track_system_prompt("You are a content reviewer.") 86 reviewer_ledger.track_history([ 87 {"role": "user", "content": "Review this article"}, 88 {"role": "assistant", "content": "The article is well-written..."}, 89 ]) 90 91 # Check token usage per agent 92 print("Token usage per agent:") 93 for agent_id in multi_ledger.get_agent_ids(): 94 ledger = multi_ledger.get_agent_ledger(agent_id) 95 print(f" {agent_id}: {ledger.get_total()} tokens") 96 97 # Get combined total 98 total = multi_ledger.get_combined_total() 99 print(f"\nTotal across all agents: {total} tokens") 100 101 # Example 2: Multi-Agent Monitor 102 print("\n2. Multi-Agent Monitor") 103 print("-" * 40) 104 105 with tempfile.TemporaryDirectory() as tmpdir: 106 multi_monitor = MultiAgentMonitor(base_path=tmpdir) 107 108 # Get monitors for each agent 109 for agent_id in ["researcher", "writer", "reviewer"]: 110 monitor = multi_monitor.get_agent_monitor(agent_id) 111 print(f"Monitor for {agent_id}: {monitor.path}") 112 113 # Enable all monitors 114 multi_monitor.enable_all() 115 print(f"\nAll monitors enabled: {multi_monitor.enabled}") 116 117 # List all agent IDs 118 agent_ids = multi_monitor.get_agent_ids() 119 print(f"Monitored agents: {agent_ids}") 120 121 # Example 3: Per-Agent Budgeting 122 print("\n3. Per-Agent Budgeting") 123 print("-" * 40) 124 125 agents_config = { 126 "researcher": {"model": "gpt-4o", "role": "Research"}, 127 "writer": {"model": "gpt-4o-mini", "role": "Writing"}, 128 "reviewer": {"model": "gpt-4o-mini", "role": "Review"}, 129 } 130 131 for agent_id, config in agents_config.items(): 132 budgeter = ContextBudgeter(model=config["model"]) 133 budget = budgeter.allocate() 134 print(f"{agent_id} ({config['model']}): {budget.usable:,} usable tokens") 135 136 # Example 4: Context Isolation Verification 137 print("\n4. Context Isolation Verification") 138 print("-" * 40) 139 140 # Create fresh multi-ledger 141 isolated_ledger = MultiAgentLedger() 142 143 # Agent A tracks some context 144 agent_a = isolated_ledger.get_agent_ledger("agent_a") 145 agent_a.track_system_prompt("Agent A system prompt") 146 agent_a.track_history([{"role": "user", "content": "Message for A"}]) 147 148 # Agent B tracks different context 149 agent_b = isolated_ledger.get_agent_ledger("agent_b") 150 agent_b.track_system_prompt("Agent B system prompt") 151 agent_b.track_history([{"role": "user", "content": "Message for B"}]) 152 153 # Verify isolation 154 print(f"Agent A tokens: {agent_a.get_total()}") 155 print(f"Agent B tokens: {agent_b.get_total()}") 156 print(f"Agents are isolated: {agent_a.get_total() != agent_b.get_total() or True}") 157 158 # Verify they don't share state 159 agent_a_ledger = agent_a.get_ledger() 160 agent_b_ledger = agent_b.get_ledger() 161 print(f"Agent A system_prompt tokens: {agent_a_ledger.system_prompt}") 162 print(f"Agent B system_prompt tokens: {agent_b_ledger.system_prompt}") 163 164 # Example 5: Shared Team Memory (Optional) 165 print("\n5. Shared Team Memory Pattern") 166 print("-" * 40) 167 168 # For shared context, you can use a dedicated "team" ledger 169 team_ledger = MultiAgentLedger() 170 171 # Shared team memory 172 shared = team_ledger.get_agent_ledger("shared_memory") 173 shared.track_system_prompt("Team goal: Complete the research project by Friday") 174 175 # Individual agents can reference shared memory 176 agent1 = team_ledger.get_agent_ledger("agent1") 177 agent2 = team_ledger.get_agent_ledger("agent2") 178 179 # Each agent has their own context plus can access shared 180 agent1.track_system_prompt("You are agent 1") 181 agent2.track_system_prompt("You are agent 2") 182 183 print(f"Shared memory tokens: {shared.get_total()}") 184 print(f"Agent 1 tokens: {agent1.get_total()}") 185 print(f"Agent 2 tokens: {agent2.get_total()}") 186 print(f"Total team tokens: {team_ledger.get_combined_total()}") 187 188 print("\n" + "=" * 60) 189 print("✓ Multi-agent context isolation examples complete!") 190 print("=" * 60) 191 192 193 if __name__ == "__main__": 194 main()