api.mdx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. ---
  2. title: "API Reference"
  3. description: "Gain a deeper understanding of the core classes and methods available in Agency Swarm."
  4. icon: "book"
  5. ---
  6. ## Agency Class
  7. The Agency class orchestrates a collection of Agent instances based on entry points and communication flows.
  8. ```python
  9. from agency_swarm import Agency, Agent
  10. class Agency:
  11. def __init__(
  12. self,
  13. *entry_point_agents: Agent,
  14. communication_flows: list[CommunicationFlowEntry] | None = None,
  15. name: str | None = None,
  16. shared_instructions: str | None = None,
  17. shared_tools: list[Tool] | None = None,
  18. shared_tools_folder: str | None = None,
  19. shared_files_folder: str | None = None,
  20. shared_mcp_servers: list[Any] | None = None,
  21. send_message_tool_class: type | None = None,
  22. load_threads_callback: ThreadLoadCallback | None = None,
  23. save_threads_callback: ThreadSaveCallback | None = None,
  24. user_context: dict[str, Any] | None = None,
  25. ):
  26. """
  27. Initialize an Agency instance.
  28. Parameters:
  29. *entry_point_agents: Agent instances serving as entry points for external interaction
  30. communication_flows: Flexible communication flow definitions supporting tuples and AgentFlow objects
  31. name: Optional name for the agency
  32. shared_instructions: Instruction text or file path applied to every agent
  33. shared_tools: Tool instances or BaseTool classes to add to all agents (each agent gets independent copies)
  34. shared_tools_folder: Path to folder containing tool files to load and share with all agents
  35. shared_files_folder: Path to folder of files to upload and share with all agents via a common vector store
  36. shared_mcp_servers: MCP server instances to attach to all agents
  37. send_message_tool_class: Fallback SendMessage tool class when a communication flow does not define its own
  38. load_threads_callback: Callable used to load persisted conversation threads
  39. save_threads_callback: Callable used to save conversation threads
  40. user_context: Initial shared context accessible to all agents
  41. """
  42. ```
  43. > **Note:** `CommunicationFlowEntry` is a type alias defined in `agency_swarm.agency.core`
  44. > that accepts `(Agent, Agent)` tuples, `AgentFlow` chains, or those accompanied by a
  45. > custom SendMessage tool class.
  46. > **Advanced Note:** `Handoff` from `agency_swarm` is the Agency Swarm communication-flow class.
  47. > `SDKHandoff` exposes the raw OpenAI Agents SDK handoff type for advanced interoperability.
  48. ### Key Attributes
  49. - **`agents`** (dict[str, Agent]): Dictionary mapping agent names to their instances
  50. - **`entry_points`** (list[Agent]): Agents designated as entry points for external interaction
  51. - **`thread_manager`** (ThreadManager): Manager responsible for handling conversation threads
  52. - **`event_stream_merger`** (EventStreamMerger): Aggregates streaming events from concurrent agent runs
  53. - **`persistence_hooks`** (PersistenceHooks | None): Optional hooks for loading/saving thread state
  54. - **`shared_instructions`** (str | None): Instructions prepended to every agent's system prompt
  55. - **`shared_tools`** (list[Tool] | None): Tool instances or BaseTool classes shared with all agents
  56. - **`shared_tools_folder`** (str | None): Path to folder containing shared tool files
  57. - **`shared_files_folder`** (str | None): Path to folder of files shared via a common vector store
  58. - **`shared_mcp_servers`** (list[Any] | None): MCP server instances attached to all agents
  59. - **`user_context`** (dict[str, Any]): Shared user-defined context accessible within MasterContext
  60. - **`send_message_tool_class`** (type | None): Fallback SendMessage tool when no flow-specific tool is set
  61. ### Key Methods
  62. <CodeGroup>
  63. ```python get_response
  64. async def get_response(
  65. self,
  66. message: str | list[TResponseInputItem],
  67. recipient_agent: str | Agent | None = None,
  68. context_override: dict[str, Any] | None = None,
  69. hooks_override: RunHooks | None = None,
  70. run_config: RunConfig | None = None,
  71. file_ids: list[str] | None = None,
  72. additional_instructions: str | None = None,
  73. agency_context_override: AgencyContext | None = None,
  74. **kwargs: Any,
  75. ) -> RunResult:
  76. """
  77. Initiate an interaction with a specified agent within the agency.
  78. Parameters:
  79. message: The input message for the agent
  80. recipient_agent: Target agent instance or name (defaults to first entry point)
  81. context_override: Additional context to pass to the agent run
  82. hooks_override: Specific hooks to use for this run, overriding agency defaults
  83. run_config: Configuration for the agent run
  84. file_ids: Additional file IDs for the agent run
  85. additional_instructions: Additional instructions for this run only
  86. agency_context_override: Run-scoped agency context override (for example, isolated thread history)
  87. **kwargs: Additional arguments passed to the target agent's get_response
  88. Returns:
  89. RunResult: The result of the agent execution chain
  90. """
  91. ```
  92. ```python get_response_sync
  93. def get_response_sync(
  94. self,
  95. message: str | list[TResponseInputItem],
  96. recipient_agent: str | Agent | None = None,
  97. context_override: dict[str, Any] | None = None,
  98. hooks_override: RunHooks | None = None,
  99. run_config: RunConfig | None = None,
  100. file_ids: list[str] | None = None,
  101. additional_instructions: str | None = None,
  102. agency_context_override: AgencyContext | None = None,
  103. **kwargs: Any,
  104. ) -> RunResult:
  105. """
  106. Initiate an interaction with a specified agent within the agency.
  107. Parameters:
  108. message: The input message for the agent
  109. recipient_agent: Target agent instance or name (defaults to first entry point)
  110. context_override: Additional context to pass to the agent run
  111. hooks_override: Specific hooks to use for this run, overriding agency defaults
  112. run_config: Configuration for the agent run
  113. file_ids: Additional file IDs for the agent run
  114. additional_instructions: Additional instructions for this run only
  115. agency_context_override: Run-scoped agency context override (for example, isolated thread history)
  116. **kwargs: Additional arguments passed to the target agent's get_response
  117. Returns:
  118. RunResult: The result of the agent execution chain
  119. """
  120. ```
  121. ```python get_response_stream
  122. def get_response_stream(
  123. self,
  124. message: str | list[TResponseInputItem],
  125. recipient_agent: str | Agent | None = None,
  126. context_override: dict[str, Any] | None = None,
  127. hooks_override: RunHooks | None = None,
  128. run_config_override: RunConfig | None = None,
  129. file_ids: list[str] | None = None,
  130. additional_instructions: str | None = None,
  131. agency_context_override: AgencyContext | None = None,
  132. **kwargs: Any,
  133. ) -> StreamingRunResponse:
  134. """
  135. Initiate a streaming interaction with a specified agent within the agency.
  136. Parameters:
  137. message: The input message for the agent
  138. recipient_agent: Target agent instance or name (defaults to first entry point)
  139. context_override: Additional context for the run
  140. hooks_override: Specific hooks for this run
  141. run_config_override: Specific run configuration for this run
  142. file_ids: Additional file IDs for the agent run
  143. additional_instructions: Additional instructions for this run only
  144. agency_context_override: Run-scoped agency context override (for example, isolated thread history)
  145. **kwargs: Additional arguments passed to get_response_stream
  146. Returns:
  147. StreamingRunResponse: Wrapper over the streaming agent execution, yielding events
  148. """
  149. ```
  150. ```python run_fastapi
  151. def run_fastapi(
  152. self,
  153. host: str = "0.0.0.0",
  154. port: int = 8000,
  155. app_token_env: str = "APP_TOKEN",
  156. cors_origins: list[str] | None = None,
  157. enable_agui: bool = False,
  158. ):
  159. """
  160. Serve this agency via the FastAPI integration.
  161. Parameters:
  162. host: Host address to bind the server
  163. port: Port number to bind the server
  164. app_token_env: Environment variable name for authentication token
  165. cors_origins: List of allowed CORS origins
  166. enable_agui: Enable Agency UI interface
  167. """
  168. ```
  169. ```python get_agency_graph
  170. def get_agency_graph(
  171. self,
  172. include_tools: bool = True,
  173. ) -> dict[str, Any]:
  174. """
  175. Returns a ReactFlow-compatible JSON graph representing the agency's organization.
  176. Parameters:
  177. include_tools: Whether to include agent tools as separate nodes
  178. Returns:
  179. dict: ReactFlow-compatible structure with nodes and edges
  180. """
  181. ```
  182. ```python get_metadata
  183. def get_metadata(
  184. self,
  185. include_tools: bool = True,
  186. ) -> dict[str, Any]:
  187. """
  188. Returns combined graph data and summary metadata for the agency.
  189. Parameters:
  190. include_tools: Whether to include agent tools as separate nodes
  191. Returns:
  192. dict: Graph data plus metadata fields like agencyName, totalAgents, totalTools, agents, entryPoints.
  193. Tool entries include inputSchema when available.
  194. """
  195. ```
  196. ```python visualize
  197. def visualize(
  198. self,
  199. output_file: str = "agency_visualization.html",
  200. include_tools: bool = True,
  201. open_browser: bool = True,
  202. ) -> str:
  203. """
  204. Create an HTML visualization of the agency structure.
  205. Parameters:
  206. output_file: Path to save the HTML file
  207. include_tools: Whether to include agent tools in visualization
  208. open_browser: Whether to automatically open in browser
  209. Returns:
  210. str: Path to the generated HTML file
  211. """
  212. ```
  213. ```python tui
  214. def tui(self, show_reasoning: bool | None = None, reload: bool = True) -> None:
  215. """
  216. Run the terminal UI for the agency (set reload=False to disable hot reload on file changes).
  217. """
  218. ```
  219. ```python copilot_demo
  220. def copilot_demo(
  221. self,
  222. host: str = "0.0.0.0",
  223. port: int = 8000,
  224. frontend_port: int = 3000,
  225. cors_origins: list[str] | None = None,
  226. ) -> None:
  227. """
  228. Run the bundled copilot demo for the agency.
  229. """
  230. ```
  231. For provisioning and current terminal limitations, see [Agent Swarm TUI](/core-framework/agencies/agent-swarm-cli).
  232. </CodeGroup>
  233. ## Agent Class
  234. The Agent class extends the base `agents.Agent` with capabilities for multi-agent collaboration within an Agency.
  235. ```python
  236. from agency_swarm import Agent, ModelSettings
  237. class Agent(BaseAgent[MasterContext]):
  238. def __init__(self, **kwargs: Any):
  239. """
  240. Initialize an Agency Swarm Agent.
  241. Parameters:
  242. name (str): Agent name (**required**)
  243. instructions (str | Path | None): System prompt text or path
  244. description (str | None): Optional role description for send_message tools
  245. files_folder (str | Path | None): Folder for local file management and vector stores
  246. tools_folder (str | Path | None): Directory for automatic tool discovery
  247. schemas_folder (str | Path | None): Directory containing OpenAPI schemas for tool generation
  248. api_headers (dict[str, dict[str, str]] | None): Per-schema HTTP headers for generated tools
  249. api_params (dict[str, dict[str, Any]] | None): Per-schema default parameters for generated tools
  250. include_search_results (bool): Include search results in FileSearchTool output (default False)
  251. include_web_search_sources (bool): Include source URLs for WebSearchTool output (default True)
  252. validation_attempts (int): Number of retries when output guardrails trigger (default 1)
  253. raise_input_guardrail_error (bool): Controls input guardrail behavior—False enables non-strict mode (guidance as assistant message), True enables strict mode (raises exceptions). Default: False
  254. handoff_reminder (str | None): Custom reminder text when handing off to another agent
  255. model (str | Model | None): Model identifier; defaults to agents SDK configuration
  256. model_settings (ModelSettings | None): Model configuration overrides
  257. tools (list[Tool] | None): Explicit tool instances to register
  258. mcp_servers (list[MCPServer] | None): Model Context Protocol servers to attach
  259. mcp_config (MCPConfig | None): Configuration for MCP servers
  260. input_guardrails (list[InputGuardrail] | None): Pre-execution validation hooks
  261. output_guardrails (list[OutputGuardrail] | None): Post-execution validation hooks
  262. output_type (type[Any] | AgentOutputSchemaBase | None): Type of final output structure
  263. hooks (AgentHooks | None): Lifecycle callbacks from the agents SDK
  264. tool_use_behavior ("run_llm_again" | "stop_on_first_tool" | StopAtTools | dict[str, Any] | Callable):
  265. Tool execution policy passed through to the agents SDK
  266. reset_tool_choice (bool | None): Whether to reset tool choice after tool calls
  267. """
  268. ```
  269. ### Key Attributes
  270. - **`files_folder`** (str | Path | None): Local folder for file management and vector stores
  271. - **`tools_folder`** (str | Path | None): Directory for automatic tool discovery and loading
  272. - **`schemas_folder`** (str | Path | None): Folder scanned for OpenAPI schemas to auto-generate tools
  273. - **`api_headers` / `api_params`** (dict): Per-schema metadata applied when generating tools
  274. - **`description`** (str | None): Agent role description for dynamic send_message tools
  275. - **`include_search_results`** (bool): Whether FileSearchTool responses include citation context
  276. - **`include_web_search_sources`** (bool): Whether WebSearchTool responses include source URLs
  277. - **`validation_attempts`** (int): Retry count for output guardrail enforcement
  278. - **`raise_input_guardrail_error`** (bool): Controls input guardrail mode—False for non-strict (guidance as assistant), True for strict (raises exceptions).
  279. - **`handoff_reminder`** (str | None): Custom reminder appended to handoff prompts
  280. - **`tool_concurrency_manager`** (ToolConcurrencyManager): Coordinates concurrent tool execution
  281. ### Core Execution Methods
  282. <CodeGroup>
  283. ```python get_response
  284. async def get_response(
  285. self,
  286. message: str | list[TResponseInputItem],
  287. sender_name: str | None = None,
  288. context_override: dict[str, Any] | None = None,
  289. hooks_override: RunHooks | None = None,
  290. run_config_override: RunConfig | None = None,
  291. file_ids: list[str] | None = None,
  292. additional_instructions: str | None = None,
  293. agency_context: AgencyContext | None = None,
  294. **kwargs: Any,
  295. ) -> RunResult:
  296. """
  297. Run the agent's turn in the conversation loop.
  298. Parameters:
  299. message: Input message as string or structured input items list
  300. sender_name: Name of sending agent (None for user interactions)
  301. context_override: Optional context data to override default MasterContext values
  302. hooks_override: Optional hooks to override default agent hooks
  303. run_config_override: Optional run configuration settings
  304. file_ids: List of OpenAI file IDs to attach to the message
  305. additional_instructions: Additional instructions for this run only
  306. agency_context: Injected AgencyContext (auto-created when running standalone)
  307. **kwargs: Additional keyword arguments forwarded to the agents SDK (e.g., max_turns)
  308. Returns:
  309. RunResult: The complete execution result from the agents SDK
  310. """
  311. ```
  312. ```python get_response_stream
  313. def get_response_stream(
  314. self,
  315. message: str | list[TResponseInputItem],
  316. sender_name: str | None = None,
  317. context_override: dict[str, Any] | None = None,
  318. hooks_override: RunHooks | None = None,
  319. run_config_override: RunConfig | None = None,
  320. file_ids: list[str] | None = None,
  321. additional_instructions: str | None = None,
  322. agency_context: AgencyContext | None = None,
  323. **kwargs: Any,
  324. ) -> StreamingRunResponse:
  325. """
  326. Run the agent's turn in streaming mode.
  327. Parameters:
  328. message: Input message or list of message items
  329. sender_name: Name of sending agent (None for user interactions)
  330. context_override: Optional context data to override default values
  331. hooks_override: Optional hooks to override default agent hooks
  332. run_config_override: Optional run configuration
  333. file_ids: List of OpenAI file IDs to attach to the message
  334. additional_instructions: Additional instructions for this run only
  335. agency_context: Injected AgencyContext (auto-created when running standalone)
  336. **kwargs: Additional keyword arguments forwarded to the agents SDK
  337. Returns:
  338. StreamingRunResponse: Async iterable over streamed events with access to the final result
  339. """
  340. ```
  341. </CodeGroup>
  342. ### Tool Management
  343. <CodeGroup>
  344. ```python add_tool
  345. def add_tool(self, tool: Tool) -> None:
  346. """
  347. Add a Tool instance to the agent's list of tools.
  348. Parameters:
  349. tool: The agents.Tool instance to add
  350. Raises:
  351. TypeError: If tool is not an instance of agents.Tool
  352. """
  353. ```
  354. ```python register_subagent
  355. def register_subagent(
  356. self,
  357. recipient_agent: "Agent",
  358. send_message_tool_class: type | None = None,
  359. runtime_state: AgentRuntimeState | None = None,
  360. ) -> None:
  361. """
  362. Register another agent as a subagent for communication.
  363. Creates a dynamic `send_message_to_<RecipientName>` tool for inter-agent communication.
  364. Parameters:
  365. recipient_agent: The Agent instance to register as a recipient
  366. send_message_tool_class: Optional custom SendMessage override for this pair
  367. runtime_state: Optional runtime state container injected by the owning Agency
  368. Raises:
  369. TypeError: If recipient_agent is not a valid Agent instance
  370. ValueError: If attempting to register the agent itself as a subagent
  371. """
  372. ```
  373. </CodeGroup>
  374. ### File Management
  375. <CodeGroup>
  376. ```python upload_file
  377. def upload_file(self, file_path: str, include_in_vector_store: bool = True) -> str:
  378. """
  379. Upload a file using the agent's file manager.
  380. Parameters:
  381. file_path: Path to the file to upload
  382. include_in_vector_store: Whether to add file to vector store
  383. Returns:
  384. str: File ID of the uploaded file
  385. Raises:
  386. RuntimeError: If the agent has no file manager configured
  387. """
  388. ```
  389. </CodeGroup>