{"id":16973333,"url":"https://github.com/openai/swarm","last_synced_at":"2025-05-12T03:45:38.290Z","repository":{"id":257825193,"uuid":"761974775","full_name":"openai/swarm","owner":"openai","description":"Educational framework exploring ergonomic, lightweight multi-agent orchestration. Managed by OpenAI Solution team.","archived":false,"fork":false,"pushed_at":"2025-03-11T17:27:22.000Z","size":499,"stargazers_count":19741,"open_issues_count":9,"forks_count":2100,"subscribers_count":316,"default_branch":"main","last_synced_at":"2025-05-09T18:53:58.738Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-02-22T20:53:54.000Z","updated_at":"2025-05-09T17:28:08.000Z","dependencies_parsed_at":"2024-10-14T01:02:45.255Z","dependency_job_id":"b7529bec-d2c0-4b67-a101-e40126c66bc0","html_url":"https://github.com/openai/swarm","commit_stats":{"total_commits":25,"total_committers":15,"mean_commits":"1.6666666666666667","dds":0.76,"last_synced_commit":"9db581cecaacea0d46a933d6453c312b034dbf47"},"previous_names":["openai/swarm"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fswarm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fswarm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fswarm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fswarm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openai","download_url":"https://codeload.github.com/openai/swarm/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253309289,"owners_count":21887971,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-14T01:01:11.291Z","updated_at":"2025-05-12T03:45:38.270Z","avatar_url":"https://github.com/openai.png","language":"Python","readme":"![Swarm Logo](assets/logo.png)\n\n# Swarm (experimental, educational)\n\n\u003e [!IMPORTANT]\n\u003e Swarm is now replaced by the [OpenAI Agents SDK](https://github.com/openai/openai-agents-python), which is a production-ready evolution of Swarm. The Agents SDK features key improvements and will be actively maintained by the OpenAI team.\n\u003e\n\u003e We recommend migrating to the Agents SDK for all production use cases.\n\n## Install\n\nRequires Python 3.10+\n\n```shell\npip install git+ssh://git@github.com/openai/swarm.git\n```\n\nor\n\n```shell\npip install git+https://github.com/openai/swarm.git\n```\n\n## Usage\n\n```python\nfrom swarm import Swarm, Agent\n\nclient = Swarm()\n\ndef transfer_to_agent_b():\n    return agent_b\n\n\nagent_a = Agent(\n    name=\"Agent A\",\n    instructions=\"You are a helpful agent.\",\n    functions=[transfer_to_agent_b],\n)\n\nagent_b = Agent(\n    name=\"Agent B\",\n    instructions=\"Only speak in Haikus.\",\n)\n\nresponse = client.run(\n    agent=agent_a,\n    messages=[{\"role\": \"user\", \"content\": \"I want to talk to agent B.\"}],\n)\n\nprint(response.messages[-1][\"content\"])\n```\n\n```\nHope glimmers brightly,\nNew paths converge gracefully,\nWhat can I assist?\n```\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Examples](#examples)\n- [Documentation](#documentation)\n  - [Running Swarm](#running-swarm)\n  - [Agents](#agents)\n  - [Functions](#functions)\n  - [Streaming](#streaming)\n- [Evaluations](#evaluations)\n- [Utils](#utils)\n\n# Overview\n\nSwarm focuses on making agent **coordination** and **execution** lightweight, highly controllable, and easily testable.\n\nIt accomplishes this through two primitive abstractions: `Agent`s and **handoffs**. An `Agent` encompasses `instructions` and `tools`, and can at any point choose to hand off a conversation to another `Agent`.\n\nThese primitives are powerful enough to express rich dynamics between tools and networks of agents, allowing you to build scalable, real-world solutions while avoiding a steep learning curve.\n\n\u003e [!NOTE]\n\u003e Swarm Agents are not related to Assistants in the Assistants API. They are named similarly for convenience, but are otherwise completely unrelated. Swarm is entirely powered by the Chat Completions API and is hence stateless between calls.\n\n## Why Swarm\n\nSwarm explores patterns that are lightweight, scalable, and highly customizable by design. Approaches similar to Swarm are best suited for situations dealing with a large number of independent capabilities and instructions that are difficult to encode into a single prompt.\n\nThe Assistants API is a great option for developers looking for fully-hosted threads and built in memory management and retrieval. However, Swarm is an educational resource for developers curious to learn about multi-agent orchestration. Swarm runs (almost) entirely on the client and, much like the Chat Completions API, does not store state between calls.\n\n# Examples\n\nCheck out `/examples` for inspiration! Learn more about each one in its README.\n\n- [`basic`](examples/basic): Simple examples of fundamentals like setup, function calling, handoffs, and context variables\n- [`triage_agent`](examples/triage_agent): Simple example of setting up a basic triage step to hand off to the right agent\n- [`weather_agent`](examples/weather_agent): Simple example of function calling\n- [`airline`](examples/airline): A multi-agent setup for handling different customer service requests in an airline context.\n- [`support_bot`](examples/support_bot): A customer service bot which includes a user interface agent and a help center agent with several tools\n- [`personal_shopper`](examples/personal_shopper): A personal shopping agent that can help with making sales and refunding orders\n\n# Documentation\n\n![Swarm Diagram](assets/swarm_diagram.png)\n\n## Running Swarm\n\nStart by instantiating a Swarm client (which internally just instantiates an `OpenAI` client).\n\n```python\nfrom swarm import Swarm\n\nclient = Swarm()\n```\n\n### `client.run()`\n\nSwarm's `run()` function is analogous to the `chat.completions.create()` function in the Chat Completions API – it takes `messages` and returns `messages` and saves no state between calls. Importantly, however, it also handles Agent function execution, hand-offs, context variable references, and can take multiple turns before returning to the user.\n\nAt its core, Swarm's `client.run()` implements the following loop:\n\n1. Get a completion from the current Agent\n2. Execute tool calls and append results\n3. Switch Agent if necessary\n4. Update context variables, if necessary\n5. If no new function calls, return\n\n#### Arguments\n\n| Argument              | Type    | Description                                                                                                                                            | Default        |\n| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |\n| **agent**             | `Agent` | The (initial) agent to be called.                                                                                                                      | (required)     |\n| **messages**          | `List`  | A list of message objects, identical to [Chat Completions `messages`](https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages) | (required)     |\n| **context_variables** | `dict`  | A dictionary of additional context variables, available to functions and Agent instructions                                                            | `{}`           |\n| **max_turns**         | `int`   | The maximum number of conversational turns allowed                                                                                                     | `float(\"inf\")` |\n| **model_override**    | `str`   | An optional string to override the model being used by an Agent                                                                                        | `None`         |\n| **execute_tools**     | `bool`  | If `False`, interrupt execution and immediately returns `tool_calls` message when an Agent tries to call a function                                    | `True`         |\n| **stream**            | `bool`  | If `True`, enables streaming responses                                                                                                                 | `False`        |\n| **debug**             | `bool`  | If `True`, enables debug logging                                                                                                                       | `False`        |\n\nOnce `client.run()` is finished (after potentially multiple calls to agents and tools) it will return a `Response` containing all the relevant updated state. Specifically, the new `messages`, the last `Agent` to be called, and the most up-to-date `context_variables`. You can pass these values (plus new user messages) in to your next execution of `client.run()` to continue the interaction where it left off – much like `chat.completions.create()`. (The `run_demo_loop` function implements an example of a full execution loop in `/swarm/repl/repl.py`.)\n\n#### `Response` Fields\n\n| Field                 | Type    | Description                                                                                                                                                                                                                                                                  |\n| --------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **messages**          | `List`  | A list of message objects generated during the conversation. Very similar to [Chat Completions `messages`](https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages), but with a `sender` field indicating which `Agent` the message originated from. |\n| **agent**             | `Agent` | The last agent to handle a message.                                                                                                                                                                                                                                          |\n| **context_variables** | `dict`  | The same as the input variables, plus any changes.                                                                                                                                                                                                                           |\n\n## Agents\n\nAn `Agent` simply encapsulates a set of `instructions` with a set of `functions` (plus some additional settings below), and has the capability to hand off execution to another `Agent`.\n\nWhile it's tempting to personify an `Agent` as \"someone who does X\", it can also be used to represent a very specific workflow or step defined by a set of `instructions` and `functions` (e.g. a set of steps, a complex retrieval, single step of data transformation, etc). This allows `Agent`s to be composed into a network of \"agents\", \"workflows\", and \"tasks\", all represented by the same primitive.\n\n## `Agent` Fields\n\n| Field            | Type                     | Description                                                                   | Default                      |\n| ---------------- | ------------------------ | ----------------------------------------------------------------------------- | ---------------------------- |\n| **name**         | `str`                    | The name of the agent.                                                        | `\"Agent\"`                    |\n| **model**        | `str`                    | The model to be used by the agent.                                            | `\"gpt-4o\"`                   |\n| **instructions** | `str` or `func() -\u003e str` | Instructions for the agent, can be a string or a callable returning a string. | `\"You are a helpful agent.\"` |\n| **functions**    | `List`                   | A list of functions that the agent can call.                                  | `[]`                         |\n| **tool_choice**  | `str`                    | The tool choice for the agent, if any.                                        | `None`                       |\n\n### Instructions\n\n`Agent` `instructions` are directly converted into the `system` prompt of a conversation (as the first message). Only the `instructions` of the active `Agent` will be present at any given time (e.g. if there is an `Agent` handoff, the `system` prompt will change, but the chat history will not.)\n\n```python\nagent = Agent(\n   instructions=\"You are a helpful agent.\"\n)\n```\n\nThe `instructions` can either be a regular `str`, or a function that returns a `str`. The function can optionally receive a `context_variables` parameter, which will be populated by the `context_variables` passed into `client.run()`.\n\n```python\ndef instructions(context_variables):\n   user_name = context_variables[\"user_name\"]\n   return f\"Help the user, {user_name}, do whatever they want.\"\n\nagent = Agent(\n   instructions=instructions\n)\nresponse = client.run(\n   agent=agent,\n   messages=[{\"role\":\"user\", \"content\": \"Hi!\"}],\n   context_variables={\"user_name\":\"John\"}\n)\nprint(response.messages[-1][\"content\"])\n```\n\n```\nHi John, how can I assist you today?\n```\n\n## Functions\n\n- Swarm `Agent`s can call python functions directly.\n- Function should usually return a `str` (values will be attempted to be cast as a `str`).\n- If a function returns an `Agent`, execution will be transferred to that `Agent`.\n- If a function defines a `context_variables` parameter, it will be populated by the `context_variables` passed into `client.run()`.\n\n```python\ndef greet(context_variables, language):\n   user_name = context_variables[\"user_name\"]\n   greeting = \"Hola\" if language.lower() == \"spanish\" else \"Hello\"\n   print(f\"{greeting}, {user_name}!\")\n   return \"Done\"\n\nagent = Agent(\n   functions=[greet]\n)\n\nclient.run(\n   agent=agent,\n   messages=[{\"role\": \"user\", \"content\": \"Usa greet() por favor.\"}],\n   context_variables={\"user_name\": \"John\"}\n)\n```\n\n```\nHola, John!\n```\n\n- If an `Agent` function call has an error (missing function, wrong argument, error) an error response will be appended to the chat so the `Agent` can recover gracefully.\n- If multiple functions are called by the `Agent`, they will be executed in that order.\n\n### Handoffs and Updating Context Variables\n\nAn `Agent` can hand off to another `Agent` by returning it in a `function`.\n\n```python\nsales_agent = Agent(name=\"Sales Agent\")\n\ndef transfer_to_sales():\n   return sales_agent\n\nagent = Agent(functions=[transfer_to_sales])\n\nresponse = client.run(agent, [{\"role\":\"user\", \"content\":\"Transfer me to sales.\"}])\nprint(response.agent.name)\n```\n\n```\nSales Agent\n```\n\nIt can also update the `context_variables` by returning a more complete `Result` object. This can also contain a `value` and an `agent`, in case you want a single function to return a value, update the agent, and update the context variables (or any subset of the three).\n\n```python\nsales_agent = Agent(name=\"Sales Agent\")\n\ndef talk_to_sales():\n   print(\"Hello, World!\")\n   return Result(\n       value=\"Done\",\n       agent=sales_agent,\n       context_variables={\"department\": \"sales\"}\n   )\n\nagent = Agent(functions=[talk_to_sales])\n\nresponse = client.run(\n   agent=agent,\n   messages=[{\"role\": \"user\", \"content\": \"Transfer me to sales\"}],\n   context_variables={\"user_name\": \"John\"}\n)\nprint(response.agent.name)\nprint(response.context_variables)\n```\n\n```\nSales Agent\n{'department': 'sales', 'user_name': 'John'}\n```\n\n\u003e [!NOTE]\n\u003e If an `Agent` calls multiple functions to hand-off to an `Agent`, only the last handoff function will be used.\n\n### Function Schemas\n\nSwarm automatically converts functions into a JSON Schema that is passed into Chat Completions `tools`.\n\n- Docstrings are turned into the function `description`.\n- Parameters without default values are set to `required`.\n- Type hints are mapped to the parameter's `type` (and default to `string`).\n- Per-parameter descriptions are not explicitly supported, but should work similarly if just added in the docstring. (In the future docstring argument parsing may be added.)\n\n```python\ndef greet(name, age: int, location: str = \"New York\"):\n   \"\"\"Greets the user. Make sure to get their name and age before calling.\n\n   Args:\n      name: Name of the user.\n      age: Age of the user.\n      location: Best place on earth.\n   \"\"\"\n   print(f\"Hello {name}, glad you are {age} in {location}!\")\n```\n\n```javascript\n{\n   \"type\": \"function\",\n   \"function\": {\n      \"name\": \"greet\",\n      \"description\": \"Greets the user. Make sure to get their name and age before calling.\\n\\nArgs:\\n   name: Name of the user.\\n   age: Age of the user.\\n   location: Best place on earth.\",\n      \"parameters\": {\n         \"type\": \"object\",\n         \"properties\": {\n            \"name\": {\"type\": \"string\"},\n            \"age\": {\"type\": \"integer\"},\n            \"location\": {\"type\": \"string\"}\n         },\n         \"required\": [\"name\", \"age\"]\n      }\n   }\n}\n```\n\n## Streaming\n\n```python\nstream = client.run(agent, messages, stream=True)\nfor chunk in stream:\n   print(chunk)\n```\n\nUses the same events as [Chat Completions API streaming](https://platform.openai.com/docs/api-reference/streaming). See `process_and_print_streaming_response` in `/swarm/repl/repl.py` as an example.\n\nTwo new event types have been added:\n\n- `{\"delim\":\"start\"}` and `{\"delim\":\"end\"}`, to signal each time an `Agent` handles a single message (response or function call). This helps identify switches between `Agent`s.\n- `{\"response\": Response}` will return a `Response` object at the end of a stream with the aggregated (complete) response, for convenience.\n\n# Evaluations\n\nEvaluations are crucial to any project, and we encourage developers to bring their own eval suites to test the performance of their swarms. For reference, we have some examples for how to eval swarm in the `airline`, `weather_agent` and `triage_agent` quickstart examples. See the READMEs for more details.\n\n# Utils\n\nUse the `run_demo_loop` to test out your swarm! This will run a REPL on your command line. Supports streaming.\n\n```python\nfrom swarm.repl import run_demo_loop\n...\nrun_demo_loop(agent, stream=True)\n```\n\n# Core Contributors\n\n- Ilan Bigio - [ibigio](https://github.com/ibigio)\n- James Hills - [jhills20](https://github.com/jhills20)\n- Shyamal Anadkat - [shyamal-anadkat](https://github.com/shyamal-anadkat)\n- Charu Jaiswal - [charuj](https://github.com/charuj)\n- Colin Jarvis - [colin-openai](https://github.com/colin-openai)\n- Katia Gil Guzman - [katia-openai](https://github.com/katia-openai)\n","funding_links":[],"categories":["🗺️ Field guide (quick picks)","Python","MCP Clients","🤖 AI \u0026 Machine Learning","Frameworks","Table of Open-Source AI Agents Projects","A01_文本生成_文本对话","Repos","Agentic Framework","🤖 AI Agents","Multi-Agent Orchestration","HarmonyOS","Agentic Frameworks","Openai","智能体 Agents","Building","NLP","🛠️ Frameworks \u0026 Platforms","排行榜 [2025-03-18]","LLM Application / RAG","Large Language Models (LLMs)","Agent框架","Orchestration","2. Libraries \u0026 Frameworks","Frameworks \u0026 Libraries","Agent Frameworks","Miscellaneous"],"sub_categories":["Multi-agent coordination","Agent Orchestration Platforms","大语言对话模型及数据","Frameworks \u0026 Libraries","Windows Manager","Frameworks","3. Pretraining","Multi-Agent Orchestration","Autonomous LLM Agents","Agent Framework","Python","AI Agents \u0026 Automation"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2Fswarm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenai%2Fswarm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2Fswarm/lists"}