hybrid_communication_flows.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. """
  2. Hybrid Communication Flows Example
  3. This example demonstrates advanced communication patterns in Agency Swarm by combining
  4. two different communication mechanisms: SendMessage tools and handoffs.
  5. ## Agents and Their Roles
  6. - **ProjectManager**: Coordinates projects using custom context-aware messaging
  7. - **Developer**: Implements features and transfers to security expert when needed
  8. - **SecurityExpert**: Performs security audits and vulnerability assessments
  9. ## Communication Flow
  10. The agency demonstrates a real-world software development workflow:
  11. 1. ProjectManager delegates tasks with project context and priority
  12. 2. Developer implements features and reviews code quality
  13. 3. Developer can transfer to SecurityExpert for security-sensitive work
  14. 4. SecurityExpert performs audits and returns findings
  15. ## Usage
  16. Run this example with: python examples/hybrid_communication_flows.py
  17. It will open the TUI for the agency, where you can interact with the agency.
  18. Ask ProjectManager to implement a new feature with code quality review and security audit.
  19. For example, you can use the following input query:
  20. '''
  21. We need to implement a user authentication system for our web application.
  22. This is a high priority item for our security review phase.
  23. Please implement the feature and ensure it meets security standards.
  24. '''
  25. """
  26. import logging
  27. import os
  28. import sys
  29. # Path setup so the example can be run standalone
  30. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
  31. from pydantic import Field
  32. from agency_swarm import Agency, Agent, ModelSettings, function_tool
  33. from agency_swarm.tools.send_message import Handoff, SendMessage
  34. # Setup logging
  35. logging.basicConfig(level=logging.WARNING)
  36. logging.getLogger("agency_swarm").setLevel(
  37. logging.DEBUG if os.getenv("DEBUG_LOGS", "False").lower() == "true" else logging.WARNING
  38. )
  39. # Define tools for the agents
  40. @function_tool
  41. def review_code_quality(code_snippet: str) -> str:
  42. """Review code for quality, best practices, and potential improvements."""
  43. return f"Code quality review complete for {len(code_snippet)} characters. Found 2 minor improvements: variable naming and error handling."
  44. @function_tool
  45. def implement_feature(feature_name: str) -> str:
  46. """Implement a software feature with basic structure."""
  47. return f"Feature '{feature_name}' implemented with authentication middleware, input validation, and error handling."
  48. @function_tool
  49. def security_audit(component: str) -> str:
  50. """Perform comprehensive security audit of a component."""
  51. return f"Security audit complete for {component}. Found: 1 SQL injection vulnerability, 2 XSS risks, authentication bypass potential. Recommendations provided."
  52. @function_tool
  53. def vulnerability_scan(target: str) -> str:
  54. """Scan for known vulnerabilities and security weaknesses."""
  55. return f"Vulnerability scan of {target} complete. Detected 3 medium-risk issues: outdated dependencies, weak encryption, missing rate limiting."
  56. # Custom SendMessage that adds project context
  57. class SendMessageWithProjectContext(SendMessage):
  58. """SendMessage with project context tracking."""
  59. tool_name = "send_message_with_context"
  60. project_phase: str = Field(
  61. description=(
  62. "Current phase of the project (planning, development, testing, security_review, deployment). "
  63. "This helps the recipient understand the urgency and focus area for their response."
  64. )
  65. )
  66. priority_level: str = Field(
  67. description=(
  68. "Priority level of this task. Critical items need immediate attention, "
  69. "high priority items should be completed within the day."
  70. )
  71. )
  72. project_manager = Agent(
  73. name="ProjectManager",
  74. description="Coordinates software development projects and ensures quality delivery",
  75. instructions=(
  76. "You are a Project Manager responsible for coordinating software development projects. "
  77. "Your role is to delegate tasks, track progress, and ensure deliverables meet requirements. "
  78. "When delegating work, always specify the project phase and priority level. "
  79. "CRITICAL: When you receive responses from team members, include their complete "
  80. "findings and recommendations in your final output to maintain transparency."
  81. ),
  82. model_settings=ModelSettings(temperature=0),
  83. )
  84. developer = Agent(
  85. name="Developer",
  86. description="Software developer who implements features and coordinates with security experts",
  87. instructions=(
  88. "You are a Senior Developer responsible for implementing software features. "
  89. "You have access to code quality review and feature implementation tools. "
  90. "When working on security-sensitive features, you must consult the SecurityExpert using handoff (transfer) tool. "
  91. "Always provide detailed technical responses including any tool outputs. "
  92. "When performing handoffs, transfer complete context including all technical details."
  93. ),
  94. tools=[review_code_quality, implement_feature],
  95. model_settings=ModelSettings(temperature=0),
  96. )
  97. security_expert = Agent(
  98. name="SecurityExpert",
  99. description="Security specialist who performs audits and vulnerability assessments",
  100. instructions=(
  101. "You are a Security Expert specializing in application security audits. "
  102. "You have access to security audit and vulnerability scanning tools. "
  103. "Provide comprehensive security assessments with specific recommendations. "
  104. "Always run appropriate security tools and include complete findings in your response. "
  105. "Focus on practical, actionable security improvements."
  106. ),
  107. tools=[security_audit, vulnerability_scan],
  108. model_settings=ModelSettings(temperature=0),
  109. )
  110. agency = Agency(
  111. project_manager,
  112. communication_flows=[
  113. (project_manager > developer > security_expert, Handoff),
  114. ],
  115. shared_instructions="Focus on delivering secure, high-quality software. Use project context to prioritize work.",
  116. )
  117. if __name__ == "__main__":
  118. agency.tui()