guide.mdx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. ---
  2. title: "Migration Guide: v0.x to v1.x"
  3. description: "Guide for migrating from Agency Swarm v0.x to v1.x (OpenAI Agents SDK based)"
  4. icon: "book"
  5. ---
  6. Agency Swarm v1.x is a complete rewrite built on the OpenAI Agents SDK, bringing significant improvements and new capabilities.
  7. ## Installation
  8. <Tabs defaultValue="v1.x (New)">
  9. <Tab title="v0.x (Previous)">
  10. ```bash
  11. pip install "agency-swarm<1.0.0"
  12. ```
  13. <Note>
  14. v0.x documentation remains available at the current site until v1.0 reaches general availability.
  15. </Note>
  16. </Tab>
  17. <Tab title="v1.x (New)">
  18. ```bash
  19. pip install agency-swarm
  20. ```
  21. <Info>
  22. If you encounter issues, please create a GitHub issue with the **v1.x** label.
  23. </Info>
  24. </Tab>
  25. </Tabs>
  26. ## What's New in v1.x
  27. <CardGroup cols={2}>
  28. <Card title="Latest AI Models" icon="robot">
  29. Full support for reasoning models
  30. Web Search and Computer Use capabilities
  31. </Card>
  32. <Card title="Better Performance" icon="bolt">
  33. Async-first architecture with direct conversation control
  34. </Card>
  35. <Card title="Enhanced Tools" icon="wrench">
  36. Simple `@function_tool` decorator replaces complex BaseTool classes
  37. </Card>
  38. <Card title="Direct Control" icon="gear">
  39. No more black-box Assistants API - full control over threads and runs
  40. </Card>
  41. </CardGroup>
  42. <Accordion title="📋 Complete Feature Comparison">
  43. ### New Capabilities
  44. - **Web Search & Computer Use**: Native OpenAI Responses API integration
  45. - **Latest Models**: Full support for o3, o4-mini, and future OpenAI models via Responses API
  46. - **Third-Party Models**: Use any Chat Completions API-compatible provider
  47. - **Direct Thread Control**: No more black-box Assistants API limitations
  48. - **Full Conversation Persistence**: Complete history management (not just thread IDs)
  49. - **Enhanced Validation**: `output_guardrails` and `input_guardrails` system
  50. ### Architectural Improvements
  51. - **Orchestrator Pattern on New Foundation**: Agency Swarm's proven orchestrator-workers pattern now runs on the OpenAI Agents SDK foundation
  52. - **Async-first**: Native async execution for better performance
  53. - **Enhanced Communication**: Defined `communication_flows` for coordinated multi-agent execution
  54. - **Better State Management**: Complete conversation history persistence
  55. ### Enhanced Developer Experience
  56. - **Structured Outputs**: Native Pydantic model support for agent outputs via `output_type`
  57. - **Modern Tool System**: `@function_tool` decorator replaces `BaseTool` classes for cleaner tool definitions
  58. - **Better Validation**: `output_guardrails` and `input_guardrails` replace the old `response_validator` system
  59. - **Real-time Streaming**: Improved streaming capabilities with async response handling
  60. </Accordion>
  61. <Accordion title="🏗️ Understanding the Migration">
  62. The migration from v0.x to v1.x represents a fundamental shift in how Agency Swarm operates:
  63. ### Execution Core
  64. - **v0.x**: Used OpenAI Assistants API runs directly
  65. - **v1.x**: Uses `agents.Runner` from OpenAI Agents SDK for more control
  66. ### State Management
  67. - **v0.x**: Relied on Assistant/Thread objects managed by OpenAI
  68. - **v1.x**: Uses `ThreadManager` and `MessageStore` managed via `RunHooks` and shared `MasterContext`
  69. ### Agent Definition
  70. - **v0.x**: Custom `Agent` class with Assistants API integration
  71. - **v1.x**: `agency_swarm.Agent` extends `agents.Agent`, incorporating tools, subagent registration, and file handling
  72. ### Conversation History Persistence
  73. This is an important architectural difference between versions:
  74. - **v0.x (Assistants API)**: Required thread callbacks for production to persist OpenAI Assistant/Thread IDs. OpenAI managed conversation history server-side.
  75. - **v1.x (Agents SDK)**: Required thread callbacks for production to persist complete conversation histories locally. You manage the full conversation state.
  76. **Key Changes:**
  77. - **Callback Structure**: `threads_callbacks` dict → separate `load_threads_callback` and `save_threads_callback` parameters
  78. - **Data Format**: Thread IDs only → Complete conversation histories
  79. - **Callback Signatures**: Unchanged (both use no-parameter callbacks with closure)
  80. </Accordion>
  81. ## Step-by-Step Migration
  82. <Accordion title="🔧 Agency & Agent Updates" defaultOpen>
  83. ### Agency Constructor
  84. <CodeGroup>
  85. ```python v0.x
  86. def load_threads(chat_id):
  87. return load_threads_from_db(chat_id) # Returns thread IDs
  88. def save_threads(new_threads):
  89. save_threads_to_db(new_threads) # Saves thread IDs
  90. agency = Agency(
  91. agency_chart=[agent1, [agent1, agent2]], # Will show warning
  92. threads_callbacks={
  93. 'load': lambda: load_threads(chat_id),
  94. 'save': lambda new_threads: save_threads(new_threads)
  95. }
  96. )
  97. ```
  98. ```python v1.x
  99. def load_threads(chat_id):
  100. # Load the complete conversation history instead of just thread IDs
  101. return load_conversation_history(chat_id)
  102. def save_threads(thread_dict):
  103. # Persist the full conversation histories
  104. save_conversation_history(thread_dict)
  105. agency = Agency(
  106. entry_point_agent, # Positional argument
  107. communication_flows=[(agent1, agent2)],
  108. load_threads_callback=lambda: load_threads(chat_id),
  109. save_threads_callback=lambda new_threads: save_threads(new_threads)
  110. )
  111. ```
  112. </CodeGroup>
  113. <Warning>
  114. **Data Format Change:** Your callbacks now need to store complete conversation histories instead of just thread IDs. Refer to [examples/custom_persistence.py](https://github.com/VRSEN/agency-swarm/blob/main/examples/custom_persistence.py) to see the example implementation.
  115. </Warning>
  116. ### Agent Configuration
  117. <CodeGroup>
  118. ```python v0.x
  119. agent = Agent(
  120. name="MyAgent",
  121. temperature=0.7,
  122. max_completion_tokens=1000,
  123. response_validator=my_validator
  124. )
  125. ```
  126. ```python v1.x
  127. agent = Agent(
  128. name="MyAgent",
  129. model="gpt-4.1",
  130. model_settings=ModelSettings(
  131. temperature=0.7,
  132. max_tokens=1000,
  133. ),
  134. output_guardrails=[my_guardrail]
  135. )
  136. ```
  137. </CodeGroup>
  138. </Accordion>
  139. <Accordion title="🛠️ Tool Migration" defaultOpen>
  140. ### Simple Tool Conversion
  141. <Note>
  142. This step is optional. Agency Swarm will keep maintaining the BaseTool approach for tool definition as well.
  143. </Note>
  144. <CodeGroup>
  145. ```python v0.x
  146. class ProcessData(BaseTool):
  147. """Processes input data."""
  148. input_data: str = Field(..., description="Data to process")
  149. def run(self):
  150. return f"Processed: {self.input_data}"
  151. ```
  152. ```python v1.x
  153. @function_tool
  154. def process_data(input_data: str) -> str:
  155. """Processes input data."""
  156. return f"Processed: {input_data}"
  157. ```
  158. </CodeGroup>
  159. ### Tool with Context Access
  160. <CodeGroup>
  161. ```python v0.x
  162. class AdvancedTool(BaseTool):
  163. data: str = Field(..., description="Input data")
  164. def run(self):
  165. # Access shared state
  166. shared_data = self._shared_state.get("key", "default")
  167. return f"Result: {self.data} + {shared_data}"
  168. ```
  169. ```python v1.x
  170. @function_tool
  171. async def advanced_tool(ctx: RunContextWrapper[Any], data: str) -> str:
  172. """Advanced tool with context access."""
  173. # Access shared state and other context
  174. shared_data = ctx.context.get("key", "default")
  175. return f"Result: {data} + {shared_data}"
  176. ```
  177. </CodeGroup>
  178. </Accordion>
  179. <Accordion title="🔒 Validation & Outputs" defaultOpen>
  180. ### Response Validation
  181. <CodeGroup>
  182. ```python v0.x
  183. class TestAgent(Agent):
  184. def __init__(self):
  185. super().__init__(
  186. name="TestAgent",
  187. description="..."
  188. )
  189. @override
  190. def response_validator(self, message):
  191. # User-defined validation function
  192. if self.check_errors(message):
  193. raise ValueError("Error processing message")
  194. # Returns original message if no errors are raised
  195. return message
  196. ```
  197. ```python v1.x
  198. @output_guardrail
  199. async def validate_response(
  200. ctx: RunContextWrapper, agent: Agent, agent_response: str
  201. ) -> GuardrailFunctionOutput:
  202. # User-defined validation logic
  203. error_msg, tripwire_triggered = check_errors(agent_response)
  204. return GuardrailFunctionOutput(
  205. output_info=error_msg,
  206. tripwire_triggered=tripwire_triggered,
  207. )
  208. agent = Agent(output_guardrails=[validate_response])
  209. ```
  210. </CodeGroup>
  211. ### Structured Outputs
  212. <CodeGroup>
  213. ```python v0.x
  214. result = agency.get_completion(
  215. "Analyze this data",
  216. response_format={"type": "json_schema", "json_schema": {...}}
  217. )
  218. ```
  219. ```python v1.x
  220. class AnalysisResult(BaseModel):
  221. status: str
  222. findings: str
  223. agent = Agent(output_type=AnalysisResult)
  224. result = await agency.get_response("Analyze this data")
  225. # result.final_output is now a typed AnalysisResult object
  226. ```
  227. </CodeGroup>
  228. </Accordion>
  229. <Accordion title="🔄 Interaction Updates" defaultOpen>
  230. ### Getting Agency Response
  231. <CodeGroup>
  232. ```python v0.x
  233. # Removed in v1.x
  234. result = agency.get_completion("Hello")
  235. stream = agency.get_completion_stream("Hello")
  236. ```
  237. ```python v1.x
  238. # Async (recommended)
  239. import asyncio
  240. async def main():
  241. result = await agency.get_response("Hello")
  242. print(result.final_output)
  243. # Streaming (async only)
  244. async def stream_example():
  245. async for chunk in agency.get_response_stream("Hello"):
  246. print(chunk)
  247. asyncio.run(main())
  248. ```
  249. </CodeGroup>
  250. </Accordion>
  251. ## Complete Migration Example
  252. <Tabs defaultValue="After (v1.x)">
  253. <Tab title="Before (v0.x)">
  254. ```python
  255. from agency_swarm import Agency, Agent, BaseTool
  256. from pydantic import Field
  257. class DataProcessor(BaseTool):
  258. """Processes data."""
  259. data: str = Field(..., description="Input data")
  260. def run(self):
  261. return f"Processed: {self.data}"
  262. class Analyst(Agent):
  263. def __init__(self):
  264. super().__init__(
  265. name="Analyst",
  266. description="Analyzes data",
  267. tools=[DataProcessor],
  268. temperature=0.7
  269. )
  270. def response_validator(self, message):
  271. if "error" in message.lower():
  272. raise ValueError("Invalid response")
  273. return message
  274. agency = Agency(
  275. agency_chart=[Analyst()],
  276. shared_instructions="Be helpful and accurate."
  277. )
  278. result = agency.get_completion("Analyze sample data")
  279. ```
  280. </Tab>
  281. <Tab title="After (v1.x)">
  282. ```python
  283. from agency_swarm import (
  284. Agency,
  285. Agent,
  286. function_tool,
  287. ModelSettings,
  288. output_guardrail,
  289. GuardrailFunctionOutput,
  290. )
  291. from pydantic import BaseModel, Field
  292. import asyncio
  293. # Modern tool definition
  294. @function_tool
  295. def data_processor(data: str) -> str:
  296. """Processes data."""
  297. return f"Processed: {data}"
  298. # Structured output
  299. class AnalysisResult(BaseModel):
  300. status: str
  301. findings: str
  302. # Validation guardrail
  303. @output_guardrail
  304. async def validate_analysis(ctx, agent, response):
  305. if "error" in response.lower():
  306. return GuardrailFunctionOutput(
  307. output_info="Invalid response detected",
  308. tripwire_triggered=True
  309. )
  310. return GuardrailFunctionOutput(output_info="Valid response")
  311. # Agent with modern configuration
  312. analyst = Agent(
  313. name="Analyst",
  314. description="Analyzes data",
  315. tools=[data_processor],
  316. output_type=AnalysisResult,
  317. output_guardrails=[validate_analysis],
  318. model="gpt-4.1",
  319. model_settings=ModelSettings(temperature=0.7),
  320. )
  321. agency = Agency(
  322. analyst,
  323. shared_instructions="Be helpful and accurate."
  324. )
  325. # Modern async usage
  326. async def main():
  327. result = await agency.get_response("Analyze sample data")
  328. print(result.final_output) # Typed AnalysisResult object
  329. asyncio.run(main())
  330. ```
  331. </Tab>
  332. </Tabs>
  333. ## Reference Tables
  334. <Accordion title="📚 API changes overview">
  335. ### Agency Methods
  336. | v0.x | Status | v1.x alternative |
  337. |:----:|:------:|:----------------:|
  338. | `get_completion()` | ❌ Removed | `get_response()` (async) |
  339. | `get_completion_stream()` | ❌ Removed | `get_response_stream()` (async) |
  340. | `agency_chart` | ❌ Removed | Positional args + `communication_flows` |
  341. | `model` (global default) | ❌ Removed | Configure each `Agent` via `model` |
  342. | `threads_callbacks` | ❌ Breaking change | `load_threads_callback` + `save_threads_callback` |
  343. ### Agent Parameters
  344. | v0.x | Status | v1.x alternative |
  345. |:----:|:------:|:----------------:|
  346. | `temperature`, `top_p`, etc. | ❌ Removed | `model_settings=ModelSettings(...)` |
  347. | `response_validator` | ❌ Removed | `output_guardrails`, `input_guardrails` |
  348. | `response_format` | ❌ Removed | `output_type` |
  349. | `examples` | ❌ Removed | Include in `instructions` or pass message history to `get_response` / `get_response_stream` |
  350. ### Tools
  351. | v0.x | Status | v1.x alternative |
  352. |:----:|:------:|:----------------:|
  353. | `BaseTool` classes | ✅ Supported | `@function_tool` decorator (recommended) |
  354. | `run()` method | ✅ Simplified | Direct function body implementation |
  355. | `_shared_state` | ❌ Removed | `ctx.context` |
  356. </Accordion>
  357. ## Getting Help
  358. <CardGroup cols={2}>
  359. <Card title="Examples" icon="code" href="https://github.com/VRSEN/agency-swarm/tree/main/examples">
  360. Working v1.x examples with detailed comments
  361. </Card>
  362. <Card title="Issues" icon="bug" href="https://github.com/VRSEN/agency-swarm/issues">
  363. Report v1.x issues with the **v1.x** label
  364. </Card>
  365. <Card title="OpenAI Agents SDK" icon="link" href="https://openai.github.io/openai-agents-python/">
  366. Official OpenAI Agents SDK documentation
  367. </Card>
  368. <Card title="v0.x Docs" icon="book" href="https://agency-swarm.ai">
  369. Current production documentation
  370. </Card>
  371. </CardGroup>