用于构建多智能体系统的智能体架构模式——面向生产就绪的系统级模式

0 阅读35分钟

在前面的章节中,我们对 agentic AI 的构建模块进行了细致的审视与组装。我们为单个智能体设计了记忆与推理能力,让它们能够在复杂任务上协同,并为将其架构为既健壮又可问责的系统所固有的挑战提供了解决方案。换句话说,我们已经为设计与构建高度有能力、具备智能的 agent actor 铺平了道路。现在,我们必须构建它们将要“生活”和“运作”的上下文世界。

正如我们现在所知道的,多智能体系统不仅仅是智能体的集合。在很多方面,它映射了现代微服务架构,但有一个关键区别:它的组件不是执行固定代码的静态服务,而是具备推理能力、以目标为导向并能自主行动的智能体。为了有效协作并驱动一个企业级应用,这种分布式智能需要一整套编排单元(orchestration)、策略遵循(policy adherence)与共享基础设施。现实要求我们把关注点从“智能体本身”转向“包含智能体在内的整体系统架构”。因此,在本章中,我们将介绍系统级模式(system-level patterns) ,它们为生产级多智能体系统提供架构脚手架(architectural scaffolding)。这些模式解决任何企业应用都不可妥协的要求,回答如下关键问题:

  • 服务与智能体如何动态发现彼此?
  • 我们如何为自治智能体强制执行安全、身份与访问控制?
  • 我们如何实时监控并强制执行合规规则?
  • 系统如何以异步方式并在规模化场景下响应外部事件?

为了让这些模式尽可能可落地,我们将采用 system-first 的方法。基于第 4 章的 agent-level 架构,我们把焦点从智能体的内部工作机制转向它所栖居的外部生态。在展开每个具体模式之前,我们会优先“架构先于实现”,先呈现一份战略指南。该指南与我们的 GenAI Maturity Model 对齐,提供一条路线图:随着系统从单智能体演进到协作生态,这些架构模式为何会变得至关重要。

先理解全局图景,你就能带着上下文去把握每个具体模式的位置,以及它为何是把 agentic PoC 转化为可靠、安全、健壮的生产环境所必不可少的。

本章将覆盖以下主题:

  • Strategic guide to implementing system-level patterns
  • Tool and Agent Registry
  • Real-Time Compliance Monitoring
  • Agent Authentication and Authorization
  • Event-Driven Reactivity

Strategic guide to implementing system-level patterns

理解单个架构模式,是构建健壮 agentic 系统的第一步。下一步、更关键的一步,是战略性地应用它们,以创建安全、可扩展、并满足企业要求的基础设施。对于 day-one 的 PoC,没有必要、也不建议一次性实现所有这些模式。正确做法是:随着系统复杂度、风险画像(risk profile)与规模需求的增长,渐进式采用它们。

Mapping system-level patterns to the GenAI maturity model

面对这些基础模式,一个常见问题是:我一开始需要做到多少? 答案完全取决于你在 agentic AI 旅程中的位置。为一个单一、非关键智能体实现高可用工具注册中心属于过度工程;相反,在缺乏健壮认证与合规能力的情况下部署处理敏感数据的多智能体系统,则是疏忽(negligent)。

我们将借助 GenAI maturity model 为这段旅程提供战略路线图。它帮助你把这些架构模式的实现与系统的当前能力和未来雄心对齐,确保你在正确的时间打下正确的基础。

LevelCapabilitiesEnabled patternsSummary
Level 3 – Agent-ready LLMsFoundational models and toolsInitial thoughts on security and reactivity: basic IAM (service accounts) and simple reactivity (webhooks)在部署任何智能体之前,关于安全(IAM 集成)与通信(事件基础设施)的基础决策,就应纳入平台设计。
Level 4 – Single-agent systemsProduction-grade single agentsAgent Authentication and Authorization, Event-Driven Reactivity, and Real-Time Compliance Monitoring当第一个智能体进入生产环境,安全不容谈判。智能体必须能对环境具备反应性(reactive),并且如果它处理敏感任务,合规监控就成为必需。
Level 5 – Multi-agent systemsCollaborative agent ecosystemsTool and Agent Registry一旦两个或更多智能体需要动态协作,Registry 就成为架构基石,支持全系统范围的发现(discovery)与松耦合(loose coupling)。

Table 10.1 – Mapping system-level patterns to the GenAI Maturity Model

这个 Maturity Model 提供了 when:采用顺序与演进路径的指南。为了有效实现这些模式,我们还需要理解 where:它们如何嵌入生产级系统的不同功能层。

System integration architecture: a blueprint for production readiness

该架构展示了系统级模式如何构成完整 agentic 应用的运行骨干(operational backbone)。这些组件不属于任何单个智能体,而是为所有智能体提供安全、高效运作的环境:

  • API gateway(安全与入口) :所有进入 agentic 系统请求的单一、加固入口点。
    Patterns enabled:Agent Authentication and Authorization。检查签名、过期时间、audience claims 与 scopes,并强制执行 token rotation,以确保安全、最小权限(least-privilege)的 agent-to-agent 通信。
  • Message bus / event stream(反应性骨干) :用于异步通信的中枢神经系统。
    Patterns enabled:Event-Driven Reactivity。智能体通常以持续消费者(continuous consumers)或长连接流(long-lived stream connections)方式感知事件。当订阅 topic 上出现新事件时,会触发智能体的 Sense 组件,立即启动其推理循环。这使系统无需直接耦合即可对变化做出响应。
  • Central registry(发现与目录) :系统的“黄页”,用于动态发现。
    Patterns enabled:Tool and Agent Registry。所有可发现的智能体与工具在此注册其能力与端点。
  • Governance services(监督与合规) :专门用于观察与治理智能体行为的层。
    Patterns enabled:Real-time Compliance Monitoring。合规服务或合规智能体订阅 message bus,或作为网关拦截并对动作进行裁决,将行为与中心策略引擎对照。为满足企业标准,该层在 action-level(例如 approve loan)、row-level(特定记录)与 field-level(例如阻断 PII/PHI)强制约束,确保任何操作执行前完成细粒度合规。

为了可视化这些组件如何形成一个一致系统,下图展示了该生产就绪蓝图:外部请求如何穿过安全边界进入应用环境,以及智能体如何与核心基础设施服务交互,从而实现发现、通信与治理。

image.png

Figure 10.1 – A system integration architecture showing how system-level patterns provide the foundational infrastructure for agentic applications

这份架构蓝图展示了系统组件之间的关系。为了让它“动起来”,下面的示例会从头到尾追踪一个业务事件,演示这些模式在真实序列中如何链式协作。

Pattern chaining in practice: an automated supply chain example

为了看清这些模式如何连接,我们走一遍自动化供应链管理场景。该示例展示架构模式如何协同工作,以安全、规模化方式处理外部事件:

  1. Event-Driven Reactivity:来自外部物流伙伴 webhook 的消息被发布到系统 message bus 上的 shipping_events topic。该事件表示一个集装箱已到港。
  2. Event-Driven Reactivity:一个 InventoryAgent 订阅该 topic。新消息触发它行动。其目标是核验集装箱内容并更新库存。
  3. Agent Authentication and Authorization:为了获取集装箱清单(manifest),InventoryAgent 需要访问 ShippingAPI。它首先使用其 service account 凭证向 IAM 系统请求 access token。
  4. Agent Authentication and AuthorizationInventoryAgent 携带 token 调用 ShippingAPI。API gateway 拦截调用,校验 token,并确认该智能体具备 read:manifest 权限。
  5. Tool and Agent Registry:处理完 manifest 后,InventoryAgent 判定需要通知财务部门。它查询 Tool and Agent Registry 去“寻找一个能处理海关付款(customs payments)的智能体”。Registry 返回 CustomsPaymentAgent 的端点。
  6. Real-Time Compliance MonitoringInventoryAgentCustomsPaymentAgent 发送发起付款请求。ComplianceMonitor 从 message bus 拦截该事件,依据策略引擎检查付款金额并验证供应商在批准清单内,同时记录一条已完成合规检查的事件日志。
  7. CustomsPaymentAgent 接收已验证的请求并安全完成任务。

Resiliency in action: handling a failure path

为展示系统韧性,考虑在步骤 4 中 InventoryAgent 的 access token 过期:

  • FailureShippingAPI401 Unauthorized 拒绝请求。
  • Recovery:智能体内部逻辑不会崩溃,而是捕获该特定错误码,自动向 IAM 系统重新认证,获取新 token,并重试对 ShippingAPI 的请求。
  • Result:工作流自动恢复,展示系统级安全模式如何与 agent-level 的鲁棒性模式配合,处理常见中断。

下面的时序图可视化了整个工作流,展示不同智能体与基础设施服务之间的交接与交互,它们如何协作处理该事件。

image.png

Figure 10.2 – A sequence diagram showing how system-level patterns chain together in an automated supply chain workflow

该供应链示例展示了这些架构模式如何互锁,形成强大的自动化工作流。然而,构建这样的系统不可能一蹴而就。为弥合理论与成功企业落地之间的鸿沟,分阶段方法必不可少。下一节将提供一个实用的 rollout 顺序指南,帮助你以增量方式实现这些模式。

Guidance for enterprise rollout

采用这些架构模式需要有意为之、分阶段推进。与 maturity model 对齐的实施能确保你在增加复杂性之前,先建立稳定、安全的基础。

PhasePatterns to implementRationale
Phase 1: Secure the foundationAgent Authentication and Authorization对第一个生产智能体(Level 4)而言,安全至关重要。从 day one 起与企业 IAM 系统集成。把智能体当作一等公民的服务身份(first-class service identity)。
Phase 2: Enable reactivity and oversightEvent-Driven Reactivity and Real-Time Compliance Monitoring当系统承担更关键任务时,用 event bus 解耦组件以获得可扩展性。对涉及敏感数据、PII 或金融交易的任何工作流,引入合规监控。
Phase 3: Scale the ecosystemTool and Agent Registry当你准备迈向真正的多智能体系统(Level 5),Registry 是管理复杂度与支持智能体间动态协作的必需组件。

Table 10.2 – A phased rollout for system-level patterns

在确立了战略路线图与定义成功的性能指标之后,我们已经从 system-level 架构的“why”和“需要多少”,推进到了实践层面的“how”。接下来我们将深入每个模式的详细实现,从支撑真正动态、解耦生态的基础组件开始:Tool and Agent Registry

Tool and Agent Registry

随着 agentic 生态的增长,专用智能体与可用工具的数量可能会快速膨胀。那种静态、硬编码的做法——让智能体在设计时就预先“知道”彼此的函数——会变得脆弱且几乎无法维护。Tool and Agent Registry 模式为服务发现(service discovery)提供了一种动态且可扩展的解决方案。

Context

该模式是任何多智能体(multi-agent)或工具密集型(tool-heavy)系统的基础前提,尤其当你希望促进松耦合(loose coupling)并允许系统持续演进时更是如此。它是让智能体能够动态发现并利用在设计时并未被显式编程知晓的能力的关键基础设施。

Problem

在一个规模大、持续演进的系统中(新工具与新智能体不断加入),智能体如何找到完成任务所需的正确工具或具备所需能力(以及工具)的另一个智能体

Solution

解决方案是实现一个中心化 Registry——一个充当系统能力“黄页”(yellow pages)的服务:

  • Registration(注册) :当一个新工具或新智能体被部署时,它向 Registry 注册自身。它提供关于能力的元数据,例如函数名(如 get_supplier_quote)、对能力的自然语言描述、输入/输出 schema,以及网络端点(endpoint)。
  • Discovery(发现) :当某个智能体需要某种能力时,它查询 Registry,而不是使用硬编码调用。它既可以按名字检索,也可以更强大地按语义检索(例如:Find a tool that can book a flight)。
  • Invocation(调用) :Registry 返回一组匹配的服务及其端点。发起请求的智能体随后使用这些信息直接调用对应服务。

该模式实质上把“对某种能力的认知”与“该能力的具体实现”解耦开来。

下图展示了动态发现过程:智能体查询中心 Registry 以寻找某个工具,获得必要信息,然后直接调用该工具。

image.png

Figure 10.3 – The Tool and Agent Registry pattern decouples the agent from the tool implementation

Example: A dynamic procurement system

一个 ProcurementAgent 需要为某个特定零件获取报价。公司有多种实现方式,包括面向优选供应商的内部 API,以及用于公共网站的网页抓取工具:

  • RegistrationPreferredVendorAPIToolWebScrapingQuoteTool 都向 Tool Registry 注册自己,并且都宣告提供 get_quote 能力。
  • DiscoveryProcurementAgent 接到任务:Get the best price for Part #XYZ. 它让其 LLM 生成计划,其中包含获取报价的步骤。随后智能体查询 Registry:Find all tools with the get_quote capability.
  • Invocation:Registry 返回两个工具的端点。智能体的推理逻辑决定并行调用二者以找到最佳价格。它依据 Registry 提供的 schema 为每个工具格式化请求并执行调用。

如果下个月新增一个 InternationalVendorAPIToolProcurementAgent 无需任何改动。只要新工具完成注册,智能体就会自动发现并使用它。

Example implementation

下面是一段简化的 Python 实现,用于演示动态工具 Registry 的核心逻辑。该例展示了工具如何被注册,以及智能体如何基于能力发现这些工具:

# --- 1. Define the Central Tool Registry ---
class ToolRegistry:
    def __init__(self):
        # The registry stores tools indexed by their capability
        self.registry = {}

    def register_tool(
        self, tool_name: str, capability: str, endpoint: object,
        schema: dict
    ):
        """Registers a new tool's capability and how to call it."""
        if capability not in self.registry:
            self.registry[capability] = []

        tool_info = {
            "name": tool_name,
            "endpoint": endpoint,
            "schema": schema
        }
        self.registry[capability].append(tool_info)
        print(f"REGISTRY: Registered '{tool_name}' with capability '{capability}'.")

    def discover_tools(self, capability: str) -> list:
        """Finds all tools that match a given capability."""
        print(f"REGISTRY: Discovery query for capability '{capability}'.")
        return self.registry.get(capability, [])

# --- 2. Define Mock Tools (as functions) ---
def preferred_vendor_api(part_id: str) -> dict:
    """Internal API for preferred vendors."""
    print(f"   -> TOOL (PreferredVendor): Getting quote for {part_id}...")
    return {"source": "PreferredVendorAPI", "price": 95.00}

def web_scraping_quote_tool(part_id: str) -> dict:
    """Scraping tool for public sites."""
    print(f"   -> TOOL (WebScraper): Getting quote for {part_id}...")
    return {"source": "WebScraper", "price": 98.50}

# --- 3. Setup and Registration ---
# Initialize the central registry
GLOBAL_REGISTRY = ToolRegistry()

# Register the tools
GLOBAL_REGISTRY.register_tool(
    tool_name="PreferredVendorAPITool",
    capability="get_quote",
    endpoint=preferred_vendor_api,
    schema={"part_id": "string"}
)

GLOBAL_REGISTRY.register_tool(
    tool_name="WebScrapingQuoteTool",
    capability="get_quote",
    endpoint=web_scraping_quote_tool,
    schema={"part_id": "string"}
)

# --- 4. Agent Implementation ---
class ProcurementAgent:
    def __init__(self, registry: ToolRegistry):
        self.registry = registry

    def get_best_price(self, part_id: str):
        print(f"\nAGENT: Received task to get best price for {part_id}.")

        # 2. Discovery: Agent queries the registry, not its own code
        capability_to_find = "get_quote"
        found_tools = self.registry.discover_tools(capability_to_find)

        if not found_tools:
            return f"Error: No tools found with capability '{capability_to_find}'."

        print(f"AGENT: Discovered {len(found_tools)} tools. Invoking all...")

        # 3. Invocation: Agent calls the discovered tools
        results = []
        for tool in found_tools:
            # Assumes all tools for 'get_quote' have the same schema
            tool_function = tool["endpoint"]
            result = tool_function(part_id=part_id)
            results.append(result)

        # Agent's reasoning logic to find the best price
        best_quote = min(results, key=lambda x: x["price"])
        print(f"AGENT: Best price found: {best_quote}")
        return best_quote

# --- Execute the Workflow ---
procurement_agent = ProcurementAgent(registry=GLOBAL_REGISTRY)
procurement_agent.get_best_price("Part #XYZ")

Consequences

Pros:

  • Modularity and scalability(模块化与可扩展性) :它推动形成高度模块化、可扩展的架构。可以在不修改任何现有智能体代码的情况下,为系统新增能力。
  • Resilience(韧性) :如果某个特定工具或智能体实例宕机,Registry 可以提供替代项,使系统能够绕开故障进行路由。

Cons:

  • Single point of failure(单点故障) :Registry 本身可能成为单点故障,必须以高可用与高韧性方式设计。
  • Overhead(额外开销) :它为发现(discovery)增加了一次额外的网络跳转(network hop),会引入少量延迟;同时 Registry 也需要持续维护。

Implementation guidance

对于简单场景,共享数据库甚至维护良好的 JSON 文件都可以充当 Registry。对于企业系统,更健壮的选择是使用专门的服务发现工具,例如 Consuletcd。成功 Registry 的关键在于:用于描述能力的元数据 schema 必须定义良好且信息丰富。

既然我们已经建立了让智能体动态找到所需能力的机制,就必须处理另一个关键关切:确保它们的动作是安全且被允许的。下一个模式将为治理(governance)提供一个框架。

Real-Time Compliance Monitoring

在金融、医疗、法律等受监管行业中,agentic 系统不能是“黑盒”。它们的行为必须可审计,并严格遵守外部法规与内部政策。Real-Time Compliance Monitoring(实时合规监控)模式提供了一种持续、自动化治理的机制。

Context

该模式对于任何满足以下条件的 agentic 系统都至关重要:处理敏感数据、执行高风险交易,或运行在受 GDPRHIPAA 或金融合规规则等法规约束的领域中。

Problem

系统如何确保自主智能体的行动能够持续遵循一套复杂且动态变化的规则,并在违规发生之前就阻止它,而不仅仅是事后检测?

Solution

解决方案是实现一个专用的、系统级的合规监控器(compliance monitor),它可以是另一个专门的智能体,也可以是一个专用的策略引擎服务。该监控器充当治理层(governance layer):

  • Centralized policy engine(中心化策略引擎) :使用策略引擎(例如 Open Policy Agent, OPA)以机器可读的格式定义所有规则与法规。
  • Event interception(事件拦截) :监控器订阅系统级事件总线(event bus),或作为关键动作的网关。它检查每一个重要事件(例如:智能体请求数据、或与外部方通信)。
  • Real-time adjudication(实时裁决) :对每个事件,监控器查询策略引擎,以验证超出标准授权(authorization)范围的、具备上下文感知的约束。AuthZ 判断智能体是否“可以”访问某资源(permission),而合规监控判断其在当前状态下是否“应该”被允许(例如:Agent X 有读取记录的权限,但针对这一次特定的研究目的,它是否具备有效的用户同意?)。
  • Enforcement(执行/强制) :若动作合规,则允许继续;若违反策略,监控器阻断动作、记录合规违规事件,并可触发对人类主管的告警。

下图展示了合规智能体/监控器如何拦截一个动作:它在允许或拒绝之前,将该动作与中心化策略引擎比对,从而确保所有动作都遵守预定义规则。

image.png

Figure 10.4 – The Real-Time Compliance Monitoring pattern intercepts actions for policy adjudication

Example: A HIPAA-compliant healthcare agent

一个智能体 ResearchQueryAgent 负责为临床研究查找符合某些条件的病人记录:

  • The action(动作) :智能体尝试访问病人数据库中的 Patient #12345

  • Interception(拦截)HIPAAComplianceAgent 拦截该数据访问请求。

  • Adjudication(裁决) :它携带请求上下文查询策略引擎:

    • Rule(规则) :只有当“临床研究(clinical research)”的明确且可审计同意(consent)在案时,才可访问病人记录。
    • Check(检查) :合规智能体查询同意数据库后发现,Patient #12345 仅同意将数据用于“账单用途(billing purposes)”。
  • Enforcement(执行) :策略引擎返回 DENY。随后 HIPAAComplianceAgent 阻断数据库查询,从而避免 HIPAA 违规。它记录该次拒绝访问并发出告警以供复核。

Example implementation

下面的示例实现基于上述 HIPAA 医疗智能体案例,模拟中心监控器如何拦截智能体动作、对照策略引擎检查,并在违反规则时阻断动作:

# --- Mock Database / Services ---
# Mock database of patient consent records
PATIENT_CONSENT_DB = {
    "Patient-12345": ["billing"],
    "Patient-67890": ["billing", "clinical_research"]
}

# Mock policy engine (can be a simple function or a dedicated service)
def policy_engine_adjudicate(
    action: str, resource_id: str, consent_types: list
) -> bool:
    """
    Checks if an action is compliant.
    Returns True for 'ALLOW' and False for 'DENY'.
    """
    if action == "access_patient_record_for_research":
        # Rule: Must have 'clinical_research' consent
        return "clinical_research" in consent_types
    return False # Default deny

# --- Agent and Monitor Implementation ---
class HIPAAComplianceMonitor:
    """
    Acts as the compliance agent/monitor.
    It intercepts actions and checks them against the policy engine.
    """
    def __init__(self, consent_db):
        self.consent_db = consent_db

    def intercept_and_adjudicate(
        self, agent_name: str, action: str, patient_id: str
    ) -> dict:
        """
        Intercepts an agent's action, checks policy, and enforces a decision.
        """
        print(f"MONITOR: Intercepted action '{action}' from '{agent_name}' for '{patient_id}'.")

        # 1. Get relevant context (patient's consent)
        patient_consent = self.consent_db.get(patient_id, [])
        print(f"MONITOR: Found consent for '{patient_id}': {patient_consent}")

        # 2. Adjudication: Ask the policy engine for a decision
        is_allowed = policy_engine_adjudicate(
            action, patient_id, patient_consent)

        # 3. Enforcement
        if is_allowed:
            print(f"MONITOR: Action ALLOWED.")
            return {"status": "ALLOW"}
        else:
            print(f"MONITOR: Action DENIED. (Reason: Missing required consent 'clinical_research')")
            # In a real system, this logs a formal compliance breach alert
            return {"status": "DENY",
                    "reason": "Missing required consent 'clinical_research'"}

class ResearchQueryAgent:
    """
    The agent performing the work. It must send its actions
    through the compliance monitor.
    """
    def __init__(self, monitor: HIPAAComplianceMonitor):
        self.monitor = monitor

    def access_patient_data(self, patient_id: str):
        print(f"\nAGENT (ResearchQueryAgent): Attempting to access data for '{patient_id}'...")

        action_to_perform = "access_patient_record_for_research"
        # Send action to the monitor for approval *before* execution
        decision = self.monitor.intercept_and_adjudicate(
            agent_name="ResearchQueryAgent",
            action=action_to_perform,
            patient_id=patient_id
        )

        # Only proceed if the action was allowed
        if decision["status"] == "ALLOW":
            print(f"AGENT: Access granted. Fetching data for {patient_id}...")
            # ... database.query(patient_id) ...
            return f"Successfully retrieved data for {patient_id}."
        else:
            print(f"AGENT: Access denied. Aborting task.")
            return f"Error: Could not access data for {patient_id}. Reason: {decision['reason']}"

# --- Execute the Workflow ---
# 1. Initialize the monitor with the consent database
compliance_monitor = HIPAAComplianceMonitor(consent_db=PATIENT_CONSENT_DB)

# 2. Initialize the agent and pass it the monitor
research_agent = ResearchQueryAgent(monitor=compliance_monitor)

# 3. Run Scenario 1: The Non-Compliant Request (Patient-12345)
# This patient only has 'billing' consent.
result_1 = research_agent.access_patient_data("Patient-12345")
print(f"FINAL RESULT 1: {result_1}")

# 4. Run Scenario 2: The Compliant Request (Patient-67890)
# This patient has 'clinical_research' consent.
result_2 = research_agent.access_patient_data("Patient-67890")
print(f"FINAL RESULT 2: {result_2}")

Consequences

Pros:

  • Trust and safety(信任与安全) :它是建立信任并确保系统合法安全运行的关键机制,为所有动作提供可审计轨迹。
  • Dynamic governance(动态治理) :策略可在中心引擎中更新而无需重新部署智能体,使系统能够快速适配新法规。

Cons:

  • Performance overhead(性能开销) :每次动作都要对策略引擎做检查会增加延迟。应谨慎应用于敏感或关键操作。
  • Complexity(复杂度) :需要搭建并维护独立的策略引擎,以及一组精心设计的规则。

Implementation guidance

强烈建议使用标准策略语言,例如 Rego(OPA) 。为提高效率,并不需要对每一个细粒度动作都检查;应聚焦在关键交互点(policy “choke points”)建立策略闸口,例如:访问数据存储、调用外部 API、以及与用户通信等环节。

尽管合规监控决定“哪些动作被允许”,其规则往往依赖于“是谁在执行动作”。要让这一检查安全可靠,系统不能仅仅信任智能体自报的身份;它必须能够以可验证方式证明身份。这种对安全、认证身份的依赖是基础前提,也就直接引出了下一个模式:Agent Authentication and Authorization

Agent Authentication and Authorization

当智能体能够代表系统、用户或组织自主行动时,安全就成为最重要的关注点。一个未被安全保护的智能体不仅仅是一个漏洞;它对应用而言是生存级风险。它可能被操控以泄露敏感数据、执行欺诈交易,或造成系统范围的破坏。

因此,在我们将任何有意义的任务交给智能体之前,必须以密码学确定性回答两个基本安全问题:这个智能体是谁?(authentication / 认证)以及这个智能体被允许做什么?(authorization / 授权)。

Context

该模式对于任何不是简单、孤立单体的 agentic 系统而言,都是不可妥协的要求。只要智能体需要访问受控资源(API、数据库等)、与具备不同权限级别的其他智能体交互,或执行会产生现实世界后果的操作,它就至关重要。

Problem

在一个分布式、动态环境中,如何安全地管理智能体身份并强制访问控制,以防止未授权行为、数据泄露,或对智能体能力的恶意接管?

Solution

解决方案是将 agentic 系统与健壮的身份与访问管理(IAM)框架集成,把智能体当作与用户或服务类似的“一级公民”,为其分配数字身份:

  • Authentication(验证身份) :每个智能体在部署时都会被签发一个唯一且可验证的凭据。通常是一个能生成短时效加密令牌的服务账号(例如 JSON Web Token, JWT)。智能体对系统其他部分发起的每个请求都必须用该令牌签名;接收方服务校验令牌以确认智能体身份。
  • Authorization(强制权限) :在智能体通过认证后,系统还必须检查它被允许做什么。这由访问控制策略管理。使用基于角色的访问控制(RBAC),智能体被分配角色(例如 billing_analystread_only_reporter),权限授予角色而非单个智能体。当已认证的智能体发起请求时,资源服务器会检查其角色是否具备该特定动作所需的权限。

High-security enhancements(高安全增强)

在需要最高完整性的环境中,标准 OAuth 2.0 的客户端凭据流(client credentials flow)通常会与签名 JWT(对照可轮换的 JWKS:JSON Web Key Set 验证)组合使用。此外,还可以强制 mTLS(双向 TLS) 在传输层同时认证客户端智能体与服务器,防止令牌被拦截并确保端到端信任。

该图详述了安全流程:智能体向资源提交其凭据(JWT),API 网关先验证令牌,再检查基于角色的权限后才授予访问。

image.png

Figure 10.5 – The Agent Authentication and Authorization pattern secures interactions using standard IAM protocols

Example: A multi-departmental analytics system

一家公司的主客户数据库由一个中心化的 CustomerDataAgent 守护。系统中还有两个智能体:SalesAgentMarketingAgent

  • Authentication(认证)SalesAgent 需要获取某客户的购买历史。它用自己的服务账号生成 JWT,并把它放入请求 CustomerDataAgent 的 header 中。CustomerDataAgent 的 API 网关验证令牌签名,确认该请求确实来自 SalesAgent
  • Authorization(授权) :网关在确认身份后检查其角色:sales_role。它查询访问控制列表,发现 sales_role 被允许读取 purchase_historycontact_info 字段。但 MarketingAgent(角色 marketing_role)只被允许读取匿名化的聚合数据。如果 SalesAgent 试图访问受限字段(例如支付明细),授权检查会失败,请求将以 403 Forbidden 被拒绝。

Example implementation

为说明该模式,我们沿用多部门分析系统:CustomerDataAgent 守护数据库,而 SalesAgentMarketingAgent 尝试访问。示例展示系统如何先验证请求者是谁(认证),再检查它能做什么(授权):

# --- 1. Define the Access Control List (ACL) ---
# This defines what each role is allowed to do.
ROLE_PERMISSIONS = {
    "sales_role": ["read_purchase_history", "read_contact_info"],
    "marketing_role": ["read_aggregated_data"]
}

# --- 2. Define the Protected Resource (the Data Agent) ---
class CustomerDataAgent:
    def __init__(self, acl):
        self.acl = acl
        # Mock database of protected data
        self.database = {
            "purchase_history": {"items": ["Laptop", "Mouse"]},
            "contact_info": {"email": "j.doe@example.com"},
            "payment_details": {"card": "xxxx-xxxx-xxxx-1234"},
            "aggregated_data": {"total_sales": 10000}
        }

    def get_data(self, requested_action: str, agent_token: str):
        """
        Handles a data request, checking auth and authorization.
        'agent_token' is a simple string representing the agent's role.
        """
        print(f"\n--- New Request ---")
        print(f"AGENT (Role: {agent_token}) requests: '{requested_action}'")
   
        # 1. Authentication (Who is this?)
        # We simply trust the token is the role for this example.
        agent_role = agent_token
        if agent_role not in self.acl:
            print(f"DENIED (401): Role '{agent_role}' does not exist.")
            return "Error: 401 Unauthorized"

        # 2. Authorization (What are they allowed to do?)
        allowed_actions = self.acl.get(agent_role)
        if requested_action not in allowed_actions:
            print(f"DENIED (403): Role '{agent_role}' cannot perform '{requested_action}'.")
            return "Error: 403 Forbidden"

        # 3. Grant Access
        data = self.database.get(requested_action)
        print(f"ALLOWED (200): Access granted.")
        return f"Success: {data}"

# --- 3. Execute the Workflow ---
# Initialize the system
data_agent = CustomerDataAgent(acl=ROLE_PERMISSIONS)

# Define the agents' "tokens" (their roles)
SALES_AGENT_TOKEN = "sales_role"
MARKETING_AGENT_TOKEN = "marketing_role"

# --- Scenario 1 (Success) ---
# Sales agent requests allowed data
result_1 = data_agent.get_data("read_purchase_history", SALES_AGENT_TOKEN)
print(result_1)

# --- Scenario 2 (Authorization Failure) ---
# Sales agent requests forbidden data
result_2 = data_agent.get_data("read_payment_details", SALES_AGENT_TOKEN)
print(result_2)

# --- Scenario 3 (Success) ---
# Marketing agent requests allowed data
result_3 = data_agent.get_data(
    "read_aggregated_data", MARKETING_AGENT_TOKEN)
print(result_3)

Consequences

Pros:

  • Security(安全) :提供基础安全保证,防止智能体冒充,并落实最小权限原则——智能体只能执行其绝对需要的操作。
  • Auditability(可审计性) :形成清晰可审计日志,记录哪个智能体在何时执行了哪个动作。

Cons:

  • Infrastructure complexity(基础设施复杂度) :需要搭建并管理完整 IAM:服务账号、令牌签发、策略定义等,带来运维开销。
  • Development overhead(开发开销) :智能体开发者必须在代码中正确实现令牌处理与管理。

Implementation guidance

不要为安全“重复造轮子”。自研认证或授权协议是常见反模式,往往会导致安全漏洞。

应使用业界成熟、经受实战考验的企业安全协议。现代标准是:OAuth 2.0 用于授权,OpenID Connect(OIDC) 用于认证。

理解 OAuth 2.0 的机器对机器(M2M)流程。由于智能体是自动化服务,不存在人工输入密码;该场景适用的 OAuth 2.0 流程是 client credentials flow(客户端凭据流) 。其工作方式如下:

  • Setup(注册) :将智能体作为客户端注册到中心授权服务器(如 OktaMicrosoft Entra ID(原 Azure AD)、或 Google IAM)。获得 client_idclient_secret
  • Token request(令牌请求) :当智能体需要访问受保护资源时,向授权服务器的 token endpoint 提交 client_idclient_secret
  • Token issuance(签发令牌) :服务器验证凭据后向智能体签发短时效 access token(通常为 JWT)。
  • API call(调用) :智能体在请求受保护资源(例如另一个智能体的 API)时,将该 access token 放入 Authorization header。
  • Validation(校验) :资源服务器(或其前置 API 网关)验证令牌真实性与有效期,并检查 token 关联的权限(scopes)以授权具体动作。

API gateway 集中化执行。与其让每个智能体/工具各自实现 token 校验逻辑,不如把它集中到 API 网关中。网关作为系统的安全入口,负责:

  • 拦截所有入站请求
  • 校验 JWT access token
  • 执行初步授权检查
  • 将已验证请求(连同智能体身份与权限)转发给下游服务

这会显著简化单个智能体的代码,因为它们可以信任:收到的请求已经完成认证与授权。

Key resources and further reading(关键资源与延伸阅读)

为正确实现该模式,你的团队应熟悉以下核心技术:

  • OAuth 2.0 网站:概念综述与官方规范入口(https://oauth.net/
  • RFC 6749:OAuth 2.0 授权框架官方规范
  • JWT 调试器:用于解码 payload 并校验签名(https://www.jwt.io/
  • 身份提供方(IdP)文档:如 Okta、Auth0、Microsoft Entra ID、Google Cloud IAM 等,提供 client credentials flow 的实操教程
  • 机密管理:client_idclient_secret 是高敏凭据,绝不能硬编码。使用 HashiCorp VaultAWS Secrets ManagerGoogle Secret Manager 进行安全存储与运行时读取

当智能体能够被发现、被治理、并被安全保护后,我们就具备了构建健壮系统的核心组件。本章最后一个模式将讨论系统如何高效响应周遭动态世界,确保它不仅安全,而且具备响应性。

Event-Driven Reactivity

智能体经常需要对外部世界正在发生的事情以(近)实时方式作出响应:一封新邮件到达、股价发生变化、或有新文件被上传。不断轮询数据源来检查更新既低效又难以扩展。**事件驱动反应性(Event-Driven Reactivity)**模式提供了更优雅、可扩展得多的解决方案。

Context

当 agentic 系统需要对来自外部系统、用户,甚至其他智能体的异步、不可预测事件保持响应时,会使用该模式。它是构建反应式、实时应用的基础。

Problem

在不浪费资源进行持续轮询的前提下,agentic 系统如何高效响应外部或内部触发?

Solution

为消除轮询的低效性,我们必须反转通信流。解决方案是基于事件驱动架构构建系统,并由一个中心消息总线或事件流来承载。该架构依赖三个核心组件之间的协作:

  • 事件生产者(Event producers) :生成事件的系统(例如处理新用户注册的 Web 服务器,或 IoT 传感器)称为生产者。它们会将描述事件的、短小且自包含的消息(例如 { "event_type": "new_user", "user_id": "123" })发布到消息总线上的特定主题(topic)。
  • 消息总线(Message bus) :专用基础设施组件(如 Apache KafkaRabbitMQGoogle Cloud Pub/Sub),负责接收生产者的消息,并将其路由到感兴趣的消费者。
  • 事件消费者(智能体)(Event consumers / agents) :需要对事件作出反应的智能体是消费者。它们订阅自己关心的主题。消息总线在消息发布后立即将其推送给订阅者。这个基于推送的模型会触发智能体的 sense-plan-act 循环。

智能体不再问:“有没有新的东西?”
系统会告诉智能体:“这里有新的东西。”

为使该架构具备韧性,三个运维控制至关重要:必须具备背压(backpressure)机制,避免事件洪峰压垮智能体的速率限制;应配置死信队列(DLQ)以捕获会导致智能体崩溃的畸形事件,防止“毒丸(poison pill)”阻塞队列;最后,智能体的动作必须设计为幂等(idempotent) ,确保当消息总线重投递事件(分布式系统中很常见)时,智能体不会重复执行同一动作(例如重复扣费)。

下图展示了一个解耦的异步工作流:生产者向消息总线发布事件,总线将消息推送给所有订阅的智能体,从而触发它们实时执行。

image.png

Figure 10.6 – The Event-Driven Reactivity pattern enables scalable and responsive systems through a central message bus

Example: An automated customer support system

为了看到该模式的实际效果,我们看一个自动化客服系统。当用户提交新工单时,系统通过事件总线立即触发多个相互独立的流程。这个“推送”模型使 TriageAgentArchivingService 能够实时响应,而无需轮询数据库来寻找新任务:

  • Producer(生产者) :用户通过 Web 表单提交新工单。Web 服务器向 Kafka 的 new_tickets topic 发布一条消息。

  • Message bus(消息总线) :Kafka 接收消息,并发现有两个服务订阅了该 topic。

  • Consumers(消费者)

    • TriageAgent 接收事件并立刻被触发,读取工单内容,使用 LLM 对优先级和类别进行分类(例如“Billing”“Urgent”),并将一个新的、增强后的事件发布到 triaged_tickets topic。
    • ArchivingService 也接收原始事件,并立即把原始工单写入长期数据仓库,用于分析。

TriageAgent 不需要轮询数据库。它被事件瞬间激活,使整个系统高度敏捷。

Example implementation

下面是一个 Python 示例,用于模拟该事件驱动工作流。我们将创建消息总线与智能体的 mock 类,展示信息如何流动:

import time

class MessageBus:
    """A simple mock message bus (like Kafka or Pub/Sub)."""
    def __init__(self):
        # Stores subscribers as: {"topic_name": [list_of_callbacks]}
        self.subscriptions = {}
        print("BUS: Message Bus initialized.")

    def subscribe(self, topic: str, callback_function):
        """Allows a consumer (agent) to subscribe to a topic."""
        if topic not in self.subscriptions:
            self.subscriptions[topic] = []
        self.subscriptions[topic].append(callback_function)
        # Get the name of the class that owns the callback
        consumer_name = callback_function.__self__.__class__.__name__
        print(f"BUS: '{consumer_name}' subscribed to topic '{topic}'.")

    def publish(self, topic: str, message: dict):
        """A producer calls this to publish an event."""
        print(f"\nBUS: New message published to topic '{topic}': {message}")
        if topic in self.subscriptions:
            # Push the message to all subscribed consumers
            for callback in self.subscriptions[topic]:
                callback(message)  # Trigger the consumer's method

class TriageAgent:  # Consumer 1
    def __init__(self, bus: MessageBus):
        self.bus = bus
        # Subscribe to the 'new_tickets' topic
        self.bus.subscribe("new_tickets", self.handle_new_ticket)

    def handle_new_ticket(self, ticket_data: dict):
        """This is the callback function triggered by the bus."""
        print("AGENT (Triage): Received new ticket. Classifying...")
        # Simulate LLM classification logic
        priority = "Urgent" if "payment" in ticket_data['content'].lower() else "Medium"
        category = "Billing" if "payment" in ticket_data['content'].lower() else "Technical"

        enriched_ticket = {
            **ticket_data,
            "priority": priority,
            "category": category
        }

        # Publish the enriched ticket to a new topic
        self.bus.publish("triaged_tickets", enriched_ticket)


class ArchivingService:  # Consumer 2
    def __init__(self, bus: MessageBus):
        self.bus = bus
        # Subscribe to the same 'new_tickets' topic
        self.bus.subscribe("new_tickets", self.archive_ticket)

    def archive_ticket(self, ticket_data: dict):
        """This callback is also triggered by the 'new_tickets' event."""
        print(f"AGENT (Archive): Received ticket {ticket_data['id']}. Writing to data warehouse...")
        # Simulate database write
        time.sleep(0.5)
        print(f"AGENT (Archive): Wrote {ticket_data['id']} to warehouse.")


class WebServer:  # Producer
    def __init__(self, bus: MessageBus):
        self.bus = bus

    def submit_ticket(self, ticket_content: str, user: str):
        ticket_id = f"TKT-{hash(ticket_content)}"
        print(f"\nSERVER: User '{user}' submitted a new ticket.")
        new_ticket = {
            "id": ticket_id,
            "user": user,
            "content": ticket_content
        }
        # Publish the event to the bus
        self.bus.publish("new_tickets", new_ticket)


# --- Execute the Workflow ---
message_bus = MessageBus()

# 1. Initialize the Consumers (Agents)
# They automatically subscribe when created
triage_agent = TriageAgent(bus=message_bus)
archiving_service = ArchivingService(bus=message_bus)

# 2. Initialize the Producer
web_server = WebServer(bus=message_bus)

# 3. Simulate a user submitting a ticket
web_server.submit_ticket(
    ticket_content="I can't access my payment history.",
    user="user@example.com"
)

Consequences

Pros:

  • Scalability and decoupling(可扩展性与解耦) :该模式构建出高度可扩展、强解耦系统。生产者不需要知道消费者是谁,消费者也无需知道生产者。你可以在不修改生产者的情况下新增更多消费事件的智能体。
  • Responsiveness(响应性) :系统变得高度反应式、近实时运行,智能体会在事件发生时被触发。

Cons:

  • Complexity(复杂度) :引入部署与运维消息总线的复杂性;异步编程也往往比简单的请求-响应模型更难调试。
  • Guaranteed delivery(交付保证) :必须正确配置消息总线的消息投递语义(例如“至少一次 at least once”),并处理潜在的消息失败。

Implementation guidance

为事件负载(payload)定义清晰、可版本化的 schema(例如使用 AvroProtobuf),以确保生产者与消费者能长期可靠通信。起步阶段可优先选择托管服务(如 Google Pub/SubAmazon SQS/SNS)以降低运维负担,随后再考虑自建如 Kafka 之类的方案。

我们现在已经探索了构建生产级 agentic 系统的四个基础模式:通过 registry 实现动态发现、通过认证实现强安全、通过合规监控实现自动化治理,以及通过事件驱动架构实现可扩展的响应性。理解这些组件各自的作用固然重要,但真正区分“能用”和“可用且稳”的关键在于:知道如何以及何时把它们部署到系统演进路径中。我们在本章开头提供的战略指南给出了一个实用路线图,帮助你随着系统从单智能体演进到企业级生态而逐步集成这些模式。

借助完整的模式语言与清晰的方法论,我们已经完成了对生产级 agentic AI 核心架构的深度剖析。接下来,让我们退一步,在总结中凝练我们确立的关键原则。

Summary

本章将我们的关注点从单个智能体的内部能力,转向使其能够作为一个内聚的、企业级多智能体系统或应用运行所必需的关键整体性外部架构。我们不再停留在智能体的“心智”内部,而是走进它所栖居的“城市”——也就是确保它能够通信、能够安全地行动、并能有效扩展的基础设施。这些系统级模式提供了将一个很有前景的 agentic 概念验证(proof of concept)转化为可靠、安全、可投入生产并能展示 ROI 的应用的蓝图。

关键要点如下:

  • 安全是基础: 智能体的身份与权限不是可选特性。只要智能体要执行有意义的动作,Agent Authentication and Authorization 模式就是不可妥协的第一步。没有它,就不可能建立信任。
  • 解耦支撑规模化与演进: 生产系统是动态的。Event-Driven Reactivity 模式确保系统具备响应性与可扩展性,而 Tool and Agent Registry 模式允许生态系统在无需持续修改代码的情况下增长与演化,从而促进模块化且具韧性的架构。
  • 治理必须自动化: 在高风险环境里,“寄希望于不出事”不是策略。Real-Time Compliance Monitoring 模式把治理直接嵌入系统肌理之中,确保自治动作能够自动、持续地遵循规则与法规。
  • 生产就绪是架构选择: 这些模式共同代表了一种思维方式的转变。它们是为满足非功能性需求(安全、可扩展性、治理与可靠性)而做出的刻意架构决策——正是这些需求将一个健壮的应用与一个脆弱的实验区分开来。

使用这些系统级模式,确保你具备设计与构建任何严肃的 agentic AI 计划所需的基础设施的架构“词汇表”。在对 agent-level 与 system-level 模式都有了扎实理解之后,我们现在已经完全具备能力去看到它们如何汇聚在一起。

在我们已经建立了智能体所栖居的那座安全、可响应、受治理的“城市”之后,我们就解决了实现生产就绪所需的外部要求。然而,要让系统真正达到企业级,智能体本身也必须从静态指令进一步演化。在下一章 Advanced Adaptation: Building Agents That Learn 中,我们将探索如何通过实现反馈回路、微调以及专门的学习模式,把固定行为转变为动态智能,让你的智能体能够在每一次交互中持续改进。