Swarm
Swarm orchestration API for coordinating multi-agent systems.
#Swarm
Swarm coordinates a roster of Agent instances and exposes the same builders as an agent for local tools, events, batches, scheduling and follow-ups.
#Construction
from maivn import Agent, Swarm
researcher = Agent(name='researcher', api_key='your-api-key')
writer = Agent(name='writer', api_key='your-api-key', use_as_final_output=True)
swarm = Swarm(
name='research-team',
agents=[researcher, writer],
description='Researches and writes a final brief.',
system_prompt='Coordinate the specialists.',
)name is required. The roster defaults to empty. A swarm accepts an optional shared Client, model directive (model, default 'auto'), before_execute and after_execute hooks with hook_execution_mode, system_tools_config, max_cycles (keyword-only), the allow_private_in_system_tools flag, local tools, skills, resources, tags, skill_sets and attached_skill_ids. A swarm has no MCP server registration. Register MCP servers on the member agents instead.
The roster defines the available members; an invocation does not necessarily run every member. For resource-backed tasks, routing can narrow it to the smallest authorized relevant subset before planning. Member descriptions, the request, and resources visible in each member's authenticated scope guide selection. Describe each member's specialty clearly and name the documents or comparison you need in the request. Ambiguous resource references may require clarification. Selection cannot grant access to additional members or resources.
A member's system_tools_config travels with its inline definition. For example, Agent(..., system_tools_config={'allowed_tools': []}) disables configurable system tools for that member, including fire_trigger. Tools enabled through separate features, such as human follow-up and skill retrieval, retain their own controls. An omitted member policy inherits the swarm invocation policy. When both policies are explicit, their tool allowlists and compose-target approvals are intersected, so a member cannot re-enable a tool denied by its parent. Member function tools are configured separately.
It also accepts api_key, env_file, and api_key_file. Without an explicit client or credential source, it inherits the first member's client. An empty swarm resolves environment credentials when first used. See Authentication. Trigger builders inherit its agent_id (defaulting to name) and version (default 1).
#Invocation
def invoke(
messages: SdkMessagesInput,
*,
force_final_tool: bool = False,
thread_id: str | None = None,
verbose: bool = False,
reasoning: Literal['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None = None,
routing_preference: Literal['speed', 'cost', 'quality'] | None = None,
memory_config: MemoryConfig | Mapping[str, object] | None = None,
allow_private_in_system_tools: bool | None = None,
model: RuntimeModelChoice | None = None,
system_tools_config: SystemToolsConfig | Mapping[str, object] | None = None,
max_cycles: int | None = None,
stream_response: bool = False,
options: RunOptions | None = None,
origin: str | None = None,
) -> InvokeResponse:
...Per-call allow_private_in_system_tools wins over the swarm's value and over system_tools_config.allow_private_data for that call. None keeps the swarm's value.
max_cycles caps the run's model-loop cycles, from 1 to 1000. It is available on the Swarm constructor (keyword-only), on RunOptions, and on invoke, ainvoke, stream, astream and the time-travel streams. A per-call value beats RunOptions.max_cycles, which beats the swarm's value. The platform never runs more than 20 cycles, so it uses the smaller of your value and 20. The cap is exact: a run that reaches it without finishing raises MaivnSDKError with error_code='max_iterations_exceeded', and verbose=True prints a Cycle n/m line for each cycle. It is not RunConfig.recursion_limit, which limits delegation depth. max_cycles requires a platform release that supports it. Against an older platform, setting it makes the request fail with a validation error, and leaving it unset works everywhere. To bound how long a run takes, use a hosted job and its max_duration_seconds.
ainvoke has the same keyword surface. stream and astream yield StreamEvent. Unlike Agent.invoke, swarm invocation does not expose targeted_tools or direct structured_output parameters. batch(inputs, *, max_concurrency=None, return_exceptions=False, **invoke_kwargs) and abatch run several inputs and return list[InvokeResponse | BaseException] in input order. Both default to min(32, os.cpu_count() + 4) concurrent calls, capped at the number of inputs, and return_exceptions=True puts a failing input's exception in its place.
With force_final_tool=True, invoke raises ValueError before sending anything when more than one member has use_as_final_output=True. When the final tool's Pydantic model is known, response.result is a validated instance of it. See Structured Output.
preview_redaction(prompt, **options) and apreview_redaction preview the shielded copy this swarm would send, with its system_prompt prepended as invoke does. See Preview redaction.
response = swarm.invoke('Prepare the launch brief.', thread_id='thread-42')
print(response.response)#Thread handles
swarm.thread(thread_id=None, *, options=None) returns a local conversation handle. send / asend and stream / astream use the normal swarm execution path, preserving its roster and its hooks. Tools and full message lists carry over too. The handle fixes the ID across calls. Ordinary invoke(..., thread_id=...) remains available.
conversation = swarm.thread()
response = conversation.send('Prepare the launch brief.')
response = conversation.send('Revise it for the sales team.')Use state / astate for state and events / aevents for current-turn replay. See Sessions and Streaming for replay cursors and cleanup.
The swarm also exposes the lower-level thread methods that Agent has: start_thread, post_thread_message, get_thread, thread_events, time_travel_thread, time_travel_thread_stream and submit_approval, each with an a-prefixed async twin. The handle also has time_travel(checkpoint_id, message, ...), which waits for the new path and returns an InvokeResponse; see the Agent reference.
#Roster and dependencies
add_agent(agent) and list_agents() manage the roster. There is no public get_agent method; look up members in the returned list. The swarm.member builder registers an agent and can attach dependency metadata; see Multi-Agent. Prefer swarm.member.depends_on_agent(...) for one member waiting on another. A tool-level @depends_on_agent also works when both agents are in the swarm, and it runs the specialist once. A member invoked through a dependency receives the user's request along with the injected output.
An agent with use_as_final_output=True can supply the swarm's final result. included_nested_synthesis on agents controls whether nested responses participate in synthesis.
#Follow-ups, events, and tools
allow_followup_questions(...) behaves like the agent builder: it handles typed runtime questions inline and preserves invoke, ainvoke, stream, and astream.
events(...), batch(...), abatch(...), toolify(...), add_tool(...), add_toolset(...), list_tools(), compile_tools() and validate_tool_configuration() are available on the swarm. So are the skill methods add_skill, add_skill_set, attach_skill and use_skills. verbose=True uses the same plain or Rich terminal tier selection described in the Agent reference. The plain tier prefixes each member's streamed lines with the member's name, such as [researcher] ..., and prints the final answer once.
When task_list is in the swarm's SystemToolsConfig(allowed_tools=[...]), the swarm publishes its plan as task_list_updated events: one item per member it runs, {id, title, status} with the member's name as title and status moving from pending to in_progress to completed. See Task-list events for reading them from on_event and from normalized AppEvents; the two shapes differ.
swarm.decide(name, *, client, questions, at='before', require=None, max_concurrency=4, native_batch=False) returns a decision builder that wraps the swarm's invocation. See the Decisions API.
#Scheduling and cleanup
Use cron(...), interval(...) or at(...) to bind a scheduled swarm invocation. The on_* builders (such as on_webhook and on_email) bind trigger-driven invocations. close() takes no arguments and is safe to call twice. It releases the connection pools of a client the swarm created itself. It never closes a Client that you passed in, and it does not close member agents: call close() on each member agent yourself to stop its MCP servers.
See Agent, Multi-Agent, and Interrupts.
Live Available Models
Active, tool-capable model IDs accepted by ModelConfig.
Loading models
The current table controls remain available while records load.