server.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """
  2. FastAPI Server Example for Agency Swarm v1.x
  3. This example demonstrates how to serve agencies via FastAPI with proper
  4. streaming support, showing agent and callerAgent fields in responses.
  5. To run:
  6. 1. Set your OPENAI_API_KEY environment variable
  7. 2. Run: python server.py
  8. 3. Test with the client.py script or via curl/Postman
  9. """
  10. import os
  11. import shutil
  12. import sys
  13. import tempfile
  14. from pathlib import Path
  15. from typing import Literal
  16. # Path setup for standalone examples
  17. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "src")))
  18. from agency_swarm import (
  19. Agency,
  20. Agent,
  21. Handoff,
  22. ModelSettings,
  23. Reasoning,
  24. WebSearchTool,
  25. function_tool,
  26. run_fastapi,
  27. )
  28. # --- Simple Tools --- #
  29. @function_tool
  30. def CalculationTool(
  31. a: float,
  32. b: float,
  33. operation: Literal["add", "subtract", "multiply", "divide"] = "add",
  34. ) -> str:
  35. """Perform a basic arithmetic operation on two numbers."""
  36. if operation == "add":
  37. result = a + b
  38. elif operation == "subtract":
  39. result = a - b
  40. elif operation == "multiply":
  41. result = a * b
  42. elif operation == "divide":
  43. if b == 0:
  44. return "Error: Cannot divide by zero."
  45. result = a / b
  46. return f"Result: {result}"
  47. # --- Agent Setup --- #
  48. def create_agency(load_threads_callback=None):
  49. """Create a demo agency with two agents for testing communication flows."""
  50. # First agent - receives user requests
  51. agent = Agent(
  52. name="UserSupportAgent",
  53. description="Receives and coordinates user requests.",
  54. instructions=(
  55. "You are UserSupportAgent. Route and handle user requests as needed. "
  56. "Use your file tools when the user asks about files or asks to analyze data."
  57. ),
  58. files_folder=_prepare_runtime_files_folder(),
  59. include_search_results=True,
  60. tools=[WebSearchTool()],
  61. model="gpt-5.4-mini",
  62. model_settings=ModelSettings(reasoning=Reasoning(effort="low", summary="auto")),
  63. )
  64. # Second agent - performs tasks
  65. agent2 = Agent(
  66. name="MathAgent",
  67. description="Handles all math queries using CalculationTool.",
  68. instructions="You are MathAgent. Use CalculationTool for arithmetic questions.",
  69. tools=[CalculationTool],
  70. model="gpt-5.4-mini",
  71. model_settings=ModelSettings(reasoning=Reasoning(effort="high", summary="auto")),
  72. )
  73. # Create agency with communication flow
  74. agency = Agency(
  75. agent,
  76. agent2,
  77. communication_flows=[(agent, agent2, Handoff)],
  78. shared_instructions="Demonstrate inter-agent communication.",
  79. load_threads_callback=load_threads_callback,
  80. )
  81. return agency
  82. def _prepare_runtime_files_folder() -> str:
  83. """Create a disposable copy of examples/data for file-tool testing."""
  84. source_folder = Path(__file__).resolve().parent.parent / "data"
  85. if not source_folder.exists():
  86. raise FileNotFoundError(f"Expected example data directory at: {source_folder}")
  87. runtime_root = Path(tempfile.mkdtemp(prefix="agency-swarm-fastapi-files-"))
  88. files_folder = runtime_root / "files"
  89. shutil.copytree(source_folder, files_folder)
  90. return str(files_folder)
  91. # --- Main --- #
  92. if __name__ == "__main__":
  93. print("Starting FastAPI server for Agency Swarm")
  94. print("=" * 50)
  95. print("📍 Server will run at: http://localhost:8080")
  96. print("Available endpoints:")
  97. print(" - POST /my-agency/get_response")
  98. print(" - POST /my-agency/get_response_stream (SSE)")
  99. print(" - GET /my-agency/get_metadata")
  100. print("=" * 50)
  101. # Run the FastAPI server
  102. run_fastapi(
  103. agencies={
  104. "my-agency": create_agency,
  105. },
  106. port=8080,
  107. app_token_env="APP_TOKEN", # Optional: Set APP_TOKEN env var for authentication
  108. )