Agent 的 POC 阶段很容易:一个 while 循环,几次工具调用,接上大模型就"能用"了。但从 POC 到企业级生产,中间横着一道结构性鸿沟。企业环境要求的是:多租户隔离、会话可恢复、工具可审计、故障可定位、版本可回滚。这些不是"加个日志"能解决的,而是需要在架构层面重新分层。
企业级 Agent 架构的典型失败模式有三种:把编排逻辑写死在 prompt 里(无法测试、无法回滚);把工具调用直接暴露给模型(权限失控、无审计);把会话状态存在进程内存里(重启即丢失、无法水平扩展)。本文讨论如何用分层架构解决这三类问题,并给出可运行的核心骨架。
专业的企业级 Agent 平台通常分四层,层间通过明确契约通信:
关键设计原则:编排层不做 IO,能力层不做决策。编排层只描述"要调用什么、传什么参数",具体执行、重试、超时、审计都在能力层完成。这条边界一旦模糊,系统就会变成一坨无法测试的泥巴。
企业级 Agent 最需要的不是"更聪明",而是"可预测"。把 Agent 的执行建模为有向状态机,每个节点是一次 LLM 决策或工具调用,每条边是一次状态转移。这样每一步都可以持久化、可重放、可中断恢复。
# orchestrator/state_machine.py
from __future__ import annotations
import json, uuid, time
from dataclasses import dataclass, field, asdict
from enum import Enum
from typing import Any, Awaitable, Callable
class Node(str, Enum):
PLAN = "plan"
TOOL = "tool"
SYNTHESIZE = "synthesize"
DONE = "done"
FAILED = "failed"
@dataclass
class AgentState:
run_id: str
node: Node = Node.PLAN
step: int = 0
max_steps: int = 24
scratchpad: list[dict] = field(default_factory=list)
pending_tool: dict | None = None
result: str | None = None
error: str | None = None
class StateStore:
"""状态存储:生产环境用 Redis/Postgres,这里以内存示意接口"""
def __init__(self): self._db: dict[str, str] = {}
async def save(self, s: AgentState) -> None:
self._db[s.run_id] = json.dumps(asdict(s), default=str)
async def load(self, run_id: str) -> AgentState:
d = json.loads(self._db[run_id])
d["node"] = Node(d["node"])
return AgentState(**d)
class Orchestrator:
def __init__(self, store: StateStore,
planner: Callable[[AgentState], Awaitable[dict]],
executor: Callable[[str, dict], Awaitable[Any]],
synthesizer: Callable[[AgentState], Awaitable[str]]):
self.store, self.planner = store, planner
self.executor, self.synthesizer = executor, synthesizer
async def run(self, state: AgentState) -> AgentState:
while state.node not in (Node.DONE, Node.FAILED):
if state.step >= state.max_steps:
state.node, state.error = Node.FAILED, "max_steps_exceeded"
break
state.step += 1
try:
if state.node is Node.PLAN:
decision = await self.planner(state)
if decision["type"] == "tool":
state.pending_tool = decision
state.node = Node.TOOL
else:
state.node = Node.SYNTHESIZE
elif state.node is Node.TOOL:
name, args = state.pending_tool["name"], state.pending_tool["args"]
obs = await self.executor(name, args)
state.scratchpad.append({"step": state.step, "tool": name,
"args": args, "obs": obs})
state.pending_tool, state.node = None, Node.PLAN
elif state.node is Node.SYNTHESIZE:
state.result, state.node = await self.synthesizer(state), Node.DONE
except Exception as e: # 单步失败不吞掉整体
state.scratchpad.append({"step": state.step, "error": repr(e)})
state.node = Node.PLAN if state.step < 3 else Node.FAILED
if state.node is Node.FAILED:
state.error = repr(e)
await self.store.save(state) # 每步持久化,支持断点恢复
return state这个骨架的工程价值在于三点:每步落盘(崩溃可恢复)、步数上限(防止无限循环烧钱)、单步错误可容忍(前几步失败可重试,超过阈值才终止)。它不追求"聪明",追求"可运营"。
工具是 Agent 与真实世界交互的唯一通道,因此必须声明式注册、统一执行、集中审计。企业里常见的反模式是把 requests.get 直接暴露给模型——没有超时、没有白名单、没有脱敏。
# capabilities/registry.py
from __future__ import annotations
import asyncio, time, hashlib
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
@dataclass
class ToolSpec:
name: str
description: str
schema: dict
handler: Callable[[dict], Awaitable[Any]]
timeout_s: float = 15.0
scopes: tuple[str, ...] = () # 所需权限域,供策略引擎校验
idempotent: bool = False
class ToolRegistry:
def __init__(self): self._tools: dict[str, ToolSpec] = {}
def register(self, spec: ToolSpec) -> None:
if spec.name in self._tools: raise ValueError(f"duplicate tool {spec.name}")
self._tools[spec.name] = spec
def specs_for_llm(self, granted: set[str]) -> list[dict]:
"""只把当前主体有权限的工具暴露给模型 —— 减少幻觉与越权"""
return [{"name": s.name, "description": s.description, "parameters": s.schema}
for s in self._tools.values() if set(s.scopes) <= granted]
async def invoke(self, name: str, args: dict, granted: set[str],
audit: Callable[[dict], None]) -> Any:
spec = self._tools.get(name)
if not spec: raise KeyError(f"unknown tool {name}")
if not set(spec.scopes) <= granted: raise PermissionError(f"scope denied: {name}")
started = time.time()
try:
result = await asyncio.wait_for(spec.handler(args), timeout=spec.timeout_s)
status = "ok"
except asyncio.TimeoutError:
result, status = None, "timeout"
finally:
audit({"tool": name, "args_hash": hashlib.sha256(
repr(sorted(args.items())).encode()).hexdigest()[:16],
"latency_ms": int((time.time() - started) * 1000),
"status": status})
if status == "timeout": raise TimeoutError(f"{name} timeout")
return result注意 specs_for_llm(granted) 这个设计:按权限动态裁剪工具列表,而不是把所有工具都给模型再在调用时拦截。前者从源头降低越权概率,后者只是事后报错。
企业级 Agent 的排障不是看日志,而是看执行树。每次 run 是一个 trace,每个 step 是一个 span,工具调用是子 span。这样"为什么这次回答不对"可以精确归因到某一步的输入输出。
# observability/tracing.py
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer("agent.runtime")
async def traced_step(run_id: str, step: int, node: str, fn):
with tracer.start_as_current_span(f"agent.step.{node}") as span:
span.set_attributes({"run.id": run_id, "step": step, "node": node})
try:
out = await fn()
span.set_status(Status(StatusCode.OK))
return out
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
raise配套的硬性要求:prompt 版本号、模型版本号、工具版本号必须写进 span attribute。否则"上周还好好的,这周就不行了"这类问题永远查不清——你不知道是换了模型、改了 prompt,还是上游工具改了返回格式。
企业级 Agent 与 Demo 的区别不在模型,而在骨架:显式状态机保证可恢复,工具注册表保证可治理,trace 保证可归因。把这三样做扎实,再往上加能力才是有意义的。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。