Skip to content

框架适配器 ​

Python SDK 为十一个 Agent 框架提供适配器,TypeScript SDK 为 Vercel AI SDK 提供一个。它们共用一条判定路径,规则都一样:

  • Guard 只做限制,不替你们放宽任何权限。比如 Claude Agent SDK 里,Guard 放行之后,你们自己的权限规则和确认照常生效。
  • Guard 无法判定时,工具一律不执行。
  • Guard 放在离工具最近的那一层,判定的是工具真正会收到的参数,也就是你们自己的中间件改过之后的参数。
  • 模型在哪里收到的内容都一样,和 MCP 代理返回的一致(见模型看到什么)。

MCP 工具改走 MCP 代理。

支持的框架 ​

框架extra支持的版本接入方式最低 SDK
LangChain 1.xlangchainlangchain>=1,<2GuardMiddleware(guard),放在 create_agent(middleware=[...]) 的最后0.5.0
LangGraphlanggraphlanggraph>=1.2.11,<2guard_tool_node(tools, guard)0.8.0
Claude Agent SDKclaudeclaude-agent-sdk>=0.1.26GuardHooks(guard).options()0.5.0
OpenAI Agentsopenai-agentsopenai-agents>=0.20,<0.24protect_function_tool(tool, guard)0.5.0
Pydantic AIpydantic-ai(slim 包)pydantic-ai-slim>=2.55,<3capability guard_hooks(guard)0.8.0
Google ADKgoogle-adkgoogle-adk>=2.11,<3GuardPlugin(guard),放在 App(plugins=[...]) 的最后0.8.0
Microsoft Agent Frameworkagent-framework(只装 core)agent-framework-core>=1.21,<1.22GuardFunctionMiddleware(guard),放在 Agent(middleware=[...]) 的最后0.9.0
LlamaIndexllama-index(只装 core)llama-index-core>=0.14.25,<0.15guard_tools(tools, guard)0.9.0
Agnoagnoagno>=3.1.2,<3.2GuardToolHook(guard),放进 Agent 或 Team 的 tool_hooks0.9.0
DSPydspydspy>=3.4,<4guard_tools(tools, guard)0.9.0
CrewAIcrewaicrewai>=1.15.27,<2guard_tools(tools, guard);可选 guard_tool_call_hook(guard)0.9.0
Vercel AI SDK(TypeScript)npm 包 @preworld/guardai@^7,Node.js 22.12 及以上,ESMguardTools(tools, guard) 返回 { tools, toolApproval }npm 0.1.0

Microsoft Agent Framework、LlamaIndex、Agno、DSPy 和 CrewAI 是最新的 SDK 0.9.0 加进来的。有几个版本范围故意收得很窄:Agent Framework 和 Agno 的适配器依赖只在这些版本上核对过的行为,重新核对之后才会放宽。

SDK 版本还没有某个框架的适配器时,接入向导不会为这个框架生成接入。

不能装在一起的 extra ​

组合冲突
preworld-guard-sdk[crewai,mcp]mcp 1.28 与 2.0
preworld-guard-sdk[google-adk,gateway]、[google-adk,oauth]fastapi 和 starlette 的版本

遇到这些组合,把 MCP 代理或 HTTP broker 放在单独的虚拟环境或容器里运行。

接入示例 ​

guard 是一个 GuardClient:

python
from preworld_guard import GuardClient

guard = GuardClient("https://guard.example.com", "pwg_...", "prj_...", agent_id="support-agent")

LangChain ​

python
from preworld_guard import GuardMiddleware
agent = create_agent(model, tools, middleware=[*your_middleware, GuardMiddleware(guard)])

GuardMiddleware 放在最后,才能看到前面中间件改过的参数。拒绝和待审批作为错误 ToolMessage 交给模型。

LangGraph ​

python
from preworld_guard.langgraph import guard_tool_node
builder.add_node("tools", guard_tool_node(tools, guard))
  • 不用 interrupt():在包装器里中断会让整个节点重放。已批准的调用在 guard_resume(ticket_id) 里恢复。
  • 节点重放时(比如从检查点恢复),节点里的每个调用都会重新判定、重新审计。有副作用的工具要做成幂等的。
  • ToolNode 只接受一个同步包装器和一个异步包装器。用 compose_tool_wrappers / compose_async_tool_wrappers 把你们的包装器放在 Guard 外面。
  • 设了 handle_tool_errors=True 时,Guard 无法判定不再中止运行,而是变成一条错误消息交给模型。工具同样不执行。

Claude Agent SDK ​

python
from preworld_guard import GuardHooks
options = ClaudeAgentOptions(hooks=GuardHooks(guard).options())
  • Guard 用 PreToolUse、PostToolUse 和 PostToolUseFailure 三个钩子。
  • 钩子从不抛异常:Claude Code 把出错的钩子当作不阻断,所以任何失败都变成拒绝,原因是 GUARD_UNAVAILABLE。一次判定最多 45 秒,钩子超时设为 60 秒。
  • Guard 放行时,钩子不给出自己的决定,交回你们的权限流程。GuardHooks(guard, on_allow="allow") 恢复 0.7.0 之前的行为。
  • guard_run(...) 要包住整个 query() 迭代,或者包住 async with ClaudeSDKClient(...):钩子只能看到客户端连接那一刻的上下文。

OpenAI Agents ​

python
from agents import Agent, function_tool
from preworld_guard import GuardClient, protect_function_tool, guard_run

guard = GuardClient("https://guard.example.com", "pwg_...", "prj_...", background_events=True)

@function_tool
def update_record(value: str) -> str:
    """Update a record."""
    return value

agent = Agent(name="support", tools=[protect_function_tool(update_record, guard)])
  • 默认情况下,拒绝和待审批变成工具的结果(JSON),运行继续。on_deny="raise" 改为抛出 GuardDenied 或 GuardApprovalRequired 并中止运行,即 0.8.0 之前的行为。声明了输出 schema 的工具总是抛异常。
  • 只保护 FunctionTool。托管工具和内置工具不经过 on_invoke_tool,要另设执行边界。
  • 工具设了 timeout_seconds 时,判定的时间也算在超时里。需要审批的工具要给判定留出时间。

Pydantic AI ​

python
from preworld_guard.pydantic_ai import guard_hooks
agent = Agent(model, tools=[transfer], capabilities=[*your_capabilities, guard_hooks(guard)])
  • 这个 capability 总是把自己排在最内层。它按参数的 JSON 形式判定,工具收到的仍是带类型的参数。
  • 拒绝是 ToolFailed(模型看得到,不占重试次数)。审批默认用 Pydantic AI 自己的延后机制,所以 output_type 要包含 DeferredToolRequests。设 approval="ticket" 则改为在 ToolFailed 里返回票据。
  • 覆盖函数工具和所有 toolset,包括 MCP server。不覆盖:output 工具、external 工具(CallDeferred)、模型厂商的内置工具。
  • 持久化执行(Temporal、DBOS、Prefect)不在覆盖范围内。

Google ADK ​

python
from preworld_guard.google_adk import GuardPlugin
app = App(name="support", root_agent=agent, plugins=[*your_plugins, GuardPlugin(guard)])
  • Agent 级的 before_tool_callback 在插件之后运行,还能改参数。设 verify_arguments=True:Guard 判定之后参数又被改过的调用直接拒绝。
  • live 和双向流式运行不触发插件的工具回调,这类运行不受保护。模型侧的内置工具(比如 Gemini 的 google_search)也不受保护。

Microsoft Agent Framework ​

python
from preworld_guard.agent_framework import GuardFunctionMiddleware
agent = Agent(client=chat_client, tools=[transfer], middleware=[*your_middleware, GuardFunctionMiddleware(guard)])
await agent.run("…", function_invocation_kwargs={"subject_id": user_id})
  • 放在 Agent 级列表的最后。它里层的中间件之后再改参数,框架会拒绝执行。
  • Guard 无法判定时抛出 MiddlewareFailure,运行中止。
  • 不覆盖:模型厂商执行的工具,以及直接调用的 FunctionTool.invoke。

LlamaIndex ​

python
from preworld_guard.llama_index import guard_tools
agent = FunctionAgent(tools=guard_tools([search, transfer], guard), llm=llm)
with guard_run(subject_id=user_id):
    response = await agent.run(user_msg="…")
  • LlamaIndex 的 Agent 把所有工具异常都转成错误结果,所以 Guard 无法判定时也没法中止运行。工具同样不执行,模型收到一个错误结果。
  • CodeActAgent 生成的代码直接调用函数,不受保护。

Agno ​

python
from preworld_guard.agno import GuardToolHook
agent = Agent(model=model, tools=[transfer], tool_hooks=[GuardToolHook(guard, subject_from_user_id=True), *your_hooks])
agent.run("…", user_id=user_id)
  • Guard 从调用本身读取参数,并按 Agno 的方式校验,所以放在 tool_hooks 的哪个位置都行。
  • 开了 cache_results=True 的工具一律拒绝(GUARD_TOOL_CACHED):Agno 的缓存在用户之间共享。
  • Guard 无法判定时抛出 StopAgentRun。运行状态仍是 completed,要看 RunOutput.tools 里的 tool_call_error。
  • external_execution=True 的工具不经过钩子,要在你们执行它的地方另行保护。

DSPy ​

python
from preworld_guard.dspy import execute_tool_calls, guard_tools
tools = guard_tools([search, transfer], guard)
react = dspy.ReAct("question -> answer", tools=tools)
with guard_run(subject_id=user_id):
    prediction = react(question="…")
    results = execute_tool_calls(other_prediction.tool_calls, tools)  # 原生 tool calling
  • 不传 functions= 的 ToolCall.execute() 会在你们的全局变量里按名字找函数,执行的是原函数。要么传 functions=tools,要么用 execute_tool_calls:它拒绝一切没有受保护的名字(TOOL_NOT_GUARDED)。
  • DSPy 的线程池(Parallel、batch、Evaluate、优化器)不传递 guard_run,要在每个工作线程执行的函数里进入它。优化器编译时用测试替身,不要用有副作用的工具。

CrewAI ​

python
from preworld_guard.crewai import guard_tools
clerk = Agent(role="Clerk", goal="…", backstory="…", tools=guard_tools([search, transfer], guard))
with guard_run(subject_id=user_id):
    result = Crew(agents=[clerk], tasks=[task]).kickoff()
  • Guard 无法判定时返回 ToolFailure。除非设 tool_failure_policy="raise",运行会继续。
  • guard_tool_call_hook(guard) 是可选的进程级兜底钩子,覆盖 CrewAI 自己加给 Agent 的工具(代码执行、mcps=、apps=、委派)。要最后注册。它从不恢复审批,也不记录 started/completed。用它时设 Crew(cache=False)。

Vercel AI SDK(TypeScript) ​

ts
import { GuardClient, guardRun } from "@preworld/guard";
import { guardTools } from "@preworld/guard/ai-sdk";

const guard = new GuardClient({ endpoint: "https://guard.example.com", token: process.env.PREWORLD_GUARD_TOKEN!,
  projectId: "prj_...", agentId: "support-agent", backgroundEvents: true });
await guard.start();
const { tools, toolApproval } = guardTools({ lookup, transfer }, guard);
const result = await guardRun({ subjectId: user.id, sessionId: chat.id }, () =>
  generateText({ model, tools, toolApproval, messages }));

Guard 在每个工具的 execute 处判定。toolApproval 只回答 AI SDK「要不要先审批」的问题。见 TypeScript SDK。

各框架里的判定结果 ​

Guard 放行时,每个适配器都在工具执行前记录 started,执行后记录 completed。

框架拒绝需审批降级Guard 无法判定
LangChain、LangGraph错误 ToolMessage,内容是 JSON同拒绝,带票据ToolMessage,内容是替代工具的结果抛出 GuardUnavailable,运行中止;设 on_guard_error="deny" 时改为错误消息
Claude Agent SDK钩子返回 deny,原因是规则的说明deny,原因是带票据的 JSONdeny,fallback_resource 指出替代工具deny,GUARD_UNAVAILABLE
OpenAI Agents(默认)工具结果是 JSON,运行继续同拒绝,带票据替代工具的结果抛出 GuardUnavailable,运行中止
OpenAI Agents,on_deny="raise"抛出 GuardDenied,运行中止抛出 GuardApprovalRequired,运行中止替代工具的结果同上
Pydantic AIToolFailed原生延后(ApprovalRequired)SkipToolExecution,用替代工具的结果抛出异常,运行中止
Google ADK跳过工具,模型收到 JSON 作为函数响应同拒绝,带票据{"result": ..., "preworld_guard": ...}抛出异常;设 on_guard_error="deny" 时返回 GUARD_* 内容
Microsoft Agent Framework函数结果是 JSON同拒绝,带票据替代工具的结果抛出 MiddlewareFailure,运行中止
LlamaIndexToolOutput(is_error=True),内容是 JSON同拒绝,带票据替代工具的结果错误 ToolOutput,运行继续
Agno工具结果是 JSON同拒绝,带票据替代工具的结果抛出 StopAgentRun
DSPyJSON 作为 observation同拒绝,带票据替代工具的结果返回 GUARD_* JSON,运行继续
CrewAI工具结果是 JSON同拒绝,带票据替代工具的结果ToolFailure;只有 tool_failure_policy="raise" 时中止

每一行里,Guard 无法判定时工具都不执行。

模型看到什么 ​

拒绝、需审批、降级时,模型收到的 JSON 字段和 MCP 代理返回的一样:

字段含义
statusdenied、approval_required 或 degraded
reason_code规则的原因码,或者 APPROVAL_NOT_CONSUMABLE、FALLBACK_UNAVAILABLE、GUARD_UNAVAILABLE 等
message给人看的一句说明
policy_version做出判定的策略版本;Guard 无法判定时没有这个字段
ticket_id、expires_at、approval_status只在需审批时出现
fallback_resource只在降级时出现
json
{"status": "approval_required", "reason_code": "…", "message": "…", "policy_version": 12,
 "ticket_id": "…", "expires_at": "…", "approval_status": "pending"}

里面从不包含原始参数。

身份 ​

  • 可信主体(以及 tenant_id、destination、data_labels)只来自你们的应用:适配器的 resolve,或者 guard_run(...)。模型写出的参数和框架自动生成的 ID 都不会被当作身份。
  • 任务、会话、追踪 ID 依次取自:resolve、guard_run、框架自己的 ID、SDK 新生成的 ID。
  • resolve 和 guard_run 给出的主体不一致时,按无法判定处理(GUARD_SUBJECT_MISMATCH)。resolve 抛出异常时也一样(GUARD_IDENTITY_UNAVAILABLE)。
框架resolve 收到什么
LangChain、LangGraphruntime.context
Claude Agent SDK钩子的 context(一般改用 guard_run)
OpenAI Agents传给 Runner.run(...) 的 context
Pydantic AIctx.deps
Google ADKtool_context.state;设 subject_from_user_id=True 时用会话的 user_id
Microsoft Agent FrameworkFunctionInvocationContext;默认读 function_invocation_kwargs
LlamaIndex、DSPy、CrewAI没有 resolve:用 guard_run(...) 包住这次运行
AgnoRunContext(从 dependencies 取,不要用 session_state);设 subject_from_user_id=True 时用 user_id

审批 ​

  1. 命中需审批规则时,适配器申请一张票据,工具不执行。同一动作重试,拿到的是同一张票据。
  2. 没有可信主体的调用直接拒绝(APPROVAL_SUBJECT_REQUIRED)。
  3. 审核员批准后,在 with guard_resume(ticket_id): 里再运行一次 Agent。模型再次提出同一个调用时,票据被消费一次,工具按批准时的参数执行。
  4. Pydantic AI 默认用自己的延后机制:用 DeferredToolResults 把这次调用标为已批准,再继续运行。能不能执行仍以 Guard 的票据为准,只在你们的应用里批准不算数。

票据在哪里:

框架票据的位置
LangChain、LangGraph错误 ToolMessage 的内容和 artifact
Claude Agent SDK拒绝原因
OpenAI Agents、Agno、CrewAI工具结果(OpenAI Agents 的 raise 模式下是 GuardApprovalRequired.ticket_id)
Pydantic AIDeferredToolRequests.metadata 或 ToolFailed
Google ADK、Microsoft Agent Framework函数响应或函数结果
LlamaIndexToolOutput
DSPyobservation

见动作审批与降级。