jianmu.swarm¶
适用对象:多 Agent 应用开发者 / 协作运行时维护者
是否必读:按需
相关模块:jianmu.message, jianmu.tool, jianmu.model, jianmu.mcp
1. 模块职责¶
jianmu.swarm 提供多 Agent 角色、事件、消息封装、运行时、宿主和工具 provider 的公开 API。
如果你需要的不再是单个节点或单条工具调用,而是多个 Agent 之间的协作,这个模块就是主入口。
2. 适合查什么¶
- 配置与领域对象:
AgentProfile、GroupProfile、BudgetSpec - 运行时:
AgentRuntime、DefaultAgentState - 事件与消息:
AgentEvent、MessageEnvelope、InMemoryEventBus - 消息存储:
EnvelopeStoreProtocol、InMemoryMessageStore - 宿主与角色:
AgentHost、SwarmRole、role - provider:
SwarmToolProvider、MCPToolProvider
3. 使用建议¶
- 多 Agent 编排优先从这里的 profile / role / runtime 组合开始
- 普通单 Agent 流程不要过早引入 swarm 抽象
- 更底层的调度细节属于内部 runtime 子模块,不应默认直接依赖
- 如果你要自定义消息持久化或投递语义,优先实现
EnvelopeStoreProtocol,而不是直接耦合 runtime 内部细节
4. 最小示例¶
from jianmu.swarm import AgentProfile, role
@role
def researcher() -> str:
return "Research the question and report back."
profile = AgentProfile(name="researcher")
5. 常见入口¶
- 想定义角色:看
role、SwarmRole - 想配置 Agent / Group:看
AgentProfile、GroupProfile - 想接消息总线:看
InMemoryEventBus - 想替换消息存储:看
EnvelopeStoreProtocol、InMemoryMessageStore - 想启动协作运行时:看
AgentRuntime、AgentHost
6. 注意事项¶
- 单 Agent 流程不必为了后续扩展提前引入 swarm 抽象
- 更底层的调度细节仍属于内部 runtime 子模块,不建议直接依赖
- 角色、事件、runtime 的职责是分层的,建议先按 profile / role / runtime 入口理解
context_builder是统一入口:既可参与 mailbox/history 合并,也会注入到 prompt runtime 供 LLM 上下文装配使用
7. API 参考¶
swarm
¶
Multi-agent collaboration runtime, message routing, roles, and event bus for Jianmu swarms.
BudgetSpec
dataclass
¶
BudgetSpec(
total_tokens: Optional[int] = None,
prompt_tokens: Optional[int] = None,
completion_tokens: Optional[int] = None,
max_tool_calls: Optional[int] = None,
)
Token and call budget limits applied to one agent run.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
total_tokens |
Optional[int]
|
Overall token ceiling for the run. |
prompt_tokens |
Optional[int]
|
Prompt-token ceiling across all model calls. |
completion_tokens |
Optional[int]
|
Completion-token ceiling across all model calls. |
max_tool_calls |
Optional[int]
|
Maximum number of tool invocations allowed. |
AgentProfile
dataclass
¶
AgentProfile(
id: str,
role: str,
parent_id: Optional[str] = None,
task: Optional[str] = None,
budget: Optional[BudgetSpec] = None,
metadata: dict[str, Any] = dict(),
)
Identity and configuration snapshot for one agent in the swarm.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
id |
str
|
Stable agent identifier used by the swarm runtime. |
role |
str
|
Registered role name used to build the agent. |
parent_id |
Optional[str]
|
Optional parent agent ID when this agent was spawned. |
task |
Optional[str]
|
Optional task statement currently assigned to the agent. |
budget |
Optional[BudgetSpec]
|
Optional run budget associated with the agent. |
metadata |
dict[str, Any]
|
Arbitrary application metadata attached to the profile. |
GroupProfile
dataclass
¶
Membership record for a broadcast group channel.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
id |
str
|
Group identifier used for group message routing. |
members |
list[str]
|
Agent IDs currently subscribed to the group. |
metadata |
dict[str, Any]
|
Arbitrary metadata associated with the group. |
AgentEvent
dataclass
¶
AgentEvent(
event_type: str,
agent_id: Optional[str] = None,
payload: dict[str, Any] = dict(),
created_at: Optional[float] = None,
event_id: Optional[str] = None,
)
Runtime event emitted by an agent or the scheduler.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
event_type |
str
|
Event name such as lifecycle, routing, or mailbox actions. |
agent_id |
Optional[str]
|
Optional agent ID associated with the event. |
payload |
dict[str, Any]
|
Structured event-specific data. |
created_at |
Optional[float]
|
Optional event timestamp in Unix seconds. |
event_id |
Optional[str]
|
Optional unique event identifier. |
MessageEnvelope
dataclass
¶
MessageEnvelope(
seq: int,
message: Message,
to_agent_id: str | None = None,
group_id: str | None = None,
topic: str | None = None,
created_at: float = 0.0,
)
Stored message row with monotonic sequence for cursor-based reads.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
seq |
int
|
Monotonic sequence number used for cursor-based consumption. |
message |
Message
|
The stored message payload. |
to_agent_id |
str | None
|
Optional direct-recipient agent ID. |
group_id |
str | None
|
Optional group recipient ID. |
topic |
str | None
|
Optional topic label used for selective delivery. |
created_at |
float
|
Message creation timestamp in Unix seconds. |
AgentRole
¶
Bases: Protocol
Protocol implemented by role factories that build agent trees.
build_tree
¶
Build the root tree for an agent profile.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
profile
|
AgentProfile
|
Agent profile used to configure the role-specific tree. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Any
|
Root node or tree-like object that the runtime can execute. |
源代码位于: jianmu/swarm/base.py
AgentRuntimeProtocol
¶
Bases: Protocol
Public runtime interface for spawning and coordinating swarm agents.
spawn
¶
spawn(
role: str | AgentRole,
task: str | None = None,
parent_id: str | None = None,
mode: str = "detached",
constraints: Any | None = None,
) -> str
Create an agent host and return its runtime identifier.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
role
|
str | AgentRole
|
Registered role name or role factory instance. |
必需 |
task
|
str | None
|
Optional initial task for the spawned agent. |
None
|
parent_id
|
str | None
|
Optional parent agent identifier for nested spawns. |
None
|
mode
|
str
|
Spawn mode understood by the runtime implementation. |
'detached'
|
constraints
|
Any | None
|
Optional runtime-specific execution constraints. |
None
|
返回:
| 类型 | 描述 |
|---|---|
str
|
Runtime agent identifier. |
源代码位于: jianmu/swarm/base.py
kill
¶
kill_async
async
¶
pause
¶
resume
¶
wake
¶
Signal an agent that new work is available.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
reason
|
str | None
|
Optional explanation or trigger reason for wake-up. |
None
|
preempt_agent
async
¶
Interrupt one agent and ask it to yield control.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
reason
|
str | None
|
Optional reason for the preemption. |
None
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
True if the agent yielded successfully, False otherwise. |
源代码位于: jianmu/swarm/base.py
send_message
async
¶
send_message(
*,
sender_id: str | None,
content: str,
to_agent_id: str | None = None,
group_id: str | None = None,
topic: str | None = None,
content_type: str = "text",
metadata: Optional[dict[str, Any]] = None,
) -> int
Send a message into the swarm message store.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
sender_id
|
str | None
|
Originating agent identifier, or |
必需 |
content
|
str
|
Message body. |
必需 |
to_agent_id
|
str | None
|
Optional direct-recipient agent identifier. |
None
|
group_id
|
str | None
|
Optional group recipient. |
None
|
topic
|
str | None
|
Optional topic recipient. |
None
|
content_type
|
str
|
Message content type label. |
'text'
|
metadata
|
Optional[dict[str, Any]]
|
Optional structured metadata persisted with the message. |
None
|
返回:
| 类型 | 描述 |
|---|---|
int
|
Monotonic store sequence number or equivalent delivery token. |
源代码位于: jianmu/swarm/base.py
emit
¶
Publish one runtime event to subscribers.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
event
|
AgentEvent
|
The AgentEvent instance to emit. |
必需 |
subscribe_events
¶
Subscribe to runtime events.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
callback
|
Callable[[AgentEvent], None]
|
Consumer invoked for each emitted |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Callable[[], None]
|
Unsubscribe callback. |
subscribe_observability
¶
subscribe_observability(
callback: Callable[[str, dict[str, Any]], None],
*,
runtime_events: bool = True,
trace_events: bool = False,
) -> Callable[[], None]
Subscribe to runtime and trace observability streams.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
callback
|
Callable[[str, dict[str, Any]], None]
|
Consumer invoked with an event name and structured payload. |
必需 |
runtime_events
|
bool
|
Whether runtime-level events should be forwarded. |
True
|
trace_events
|
bool
|
Whether lower-level trace events should be forwarded. |
False
|
返回:
| 类型 | 描述 |
|---|---|
Callable[[], None]
|
Unsubscribe callback. |
源代码位于: jianmu/swarm/base.py
get_profile
¶
Return the runtime profile for one agent.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Optional[AgentProfile]
|
AgentProfile if found, else None. |
list_agents
¶
save_snapshot
async
¶
Persist a runtime snapshot.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Optional checkpoint thread identifier. |
None
|
step
|
int | None
|
Optional explicit step number for the snapshot. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Serializable snapshot payload. |
源代码位于: jianmu/swarm/base.py
restore_snapshot
async
¶
Restore runtime state from a previously saved snapshot.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Optional checkpoint thread identifier. |
None
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
|
源代码位于: jianmu/swarm/base.py
start_all
¶
stop_all
¶
step_agent
async
¶
Advance a single agent by one step.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
obs
|
Optional[dict[str, Any]]
|
Optional observation payload injected before stepping. |
None
|
返回:
| 类型 | 描述 |
|---|---|
Any
|
Runtime-defined step result. |
源代码位于: jianmu/swarm/base.py
step_agent_with_actions
async
¶
step_agent_with_actions(
agent_id: str, obs: Optional[dict[str, Any]] = None
) -> tuple[Any, dict[str, Any]]
Advance a single agent and return both status and emitted actions.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
obs
|
Optional[dict[str, Any]]
|
Optional observation payload injected before stepping. |
None
|
返回:
| 类型 | 描述 |
|---|---|
tuple[Any, dict[str, Any]]
|
Tuple of runtime-defined status and action mapping. |
源代码位于: jianmu/swarm/base.py
step_all
async
¶
Advance all agents by one scheduler step.
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Mapping of agent IDs to their step execution status/results. |
step_all_concurrent
async
¶
Advance all agents concurrently.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
max_concurrency
|
int | None
|
Optional cap for concurrent stepping tasks. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Mapping from agent identifier to runtime-defined step result. |
源代码位于: jianmu/swarm/base.py
run_until_idle
async
¶
Drive the runtime until no agents have active work.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
max_steps
|
int
|
Maximum scheduler iterations before aborting. |
200
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Final per-agent status mapping. |
源代码位于: jianmu/swarm/base.py
join_group
¶
Subscribe an agent to a broadcast group.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
group_id
|
str
|
Group identifier to subscribe to. |
必需 |
leave_group
¶
Remove an agent from a broadcast group.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
group_id
|
str
|
Group identifier to leave. |
必需 |
subscribe_topic
¶
Subscribe an agent to a topic stream.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
topic
|
str
|
Topic identifier to subscribe to. |
必需 |
unsubscribe_topic
¶
Unsubscribe an agent from a topic stream.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
topic
|
str
|
Topic identifier to unsubscribe from. |
必需 |
get_all_tools
¶
Get all available tools for an agent.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
list
|
Effective tool list after provider resolution. |
explain_tools
¶
Explain tool resolution for an agent.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target agent identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Diagnostic payload describing providers, overrides, and final tools. |
get_dead_letters
async
¶
Return failed-delivery envelopes retained by the runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str | None
|
Optional filter for one agent's dead letters. |
None
|
limit
|
int
|
Maximum number of envelopes to return. |
100
|
返回:
| 类型 | 描述 |
|---|---|
list[dict[str, Any]]
|
Dead-letter payloads in runtime-defined dictionary form. |
源代码位于: jianmu/swarm/base.py
DefaultAgentState
¶
Bases: BaseModel
Default schema for runtime host state (extra fields allowed).
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
done |
Annotated[bool, Ephemeral(scope='run')]
|
Completion flag produced during the current run. |
final_answer |
Annotated[str, Ephemeral(scope='run')]
|
Final answer produced by the agent during the current run. |
rounds |
Annotated[int, Ephemeral(scope='run')]
|
Current round counter for the agent loop. |
tool_effects |
Annotated[dict[str, int], Ephemeral(scope='run')]
|
Aggregated tool-side-effect counters. |
actions |
Annotated[list[Any], Ephemeral(scope='step')]
|
Per-step action trace for the current step scope. |
streaming_output |
Annotated[str, Ephemeral(scope='call')]
|
Incremental streamed text for the current call scope. |
AgentRuntime
¶
AgentRuntime(
*,
roles: Optional[Dict[str, AgentRole]] = None,
event_bus: Optional[InMemoryEventBus] = None,
message_store: Optional[EnvelopeStoreProtocol] = None,
state_factory: Optional[
Callable[[AgentProfile], StateManager]
] = None,
runner_factory: Optional[
Callable[
[Behaviour, StateManager, RunContext],
ReactiveRunner,
]
] = None,
tool_providers: Optional[list[ToolProvider]] = None,
default_model_client: Any = None,
auto_start: bool = False,
session_id: Optional[str] = None,
mcp_config_path: Optional[str] = None,
skills_dir: Optional[str] = None,
mailbox_drain_max_iterations: int = 100,
message_store_gc_min_advance: int = 1000,
delivery_max_failures: int = 3,
restart_policy: str = "on_failure",
max_restarts: int = 3,
restart_backoff_s: float = 0.2,
same_run_no_send_retries: int = 1,
checkpointer: Optional[CheckpointerProtocol] = None,
checkpoint_thread_id: Optional[str] = None,
context_builder: Optional[
ContextBuilderProtocol
] = None,
runtime_event_bus: Optional[RuntimeEventBus] = None,
)
Unified multi-agent runtime with host/message-store/tool-provider composition.
AgentRuntime APIs include deterministic stepping: - step_agent(agent_id) - step_all() - run_until_idle()
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
default_model_client |
Default model client injected into spawned hosts. |
|
session_id |
Optional session identifier propagated into runtime events. |
|
_event_bus |
In-memory bus carrying runtime lifecycle events. |
|
_message_store |
Envelope store used for inter-agent message delivery. |
|
_tool_providers |
list[ToolProvider]
|
Ordered tool providers merged for each host. |
_checkpointer |
Optional snapshot backend for runtime state persistence. |
|
_checkpoint_thread_id |
Default checkpoint thread identifier override. |
|
_context_builder |
Optional shared context builder for mailbox and prompt use. |
|
_runtime_event_bus |
Optional cross-module event bus for swarm lifecycle events. |
Create a multi-agent runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
roles
|
Optional[Dict[str, AgentRole]]
|
Optional mapping of role names to role factories. |
None
|
event_bus
|
Optional[InMemoryEventBus]
|
Optional event bus implementation. |
None
|
message_store
|
Optional[EnvelopeStoreProtocol]
|
Optional message store implementation. |
None
|
state_factory
|
Optional[Callable[[AgentProfile], StateManager]]
|
Factory used to build a state manager for each agent. |
None
|
runner_factory
|
Optional[Callable[[Behaviour, StateManager, RunContext], ReactiveRunner]]
|
Factory used to build a runner for each agent tree. |
None
|
tool_providers
|
Optional[list[ToolProvider]]
|
Additional tool providers merged after builtin swarm tools. |
None
|
default_model_client
|
Any
|
Default model client injected into spawned agents. |
None
|
auto_start
|
bool
|
Whether spawned agents should begin running immediately. |
False
|
session_id
|
Optional[str]
|
Optional session identifier propagated into events and state. |
None
|
mcp_config_path
|
Optional[str]
|
Optional MCP provider configuration path. |
None
|
skills_dir
|
Optional[str]
|
Optional skills directory used to bootstrap prompt configuration. |
None
|
mailbox_drain_max_iterations
|
int
|
Max envelopes to drain in one mailbox pass. |
100
|
message_store_gc_min_advance
|
int
|
Minimum sequence advance before store pruning. |
1000
|
delivery_max_failures
|
int
|
Maximum failed deliveries before dead-letter handling. |
3
|
restart_policy
|
str
|
Host restart policy: |
'on_failure'
|
max_restarts
|
int
|
Maximum restart attempts per host. |
3
|
restart_backoff_s
|
float
|
Delay before retrying a failed host. |
0.2
|
same_run_no_send_retries
|
int
|
Immediate retries when a run completes without sending. |
1
|
checkpointer
|
Optional[CheckpointerProtocol]
|
Optional runtime checkpoint backend. |
None
|
checkpoint_thread_id
|
Optional[str]
|
Optional checkpoint thread identifier override. |
None
|
context_builder
|
Optional[ContextBuilderProtocol]
|
Optional context builder used both when merging incoming history and when injecting prompt-time context. |
None
|
runtime_event_bus
|
Optional[RuntimeEventBus]
|
Optional cross-module runtime event bus used to expose swarm lifecycle events alongside single-agent flows. |
None
|
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If numeric guardrails or restart-policy values are invalid. |
源代码位于: jianmu/swarm/runtime/core.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
event_bus
property
¶
Return the runtime event bus.
返回:
| 类型 | 描述 |
|---|---|
InMemoryEventBus
|
The event bus instance. |
message_store
property
¶
Return the runtime message store.
返回:
| 类型 | 描述 |
|---|---|
EnvelopeStoreProtocol
|
The message store instance. |
hosts
property
¶
Return the live host registry.
返回:
| 类型 | 描述 |
|---|---|
Dict[str, AgentHost]
|
A dictionary mapping agent IDs to AgentHost instances. |
initialize_async
async
¶
Initialize runtime-owned providers and resources.
返回:
| 类型 | 描述 |
|---|---|
None
|
|
源代码位于: jianmu/swarm/runtime/core.py
close_async
async
¶
Stop active agents and close runtime-owned providers.
返回:
| 类型 | 描述 |
|---|---|
None
|
|
源代码位于: jianmu/swarm/runtime/core.py
save_snapshot
async
¶
Serialize hosts and message-store state into a runtime snapshot.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Optional checkpoint thread identifier override. |
None
|
step
|
int | None
|
Optional explicit checkpoint step. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Serializable runtime snapshot payload. |
源代码位于: jianmu/swarm/runtime/core.py
restore_snapshot
async
¶
Restore runtime hosts and message store from a saved snapshot.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Optional checkpoint thread identifier override. |
None
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
|
源代码位于: jianmu/swarm/runtime/core.py
register_tool_provider
¶
Register a tool provider before runtime initialization.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
provider
|
ToolProvider
|
Provider appended after the builtin swarm provider chain. |
必需 |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If called after the runtime has already initialized. |
源代码位于: jianmu/swarm/runtime/core.py
register_role
¶
Register a named role factory.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
role
|
AgentRole
|
Role object keyed by its |
必需 |
spawn
¶
spawn(
role: str | AgentRole,
task: str | None = None,
parent_id: str | None = None,
mode: str = "detached",
constraints: Any | None = None,
agent_id: str | None = None,
) -> str
Create a host for a role and return its agent identifier.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
role
|
str | AgentRole
|
Registered role name or role object. |
必需 |
task
|
str | None
|
Optional initial task for the agent. |
None
|
parent_id
|
str | None
|
Optional parent host identifier for attached agents. |
None
|
mode
|
str
|
Attachment mode, typically |
'detached'
|
constraints
|
Any | None
|
Optional execution constraints applied to the new host. |
None
|
agent_id
|
str | None
|
Optional stable identifier to reuse while reconstructing a checkpointed host. |
None
|
返回:
| 类型 | 描述 |
|---|---|
str
|
Newly created agent identifier. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If the role builds an invalid root tree. |
源代码位于: jianmu/swarm/runtime/core.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
kill
¶
Stop a host synchronously and schedule cleanup of its tasks.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
kill_async
async
¶
Stop a host asynchronously and await task cancellation.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
pause
¶
Pause a host so it no longer consumes scheduler work.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
resume
¶
Resume a paused host and schedule new work.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
wake
¶
Mark a host dirty and ensure its runner task exists.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
reason
|
str | None
|
Optional observability reason attached to the wake event. |
None
|
源代码位于: jianmu/swarm/runtime/core.py
preempt_agent
async
¶
Interrupt a running host and schedule it for a fresh restart.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
reason
|
str | None
|
Optional reason emitted in the preemption event. |
None
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
|
源代码位于: jianmu/swarm/runtime/core.py
send_message
async
¶
send_message(
*,
sender_id: str | None,
content: str,
to_agent_id: str | None = None,
group_id: str | None = None,
topic: str | None = None,
content_type: str = "text",
metadata: Optional[dict[str, Any]] = None,
) -> int
Append a routed message and wake matching recipients.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
sender_id
|
str | None
|
Originating agent identifier, or |
必需 |
content
|
str
|
Message body. |
必需 |
to_agent_id
|
str | None
|
Optional direct recipient identifier. |
None
|
group_id
|
str | None
|
Optional group recipient identifier. |
None
|
topic
|
str | None
|
Optional topic recipient. |
None
|
content_type
|
str
|
Message content-type label stored in metadata. |
'text'
|
metadata
|
Optional[dict[str, Any]]
|
Optional additional metadata persisted with the message. |
None
|
返回:
| 类型 | 描述 |
|---|---|
int
|
Monotonic message sequence number assigned by the store. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If zero or multiple routing targets are supplied. |
源代码位于: jianmu/swarm/runtime/core.py
enqueue_internal_message
¶
enqueue_internal_message(
*,
agent_id: str,
message: Message,
source: str | None = None,
wake: bool = False,
) -> bool
Deliver a runtime-local message through the mailbox handoff.
Unlike direct host.inbox mutation, this always advances the
mailbox version and marks the next execution input as pending.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Identifier of the local target host. |
必需 |
message
|
Message
|
Message to append to the target host's mailbox. |
必需 |
source
|
str | None
|
Optional provenance label stored in message metadata. |
None
|
wake
|
bool
|
Whether to schedule and signal immediate auto-mode handling. |
False
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
|
源代码位于: jianmu/swarm/runtime/core.py
step_agent
async
¶
Advance one agent in manual mode.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
obs
|
Optional[dict[str, Any]]
|
Optional observation payload injected before the step. |
None
|
返回:
| 类型 | 描述 |
|---|---|
Status
|
Root status after the step completes. |
源代码位于: jianmu/swarm/runtime/core.py
step_agent_with_actions
async
¶
step_agent_with_actions(
agent_id: str, obs: Optional[dict[str, Any]] = None
) -> tuple[Status, dict[str, Any]]
Advance one agent and return both status and emitted actions.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
obs
|
Optional[dict[str, Any]]
|
Optional observation payload injected before the step. |
None
|
返回:
| 类型 | 描述 |
|---|---|
tuple[Status, dict[str, Any]]
|
Tuple of root status and the action mapping returned by the runner. |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If the target host is in auto mode. |
源代码位于: jianmu/swarm/runtime/core.py
step_all
async
¶
Advance all hosts sequentially in manual mode.
返回:
| 类型 | 描述 |
|---|---|
dict[str, Status]
|
Mapping from agent identifier to root status. |
step_all_concurrent
async
¶
Advance all hosts concurrently in manual mode.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
max_concurrency
|
int | None
|
Optional cap for concurrent stepping tasks. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Status]
|
Mapping from agent identifier to root status. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If |
源代码位于: jianmu/swarm/runtime/core.py
run_until_idle
async
¶
Advance hosts until the runtime becomes idle.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
max_steps
|
int
|
Maximum scheduler iterations before returning. |
200
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Status]
|
Last per-agent root-status mapping observed during the run. |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If any host is running in auto mode. |
源代码位于: jianmu/swarm/runtime/core.py
join_group
¶
Subscribe a host to a broadcast group.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
The ID of the agent/host joining the group. |
必需 |
group_id
|
str
|
The ID of the broadcast group to join. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
leave_group
¶
Remove a host from a broadcast group.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
The ID of the agent/host leaving the group. |
必需 |
group_id
|
str
|
The ID of the broadcast group to leave. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
subscribe_topic
¶
Subscribe a host to a topic.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
The ID of the agent/host subscribing. |
必需 |
topic
|
str
|
The topic name to subscribe to. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
unsubscribe_topic
¶
Unsubscribe a host from a topic.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
The ID of the agent/host unsubscribing. |
必需 |
topic
|
str
|
The topic name to unsubscribe from. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
emit
¶
Normalize and publish one runtime event.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
event
|
AgentEvent
|
The event to publish. |
必需 |
源代码位于: jianmu/swarm/runtime/core.py
subscribe_events
¶
Subscribe to normalized runtime events.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
callback
|
Callable[[AgentEvent], None]
|
Consumer invoked for each emitted |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Callable[[], None]
|
Unsubscribe callback. |
源代码位于: jianmu/swarm/runtime/core.py
subscribe_observability
¶
subscribe_observability(
callback: Callable[[str, dict[str, Any]], None],
*,
runtime_events: bool = True,
trace_events: bool = False,
) -> Callable[[], None]
Subscribe to runtime and trace observability streams.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
callback
|
Callable[[str, dict[str, Any]], None]
|
Consumer invoked as |
必需 |
runtime_events
|
bool
|
Whether normalized runtime events should be forwarded. |
True
|
trace_events
|
bool
|
Whether low-level trace events should be forwarded. |
False
|
返回:
| 类型 | 描述 |
|---|---|
Callable[[], None]
|
Unsubscribe callback that detaches all registered listeners. |
源代码位于: jianmu/swarm/runtime/core.py
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 | |
get_profile
¶
Return the profile for a host, if it exists.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Optional[AgentProfile]
|
Agent profile, or |
源代码位于: jianmu/swarm/runtime/core.py
list_agents
¶
Return profiles for all active hosts.
返回:
| 类型 | 描述 |
|---|---|
list[AgentProfile]
|
A list of profiles for all active hosts. |
get_host
¶
Return the live host object for one agent.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
The ID of the target agent. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Optional[AgentHost]
|
The live host object, or None if not found. |
源代码位于: jianmu/swarm/runtime/core.py
resolve_suspension
async
¶
resolve_suspension(
*,
agent_id: str,
thread_id: str,
request_id: str,
payload: dict[str, Any],
suspension_mode: str
| SuspensionMode = SuspensionMode.YIELD,
reset_tree: bool = True,
reset_data: bool = False,
max_ticks: int | None = None,
timeout_s: float | None = None,
checkpoint_interval: int = 1,
max_fps: float = 60.0,
) -> ResumeInteractionResult
Resolve one host-owned suspension through the runtime host registry.
This facade only serves runtime-host scenarios where the runtime
already owns the agent_id -> host -> runner relationship. It does
not replace standalone ReactiveRunner.resume_and_continue() or
Agent.resume_interaction() entrypoints.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Runtime host identifier used to locate the target runner. |
必需 |
thread_id
|
str
|
Checkpoint thread identifier routed to the target runner. |
必需 |
request_id
|
str
|
Active suspension request identifier to resume. |
必需 |
payload
|
dict[str, Any]
|
Host-provided resume payload. |
必需 |
suspension_mode
|
str | SuspensionMode
|
Host-facing mode for any later suspension. |
YIELD
|
reset_tree
|
bool
|
Whether to reset tree execution before resuming. |
True
|
reset_data
|
bool
|
Whether to reset the backing state first. |
False
|
max_ticks
|
int | None
|
Optional hard tick limit. |
None
|
timeout_s
|
float | None
|
Optional wall-clock timeout for the resumed run. |
None
|
checkpoint_interval
|
int
|
Checkpoint save interval for the resumed run. |
1
|
max_fps
|
float
|
Runner FPS cap for the resumed run. |
60.0
|
返回:
| 类型 | 描述 |
|---|---|
ResumeInteractionResult
|
Structured resume status plus resumed run result when available. |
源代码位于: jianmu/swarm/runtime/core.py
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 | |
get_dead_letters
async
¶
Return dead-letter payloads from the message store.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str | None
|
Optional filter for one agent's dead letters. |
None
|
limit
|
int
|
Maximum number of dead-letter records to return. |
100
|
返回:
| 类型 | 描述 |
|---|---|
list[dict[str, Any]]
|
Dead-letter payloads, or an empty list when unsupported. |
源代码位于: jianmu/swarm/runtime/core.py
get_all_tools
¶
Return the merged tool list available to a host.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
list
|
Effective merged tool list. |
源代码位于: jianmu/swarm/runtime/core.py
explain_tools
¶
Return diagnostics for tool resolution on a host.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
agent_id
|
str
|
Target host identifier. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Diagnostic payload describing providers, overrides, and effective tools. |
源代码位于: jianmu/swarm/runtime/core.py
start_all
¶
AgentTeam
¶
AgentTeam(
*,
roles: dict[str, AgentRole] | None = None,
default_model_client: Any = None,
tool_providers: Sequence[ToolProvider] | None = None,
checkpointer: CheckpointerProtocol | None = None,
checkpoint_thread_id: str | None = None,
runtime_event_bus: RuntimeEventBus | None = None,
context_builder: ContextBuilderProtocol | None = None,
session_id: str | None = None,
auto_start: bool = False,
)
User-facing facade that wraps one AgentRuntime instance.
AgentTeam centralizes runtime assembly, lifecycle management, and
snapshot entrypoints for Jianmu's multi-agent runtime without replacing
the underlying swarm engine.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
_defaults |
Stable defaults reused when spawning or configuring hosts. |
|
_runtime |
Wrapped low-level swarm runtime instance. |
|
_checkpointer |
Resolved checkpoint backend shared with the runtime. |
|
_checkpoint_thread_id |
Default checkpoint thread identifier. |
Create a high-level facade around one assembled AgentRuntime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
roles
|
dict[str, AgentRole] | None
|
Optional mapping of role names to role objects. |
None
|
default_model_client
|
Any
|
Optional default model provider shared by hosts. |
None
|
tool_providers
|
Sequence[ToolProvider] | None
|
Optional additional runtime tool providers. |
None
|
checkpointer
|
CheckpointerProtocol | None
|
Default runtime checkpointer, if any. |
None
|
checkpoint_thread_id
|
str | None
|
Default checkpoint thread identifier, if any. |
None
|
runtime_event_bus
|
RuntimeEventBus | None
|
Optional runtime-semantic event bus shared across spawned agents and bridged swarm lifecycle events. |
None
|
context_builder
|
ContextBuilderProtocol | None
|
Optional context builder shared by mailbox-history merge and prompt-time context assembly. |
None
|
session_id
|
str | None
|
Optional runtime session identifier. |
None
|
auto_start
|
bool
|
Whether spawned hosts should begin running automatically. |
False
|
源代码位于: jianmu/swarm/team.py
runtime
property
¶
defaults
property
¶
Return the team-level defaults captured during assembly.
返回:
| 类型 | 描述 |
|---|---|
AgentTeamDefaults
|
The resulting |
start
async
¶
close
async
¶
spawn
¶
spawn(
role: str | AgentRole,
task: str | None = None,
parent_id: str | None = None,
mode: str = "detached",
constraints: Any | None = None,
agent_id: str | None = None,
) -> str
Create one runtime host via the wrapped runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
role
|
str | AgentRole
|
Role name to resolve or execute. |
必需 |
task
|
str | None
|
The |
None
|
parent_id
|
str | None
|
Identifier for parent. |
None
|
mode
|
str
|
The |
'detached'
|
constraints
|
Any | None
|
Collection of constraint values. |
None
|
agent_id
|
str | None
|
Optional stable identifier for checkpointed host rebuilds. |
None
|
返回:
| 类型 | 描述 |
|---|---|
str
|
The resulting string value. |
源代码位于: jianmu/swarm/team.py
send
async
¶
send(
*,
content: str,
sender_id: str | None = None,
to_agent_id: str | None = None,
group_id: str | None = None,
topic: str | None = None,
content_type: str = "text",
metadata: dict[str, Any] | None = None,
) -> int
Send one message through the wrapped runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
content
|
str
|
The |
必需 |
sender_id
|
str | None
|
Identifier for sender. |
None
|
to_agent_id
|
str | None
|
Identifier for to agent. |
None
|
group_id
|
str | None
|
Identifier for group. |
None
|
topic
|
str | None
|
The |
None
|
content_type
|
str
|
The |
'text'
|
metadata
|
dict[str, Any] | None
|
The |
None
|
返回:
| 类型 | 描述 |
|---|---|
int
|
The resulting integer value. |
源代码位于: jianmu/swarm/team.py
save_snapshot
async
¶
Persist one runtime snapshot through the wrapped runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Identifier for thread. |
None
|
step
|
int | None
|
The |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
The resulting mapping value. |
源代码位于: jianmu/swarm/team.py
restore_snapshot
async
¶
Restore one runtime snapshot through the wrapped runtime.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
thread_id
|
str | None
|
Identifier for thread. |
None
|
返回:
| 类型 | 描述 |
|---|---|
bool
|
True if the operation succeeds; otherwise False. |
源代码位于: jianmu/swarm/team.py
AgentTeamDefaults
dataclass
¶
AgentTeamDefaults(
default_model_client: Any = None,
context_builder: ContextBuilderProtocol | None = None,
tool_providers: tuple[ToolProvider, ...] = tuple(),
)
Stable team-level defaults propagated into newly spawned hosts.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
default_model_client |
Any
|
Default model provider injected into agent hosts. |
context_builder |
ContextBuilderProtocol | None
|
Optional context builder shared by mailbox-history merge and prompt-time context assembly. |
tool_providers |
tuple[ToolProvider, ...]
|
Additional tool providers registered for the runtime. |
MCPToolProvider
¶
Bases: BaseToolProvider
Load MCP tools from config and expose them as Jianmu tools.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
config_path |
Filesystem path to the MCP config file. |
|
_clients |
dict[str, MCPClient]
|
Connected MCP clients keyed by configured server name. |
_tools |
list[Tool]
|
Cached wrapped Tool instances exported by all connected servers. |
Create a provider backed by an MCP config file.
源代码位于: jianmu/mcp/provider.py
initialize
async
¶
Connect configured MCP clients eagerly.
源代码位于: jianmu/mcp/provider.py
get_tools
¶
Return cached MCP-backed Jianmu tools.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
_
|
Any
|
Unused keyword arguments. |
{}
|
返回:
| 类型 | 描述 |
|---|---|
list[Tool]
|
A list of cached Tool instances. |
close
async
¶
Close all managed MCP clients.
源代码位于: jianmu/mcp/provider.py
SwarmRole
¶
SwarmRole(
*,
name: str,
runtime: AgentRuntimeProtocol,
system_prompt: str = "You are a helpful assistant.",
model_client: Optional[ModelClient] = None,
model_client_factory: Optional[
Callable[[AgentProfile], ModelClient]
] = None,
tools: Optional[list[Tool]] = None,
runtime_tool_names: Optional[list[str]] = None,
max_iterations: int = 15,
constraints: Optional[Constraints] = None,
skills_dir: str | Path | None = None,
enabled_skills: Optional[list[str]] = None,
explicit_enabled_skills: bool = False,
skill_files: Optional[list[str | Path]] = None,
skill_prompt_mode: str = "summary",
)
Ready-to-use role implementation for liquid-topology collaboration.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
name |
Public role name used for lookup and runtime diagnostics. |
|
runtime |
Swarm runtime used to resolve tools and spawn profiles. |
|
system_prompt |
Base system prompt prepended to each task prompt. |
|
model_client |
Shared model client used when no factory is provided. |
|
model_client_factory |
Optional factory that resolves a model client per agent profile. |
|
tools |
Additional static tools attached to each spawned agent. |
|
runtime_tool_names |
Optional allowlist for runtime-provided tool names. |
|
max_iterations |
Max inner ReAct rounds for the spawned agent tree. |
|
constraints |
Optional execution constraints forwarded into the node config. |
|
skills_dir |
Optional resolved skill directory path. |
|
enabled_skills |
Skill names enabled for the role by default. |
|
skill_files |
Additional explicit skill file paths for the role. |
|
skill_prompt_mode |
Skill prompt rendering mode for the node config. |
Configure a reusable swarm agent role template.
源代码位于: jianmu/swarm/role.py
build_tree
¶
Build the swarm-oriented skill tree for one agent profile.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
profile
|
AgentProfile
|
AgentProfile used to build the tree. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Any
|
The configured SwarmNode. |
源代码位于: jianmu/swarm/role.py
FunctionRole
¶
Bases: FunctionalRole
Wrap a plain function as a FunctionalRole with metadata.
Create a functional role with explicit display description.
源代码位于: jianmu/swarm/decorator.py
FunctionalRole
¶
Role adapter: define agent logic via a plain callable.
Create a role wrapper around a plain handler function.
源代码位于: jianmu/swarm/decorator.py
build_tree
¶
Build a single functional node for one agent profile.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
profile
|
AgentProfile
|
AgentProfile instance to build the tree for. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Any
|
An instance of _FunctionalNode. |