agency_context.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """
  2. Agency Context Example
  3. Simple demonstration of sharing data between agents using agency context.
  4. Shows how one agent can store data and another can retrieve it.
  5. """
  6. import asyncio
  7. import logging
  8. import os
  9. import sys
  10. # Path setup for standalone examples
  11. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
  12. from agency_swarm import Agency, Agent, MasterContext, RunContextWrapper, function_tool
  13. # Minimal logging setup
  14. logging.basicConfig(level=logging.WARNING)
  15. logging.getLogger("agency_swarm").setLevel(logging.WARNING)
  16. # --- Data Storage Tools --- #
  17. @function_tool
  18. async def store_customer_data(ctx: RunContextWrapper[MasterContext], customer_id: str, name: str) -> str:
  19. """Store customer information in agency context."""
  20. context: MasterContext = ctx.context
  21. customer_data = {"id": customer_id, "name": name, "status": "active"}
  22. context.set("customer_data", customer_data)
  23. return f"Stored customer data for {name} (ID: {customer_id})"
  24. @function_tool
  25. async def get_customer_data(ctx: RunContextWrapper[MasterContext]) -> str:
  26. """Retrieve customer information from agency context."""
  27. context: MasterContext = ctx.context
  28. customer_data = context.get("customer_data")
  29. if not customer_data:
  30. return "No customer data found. Please store customer data first."
  31. return f"Customer: {customer_data['name']} (ID: {customer_data['id']}, Status: {customer_data['status']})"
  32. @function_tool
  33. async def analyze_customer(ctx: RunContextWrapper[MasterContext]) -> str:
  34. """Analyze customer using data from agency context."""
  35. context: MasterContext = ctx.context
  36. customer_data = context.get("customer_data")
  37. if not customer_data:
  38. return "Cannot analyze - no customer data available."
  39. # Store analysis results
  40. analysis = {"customer_id": customer_data["id"], "risk_level": "low", "recommendation": "approved"}
  41. context.set("customer_analysis", analysis)
  42. return (
  43. f"Analysis complete for {customer_data['name']}: {analysis['recommendation']} (risk: {analysis['risk_level']})"
  44. )
  45. @function_tool
  46. async def show_context_summary(ctx: RunContextWrapper[MasterContext]) -> str:
  47. """Show what's currently stored in agency context."""
  48. context: MasterContext = ctx.context
  49. customer_data = context.get("customer_data")
  50. analysis = context.get("customer_analysis")
  51. summary = "Agency Context Summary:\n"
  52. if customer_data:
  53. summary += f"• Customer: {customer_data['name']} ({customer_data['id']})\n"
  54. else:
  55. summary += "• Customer: None\n"
  56. if analysis:
  57. summary += f"• Analysis: {analysis['recommendation']} ({analysis['risk_level']} risk)\n"
  58. else:
  59. summary += "• Analysis: None\n"
  60. return summary
  61. # --- Agents --- #
  62. data_agent = Agent(
  63. name="DataAgent",
  64. instructions="You handle customer data storage and retrieval. Use your tools to store and access customer information.",
  65. tools=[store_customer_data, get_customer_data, show_context_summary],
  66. )
  67. analyst_agent = Agent(
  68. name="AnalystAgent",
  69. instructions="You analyze customers using data stored by other agents. Access customer data from agency context.",
  70. tools=[analyze_customer, get_customer_data, show_context_summary],
  71. )
  72. # --- Agency Setup --- #
  73. agency = Agency(
  74. data_agent,
  75. communication_flows=[data_agent > analyst_agent],
  76. user_context={"session_id": "demo_session", "system": "agency_context_demo"},
  77. )
  78. # --- Demo --- #
  79. async def run_demo():
  80. """Demonstrate agency context sharing between agents."""
  81. print("Agency Context Demo")
  82. print("=" * 40)
  83. # Step 1: Store customer data
  84. print("\nStep 1: Storing customer data...")
  85. response1 = await agency.get_response(message="Please store customer data: ID 'CUST123', name 'Alice Johnson'")
  86. print(f"✅ {response1.final_output}")
  87. # Step 2: Delegate analysis to another agent
  88. print("\nStep 2: Asking data agent to delegate analysis...")
  89. response2 = await agency.get_response(
  90. message="Please ask the analyst agent to analyze the customer data I just stored."
  91. )
  92. print(f"✅ {response2.final_output}")
  93. # Step 3: Show final context state
  94. print("\nStep 3: Checking final agency context...")
  95. response3 = await agency.get_response(message="Show me a summary of what's currently stored in the agency context.")
  96. print(f"✅ {response3.final_output}")
  97. print("\nDemo complete!")
  98. if __name__ == "__main__":
  99. asyncio.run(run_demo())