Skip to main content

Mainspring

框架设计、版本路线图、使用说明和 UML 文档统一维护在仓库根的 documentation/mainspring/。

业务无关的 Agent 框架层。提供 Agent 运行循环(Plan → Decide → Execute → Observe)、统一插件协议、Skill/Tool 执行、记忆机制与能力端口(Ports)。

  • 不依赖业务层的 HTTP / 数据库 / 配置 / 多租户概念,可独立安装使用。
  • 通过 ports.py 定义能力端口(PermissionChecker / LongTermMemory / WorkingMemory / LLMGateway / Embedder / Plugin 等),由宿主(业务层)实现并注入。

特性

能力 说明
Agent 运行循环 手写状态机:Decide → Execute → Observe(Plan 可选开启),带迭代上限防死循环
流式输出 StreamingLLMGateway + message.delta token 级事件;不支持时自动回退非流式
结构化输出 chat(schema=PydanticModel):LLMResponse.parsed 直出模型实例,校验失败抛 StructuredOutputError
@tool 装饰器 类型化函数直出 BaseTool:签名自动生成参数 JSON Schema,docstring 即描述
Checkpointer 后端 checkpoint/:SQLite / Redis / PostgreSQL 官方实现,与 InMemoryCheckpointer 行为互换;损坏/版本不符响亮失败
上下文治理 ContextManager 端口 + 默认滑窗(SlidingWindowContext),长任务不爆窗口
统一插件协议 Plugin / PluginManifest,Tool / Skill / Knowledge… 统一接入
工具执行 内置 calculator/http,支持 MCP 客户端、HTTP(OpenAPI) 适配
技能执行 四种形态:prompt / function / flow / agent
记忆 短期 Working Brain(Redis)+ 会话固化 Consolidator + LongTermMemory 端口
授权 纯逻辑 check_permission(admin 绕过 / deny 优先 / 默认拒绝 / 高危审批)
事件 运行时事件模型(非传输层),含 token 级 message.delta

安装

pip install mainspring        # 发布后

# monorepo 内以 path 依赖(开发态)
# 宿主工程的 pyproject.toml:
#   [tool.poetry.dependencies]
#   mainspring = { path = "mainspring", develop = true }

依赖:python>=3.11、litellm、pydantic、httpx、redis。


目录结构

mainspring/
├── ports.py          # 能力端口 + 权限/记忆数据类型(框架与宿主的契约)
├── log.py            # `mainspring` 命名空间日志(NullHandler,不自行配置)
├── context.py        # SlidingWindowContext(ContextManager 默认实现)
├── core/
│   ├── runtime.py     # AgentRuntime 门面(run/resume + 强类型)
│   ├── state.py       # AgentState(循环内共享状态)
│   ├── resilience.py  # RetryPolicy / CircuitBreaker
│   ├── checkpointer.py# InMemoryCheckpointer(测试/进程内默认)
│   └── nodes/         # plan(可选)/ decide / execute / observe
├── checkpoint/       # Checkpointer 官方后端(SQLite/Redis/PostgreSQL)+ JSON 信封
├── plugins/          # Plugin 协议 + PluginRegistry + ref 解析
├── skills/           # prompt/function/flow/agent 四类 Skill
├── tools/            # builtin / MCP / HTTP(OpenAPI) 工具
├── memory/           # WorkingBrain + Consolidator + MemoryManager 门面
├── events/           # 运行时事件模型(run.started/step.completed/…)
├── knowledge/        # Knowledge/Retriever 端口插件形态
├── evaluation/       # GoldenSet / run_evaluation / HeuristicJudge
├── observability/    # Tracer(可选 OTel)+ Metrics
├── security/         # 工具结果边界标注 + Redactor 脱敏
└── llm/              # LLMGateway/Embedder 协议 + LiteLLM 实现 + 成本/路由

快速开始

import asyncio

from mainspring import AgentDefinition, AgentRuntime, RunContext, RuntimeDeps
from mainspring.llm.litellm_gateway import LiteLLMGateway
from mainspring.plugins.registry import PluginRegistry
from mainspring.tools.registry import build_default_registry


async def main():
    # 1. 装配插件(内置 calculator / http)
    registry = PluginRegistry()
    for tool in build_default_registry().all():
        registry.register_tool(tool)

    # 2. 强类型门面:AgentDefinition(装配什么)+ RuntimeDeps(注入哪些端口)
    definition = AgentDefinition(model="deepseek-chat", system_prompt="你是助手", plugins=registry.all())
    deps = RuntimeDeps(llm=LiteLLMGateway(model="deepseek-chat", api_key="sk-..."))

    # 3. 运行 → RunResult(强类型,不再是裸 dict)
    result = await AgentRuntime().run(
        definition, "计算 3*8 再加 100", RunContext(run_id="demo", session_id="s1"), deps
    )
    print(result.status, result.result)      # completed, 3*8+100 = 124
    print(result.steps, result.token_usage)


asyncio.run(main())

RuntimeDeps 只要求 llm;其余端口(permission_checker / long_term_memory / knowledge / event_sink / checkpointer / tracer / metrics …)按需注入,全部契约集中在 mainspring.ports。


核心概念

AgentState(白板式共享状态)

四个节点不互相传参,而是读写同一份 AgentState(TypedDict)。节点返回一个 dict,运行时自动 merge 回状态。

关键字段:task / messages / plan / action / action_input / last_tool_result / iteration / max_iterations / status / result / memory_ctx / approvals / subagent_depth / token_usage。

运行循环

(plan ─►) decide ─► execute ─► observe ─┐
                 ▲                      │ (未完成)
                 └──────── decide ◄─────┘
                                        │ (action=="__finish__" 或 iteration 触顶)
                                        ▼ END
节点 职责
plan 拆解任务为步骤清单(默认关闭,RuntimeConfig(enable_planning=True) 开启;失败退化为单步)
decide 带工具 schema 调 LLM,选择插件或收尾给答案;流式时逐 token 发 message.delta
execute 权限校验后调用插件,归一化结果为字符串
observe 回填结果、iteration+1、触顶兜底

Plan 默认关闭的原因:它每次 run 多花一次 LLM 调用,而计划状态从未被跟踪;单循环决策已覆盖大多数任务(与 OpenAI Agents SDK 同一哲学)。


能力端口(Ports)

框架定义端口、宿主实现。全部在 ports.py。

PermissionChecker

from mainspring.ports import PermissionChecker, PermissionContext, PermissionDecision, check_permission

class MyPermissionChecker(PermissionChecker):
    def check(self, ctx, action, resource_type, resource_id,
              resource_permission="read", requires_approval=False, approved=None):
        return check_permission(ctx, action, resource_type, resource_id,
                                resource_permission=resource_permission,
                                requires_approval=requires_approval, approved=approved)

PermissionContext:permission_codes: set[str]、旧版资源级兼容 grant_keys、动作级 grant_actions: set[(resource_type, resource_id, action, effect)]、is_admin: bool。新授权使用 grant_actions;宿主迁移旧数据时可用 grant_keys 保留旧语义。

判定顺序:admin 绕过 → 功能权限 run:execute → deny 优先 → read 默认放行 → grant 要求 → 高危审批。

LongTermMemory / WorkingMemory

from mainspring.ports import LongTermMemory, MemoryEntry

class InMemoryLongTerm(LongTermMemory):
    async def add(self, db, *, tenant_id, user_id, session_id, content,
                  importance=0.5, confidence=0.5) -> str: ...
    async def recall(self, db, tenant_id, user_id, query, top_k=5) -> list[MemoryEntry]: ...

db 参数由宿主传入(如 AsyncSession),协议不约束其类型。框架自带的 Redis 实现见 mainspring.memory.working.WorkingBrain。

Embedder

from mainspring.llm.embedder import LiteLLMEmbedder, HashEmbedder

embedder = LiteLLMEmbedder("text-embedding-3-small", api_key="sk-...")  # 有 key
embedder = HashEmbedder(1536)                                          # 离线回退(确定性 hash)

开发自定义 Tool

from mainspring.tools.base import BaseTool, ToolResult

class WeatherTool(BaseTool):
    name = "weather"
    description = "查询城市天气"
    permission = "read"              # read | write | admin
    parameters = {
        "type": "object",
        "properties": {"city": {"type": "string", "description": "城市名"}},
        "required": ["city"],
    }

    async def run(self, city: str) -> ToolResult:
        return ToolResult(success=True, output=f"{city}:晴 22℃")


registry.register_tool(WeatherTool())   # 内部用 ToolAsPlugin 适配成 Plugin

开发自定义 Skill

Skill 是 kind="skill" 的插件,四种形态,用 PluginManifest 声明能力:

from mainspring.plugins.base import PluginManifest
from mainspring.plugins.registry import PluginRegistry
from mainspring.skills.prompt_skill import PromptSkill
from mainspring.skills.function_skill import FunctionSkill
from mainspring.skills.agent_skill import AgentSkill
from mainspring.skills.flow_skill import FlowSkill

registry = PluginRegistry()

registry.register(PromptSkill(           # prompt:模板渲染
    PluginManifest(name="refund_policy", kind="skill"),
    {"template": "退款政策:7 天无理由(上下文:{{memory_ctx}})"},
))

registry.register(FunctionSkill(         # function:执行 Python(非沙箱,仅可信作者)
    PluginManifest(name="add", kind="skill"),
    {"source": "def run(**kw):\n    return str(int(kw['a']) + int(kw['b']))"},
))

registry.register(AgentSkill(            # agent:调子 Agent(注入 run_subagent 回调)
    PluginManifest(name="escalate", kind="skill"),
    {"agent_ref": "agent_escalation"},
    run_subagent=my_subagent_runner,
))

registry.register(FlowSkill(             # flow:多步流程(注入 run_flow 回调)
    PluginManifest(name="report", kind="skill"),
    {"graph_spec": {}},
    run_flow=my_flow_runner,
))

PluginManifest 字段:name / version / kind / description / parameters(JSON Schema) / permission / requires_approval / dependencies / tags。


插件引用与命名

from mainspring.plugins.manifest import parse_ref, format_ref

parse_ref("tool:calculator")        # PluginRef(kind="tool", name="calculator")
parse_ref("skill:refund@1.2.0")     # PluginRef(kind="skill", name="refund", version="1.2.0")
format_ref("skill", "refund", "1.2.0")  # "skill:refund@1.2.0"

function_name 命名空间:tool 用裸名(calculator),非 tool 种类加前缀(skill_refund_policy),避免 function-calling 撞名。LLM 返回的 tool_call.name 即 function_name,可被 PluginRegistry.get() 反查。


事件与流式

经 RuntimeDeps.event_sink 注入异步回调,每步产出一个 RuntimeEvent(run.started / step.completed / run.completed / …):

async def sink(event):
    print(event.event, event.data)   # 框架只出数据;SSE/WebSocket 序列化由宿主做

deps = RuntimeDeps(llm=llm, event_sink=sink)

事件类型:run.started / message.delta / step.completed / run.completed / run.failed / run.awaiting_human / run.approved / run.rejected。框架只产出事件数据,传输由宿主负责。

流式(token 级):当网关实现 StreamingLLMGateway(如 LiteLLMGateway)且注入了 event_sink 时,Decide 自动走流式并逐 token 发出 message.delta 事件,宿主可直接转 SSE 打字机效果:

async def sink(event):
    if event.event == "message.delta":
        print(event.data["delta"], end="", flush=True)

deps = RuntimeDeps(llm=LiteLLMGateway(...), event_sink=sink)

注意两点:message.delta 是临时性事件——Decide 重试会从头重新流式,消费方应增量渲染而非持久化;只有折叠后的最终结果才是权威数据。未注入 event_sink 或网关不支持 chat_stream 时自动回退 chat(),零成本。


上下文治理

长任务的对话历史会无限增长。ContextManager 端口(ports.py)在每个 Decide 前压缩历史,被丢弃的轮次永久移除(这正是控制窗口的机制):

from mainspring import SlidingWindowContext

# 零配置:超过 40 条即滑窗压缩 + 截断超长工具结果
deps = RuntimeDeps(llm=llm)
definition = AgentDefinition(model="...", runtime=RuntimeConfig(max_history_messages=40))

# 自定义策略(如 LLM 摘要压缩):实现 ContextManager 协议
deps = RuntimeDeps(llm=llm, context_manager=MySummarizingContext(llm, max_tokens=8000))

默认实现 SlidingWindowContext:保留头部 system 消息 + 最新窗口、切点跳过孤立 tool 消息(避免 API 校验失败)、超长工具结果就地截断。宿主的摘要压缩实现可在构造时自带网关。


记忆编排

from mainspring.memory.manager import MemoryManager
from mainspring.memory.consolidator import Consolidator
from mainspring.memory.working import WorkingBrain

manager = MemoryManager(
    working=WorkingBrain(redis_client),
    vector_store=my_long_term_memory,                          # 实现 LongTermMemory
    consolidator=Consolidator(my_long_term_memory, similarity_threshold=0.85),
)

await manager.write(session_id, {"role": "user", "content": "..."})    # 短期写入
history = await manager.get_history(session_id)                       # 短期读取
entries = await manager.recall(db, tenant_id, user_id, query, top_k=5) # 长期召回
await manager.consolidate(db, session_id, tenant_id, user_id)          # 短期→长期固化

完整示例

example/ 目录下有每个模块的可运行示例(权限/HITL、事件流式、记忆、知识、可靠性、多厂商 fallback、评测等)。典型的高危审批 + 恢复流程:

result = await runtime.run(definition, "删除账号 u42", context, deps)
# result.status == "awaiting_human", result.pending_approvals = [...]

resumed = await runtime.resume(definition, "run-1", ["delete_account"], deps)
# resumed.status == "completed"

详见 example/permissions_hitl.py。


API 速查

符号 位置 签名
AgentRuntime core.runtime run(definition, task, context, deps) -> RunResult / resume(...)
RuntimeDeps core.runtime llm / permission_checker / long_term_memory / knowledge / event_sink / checkpointer / context_manager / tracer / metrics / retry …
RuntimeConfig core.runtime max_iterations / timeout_seconds / max_subagent_depth / max_total_tokens / enable_planning / max_history_messages
SlidingWindowContext context ContextManager 默认实现(滑窗 + 工具结果截断)
StreamingLLMGateway / ChatChunk ports / llm.base 可选流式协议;LiteLLMGateway.chat_stream
PluginRegistry plugins.registry register / register_tool / get / to_openai_schema / invoke
PluginManifest plugins.base Pydantic 模型 + function_name
InvokeContext plugins.base tenant_id/user_id/run_id/trace_id/session_id/subagent_depth
check_permission ports (ctx, action, resource_type, resource_id, *, resource_permission, requires_approval, approved)
Tool / BaseTool / ToolResult tools.base 工具抽象
Skill / build_skill skills.base 四形态技能
LiteLLMGateway llm.litellm_gateway (model, api_key, api_base)
LiteLLMEmbedder / HashEmbedder llm.embedder 向量化
MemoryManager / WorkingBrain / Consolidator memory.* 记忆编排

运行测试

cd mainspring
poetry install
poetry run pytest            # 168 个单元测试,无外部依赖(Redis/LLM/DB 均用 fake)

日志

框架用标准库 logging 在 mainspring 命名空间下输出日志(mainspring.core.runtime、mainspring.core.nodes.execute …),从不自行配置 handler/level——是否开启由宿主决定。

宿主开启:

import logging
from mainspring.log import configure_logging

configure_logging(level=logging.INFO)   # 或 logging.DEBUG 看更细

也可直接用宿主自己的 logging 配置(mainspring 已挂 NullHandler,不会产生 "no handler" 噪音,且会传播到根 logger)。

级别约定:

级别 场景
DEBUG 每步节点/耗时、LLM 调用元数据、插件/工具注册
INFO run 开始/完成、待审批
WARNING 越权拒绝、未知插件、LLM 失败回退、迭代触顶、工具执行失败
ERROR(含堆栈) run 失败、插件抛出异常

不记录敏感数据:api_key、消息内容、工具入参均不落日志。


设计原则

  1. 依赖倒置:框架只依赖 ports.py 的协议与纯数据,不 import 宿主的存储/HTTP/配置。
  2. 单一路径执行:无论 Tool/Skill,execute 都走 registry.get(action) → invoke。
  3. 声明与实现分离:manifest 描述「是什么」,body/run 描述「怎么做」。
  4. 容错收敛:LLM 失败退化为单步计划、空输出即收尾、迭代上限兜底,保证不死循环。
  5. 权限在执行前:不信任 LLM 的选择,execute 前强制校验。

Metadata

Release files for mainspring 3.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mainspring 3.3.0
File Size Uploaded Provenance Actions
mainspring-3.3.0.tar.gz 52.3 kB Without provenance Details for mainspring-3.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mainspring 3.3.0
File Interpreter ABI Platform Actions
mainspring-3.3.0-py3-none-any.whl Python 3 none any Details for mainspring-3.3.0-py3-none-any.whl

Total release size: 129.3 kB

Release files / mainspring-3.3.0.tar.gz

Download URL mainspring-3.3.0.tar.gz
Size 52.3 kB
Tags Source
SHA-256 checksum
How to use checksums
7ff80f971f05af11fd09e3e03c064a5ed003d21c7e3cdb0137db1c95be3fc2b0
BLAKE2b-256 checksum
How to use checksums
2a15f1b35a8b2ea7dcb4f8353459ab8b8e12a2f66d807152192d39e5dd6a545e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Release files / mainspring-3.3.0-py3-none-any.whl

Download URL mainspring-3.3.0-py3-none-any.whl
Size 77.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7218546dca22bc674ea43e0e62e49f9eaa5570e33f9a8db827c0cb85931428f4
BLAKE2b-256 checksum
How to use checksums
89cb960b61d64985936f366e146966428fa9efadc20622bbb53d2a5704c59158
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Security for mainspring 3.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page