返回 Papers
AI 底层逻辑 / 经典论文

AI Contract-First Tool/API:契约优先集成

一句话:

426ai-foundations/papers/89-contract-first-ai-tool-api-design-openapi-asyncapi.md

Contract-First AI Tool / API Design with OpenAPI / AsyncAPI 解读

面向对象: AI Solutions Architect / Platform Architect / AI Product Manager / Integration Architect / Senior BA。 核心问题: AI agent 不是靠 prompt 文本“请调用正确工具”就能安全集成企业系统。工具、API、事件、结构化输出、权限、审批、幂等和审计都需要契约优先设计。 学习目标: 用 OpenAPI、AsyncAPI、JSON Schema、CloudEvents 和 contract testing 思维, 把 AI tool/API/event 集成设计成可验证、可版本化、可治理的企业能力。


Source Anchors

SourceLink用途
OpenAPI Specificationhttps://spec.openapis.org/oas/latest.html参考 HTTP API 契约描述, 用于 tool/API 的 operation、schema、security、response 设计
AsyncAPI Specificationhttps://www.asyncapi.com/docs/reference/specification/latest参考事件驱动和消息系统契约, 用于 agent event、workflow event、notification event
JSON Schemahttps://json-schema.org/参考结构化输入输出、tool arguments、event payload、model response schema
CloudEventshttps://cloudevents.io/参考事件 metadata 一致性, 支撑跨系统事件追踪和路由
OpenTelemetryhttps://opentelemetry.io/docs/参考 trace、metrics、logs, 把契约执行连接到 runtime observability 和 evidence

一句话:

Contract-first AI integration 是先定义 tool/API/event 的结构、权限、副作用、错误、版本和证据要求, 再让模型或 agent 在这些受控契约内行动。


1. 为什么 AI 工具调用不能靠 prompt 文本约定

低成熟度做法:

System prompt: You can call account lookup, refund, email, and case update tools.

这种做法的问题:

风险说明
Tool boundary 模糊模型不知道每个工具真实权限、副作用和限制
参数不稳定自然语言约定无法保证字段、类型、枚举、必填项
错误处理弱timeout、partial failure、validation error、business error 没有统一语义
审批缺失高风险动作是否需要人工审批无法仅靠 prompt 保证
版本不可控工具变化后 prompt、eval、调用端可能不同步
审计困难无法证明当时调用的 contract、policy、payload、approval
安全漏洞prompt injection 可能诱导调用越权工具或泄露数据

企业 AI agent 的集成原则:

Prompt can propose.
Contract constrains.
Policy authorizes.
Telemetry proves.
Human approves when risk requires.

2. Contract-First Taxonomy

AI 系统至少有六类契约:

Contract type描述代表技术/产物
Tool contractAgent 可调用什么工具, 输入输出和副作用是什么OpenAPI operation、JSON Schema、tool card
Event contractAgent/workflow 发布或消费什么事件AsyncAPI、CloudEvents
Structured output contract模型必须返回什么结构JSON Schema、constrained decoding、validator
Policy contract哪些角色、数据、场景、风险等级允许调用OPA/Cedar/DMN、policy matrix
Eval contract契约如何被测试和回归验证test cases、mock server、trajectory eval
Evidence contract调用后必须产生哪些 trace、log、approval、audit recordOpenTelemetry spans、audit event schema

如果只定义 API schema, 但不定义副作用、权限、审批和证据, 仍然不是 AI-ready contract。


3. OpenAPI for AI Tools

OpenAPI 适合描述同步 HTTP API 和 tool operations。

3.1 Tool Operation Card

FieldExample
tool_idcase.create_note
operationIdCreateCaseNote
business purpose为争议 case 添加运营备注
input schemacaseId, noteText, source, confidence, traceId
output schemanoteId, createdAt, status
side effect写入 case management system
risk levelmedium
required permissioncase:write_note
approvalnot required for internal note; required if note is customer-visible
idempotencyIdempotency-Key required
audit eventcase.note.created
eval coverageparameter correctness, unsafe note refusal, duplicate prevention

3.2 AI Tool Contract 扩展字段

普通 API contract 不够, AI tool contract 需要额外说明:

Extension说明
x-ai-risk-levelread、draft、low-risk-write、high-risk-write、irreversible
x-ai-human-approvalnone、sampled、required、dual-control
x-ai-side-effectnone、reversible、compensatable、irreversible
x-ai-data-classificationpublic、internal、confidential、restricted
x-ai-policy-profile哪组 policy 决定 allow/block/approve
x-ai-evidence-requiredtrace id、approval id、actor、source citations、reason
x-ai-eval-suite需要通过的 tool trajectory eval

这些可以作为内部约定嵌入 API governance, 也可以在 tool registry 中维护。

3.3 Error Contract

AI agent 必须理解错误类别, 否则会盲目重试或编造结果。

Error classAgent behavior
validation_error修正参数或请求澄清
authorization_error停止调用并升级人工
policy_block向用户说明无法执行或进入审批
business_rule_violation根据规则提示替代路径
transient_error有预算地重试
dependency_timeout降级或排队
conflict_duplicate使用 idempotency result

错误契约必须进入 eval, 不只是进入开发文档。


4. AsyncAPI and Event Contracts for Agents

Agent workflow 不一定都是同步请求。很多企业 AI 场景是事件驱动:

  • 文档上传后触发 extraction。
  • 风险告警触发 investigation assistant。
  • 客户投诉触发 triage workflow。
  • 人工审批完成后恢复 agent workflow。
  • model/prompt/eval 版本变更触发 regression run。

4.1 Event Contract

FieldExample
channelcase.dispute.triage.requested
producercase management system
consumerdispute agent workflow
payload schemacase id、customer segment、amount band、reason code、priority
CloudEvents metadataid、source、type、subject、time、traceparent
orderingper case id
retryexponential backoff, DLQ after 5 attempts
idempotencyevent id + case id
privacyno full PAN, no unnecessary PII
auditevent stored with workflow trace

4.2 Agent Event Types

EventMeaning
agent.workflow.startedAgent workflow 启动
agent.tool.proposed模型提出工具调用
agent.policy.blockedpolicy 阻断
agent.approval.requested需要人工审批
agent.approval.completed审批完成
agent.tool.executed工具执行
agent.workflow.completed工作流完成
agent.workflow.failed工作流失败
agent.workflow.escalated升级人工

这些事件让 agent 从黑盒推理变成可观测工作流。


5. JSON Schema for Structured IO

结构化输出契约可用于:

  • 工具参数。
  • 模型回答。
  • 分类结果。
  • 风险分级。
  • eval judge 输出。
  • 人工复核表单。
  • 事件 payload。

示例字段设计:

FieldDesign rule
enum对关键 decision 使用枚举, 不让模型自由造词
required对审计和执行必须字段强制 required
format对日期、email、uri、id 等指定格式
min/max对金额、分数、置信度和步数设边界
additionalProperties高风险 payload 默认关闭
reason允许 explanation, 但不得作为执行依据
source_refs需要引用时强制列出 source id/version

结构化输出的关键不是“方便解析”, 而是把 AI 输出变成 contract-bound object, 可以验证、审计、回归测试和版本管理。


6. Contract Governance

6.1 Versioning

ChangeCompatibilityRequired action
Add optional fieldbackward compatibleupdate docs and tests
Add required fieldbreakingnew version, agent update, eval rerun
Rename enum valuebreakingmigration and compatibility layer
Relax validationriskysecurity/risk review
Tighten validationmay break agentregression eval
Change side effecthigh riskADR, approval, release gate
Change policy requirementhigh riskrisk signoff, evidence update

6.2 Contract Testing

TestPurpose
Schema validation参数和响应符合 contract
Mock server testAgent 能在 contract 下完成任务
Negative test不合法参数被拒绝
Policy test不同 role/risk/data 下 allow/block/approve 正确
Idempotency test重试不会重复执行副作用
Error behavior testAgent 不编造结果, 能升级或降级
Telemetry test每次调用都有 trace、span、audit event
Compatibility test新版本不破坏已批准 workflow

6.3 Contract Review Board

AI tool/API/event contract 的 review 不应只由工程决定:

RoleReview focus
Product工具是否支持真实用户任务, 是否引入过度自动化
Architect边界、版本、可复用、依赖和演进
Security权限、数据泄露、攻击面
Risk/compliance高风险动作、审批、证据
Operations错误处理、重试、SLO、incident
Data owner输入输出数据分类和最小化

7. Financial Retail Case: Dispute Resolution Agent

Agent 可做:

  • 读取交易详情。
  • 读取争议政策。
  • 生成 case summary。
  • 创建内部 note。
  • 请求人工审批。

Agent 不可做:

  • 自动退款。
  • 直接发送客户通知。
  • 修改监管报告。
  • 查看无关客户数据。

7.1 Tool Contract Matrix

ToolRiskContractPolicyEvidence
transaction.lookupreadOpenAPI read operationcustomer/case scopetrace span
policy.searchreadretrieval schemaapproved source onlycitation ids
case.summarizedraftstructured output schemano customer sendsummary eval
case.create_notemedium writeOpenAPI write operationcase:write_noteaudit event
approval.requestworkflowevent contractrequired for high-riskapproval id
refund.executehigh-risk writeunavailable to agenthuman-onlyseparate workflow

7.2 Event Flow

case.dispute.triage.requested
  -> agent.workflow.started
  -> agent.tool.proposed(transaction.lookup)
  -> agent.tool.executed
  -> agent.tool.proposed(policy.search)
  -> agent.tool.executed
  -> agent.output.generated(case_summary)
  -> agent.approval.requested if high amount
  -> agent.workflow.completed or escalated

每个 event 都带:

  • traceparent。
  • case id。
  • workflow id。
  • contract version。
  • policy decision。
  • actor / agent identity。

7.3 Release Gate

GateRequired evidence
Contract reviewtool cards、schemas、side-effect matrix
Security reviewpermission test、prompt injection tests
Eval reviewtrajectory eval、negative cases、error behavior
Ops reviewretry、DLQ、idempotency、dashboard
Risk approvalhigh-risk action policy、HITL rule
Releasetrace sample、audit event sample、rollback plan

8. Product Requirements for Contract-First AI

高级 PM/BA 写需求时, 不只写“Agent 可以查询交易”, 而要写:

Requirement dimensionExample
Business capabilityAgent can support dispute triage by collecting relevant transaction and policy evidence
Allowed actionRead transaction details for the active case only
Prohibited actionAgent cannot initiate refund or customer notification
ContractMust use approved transaction.lookup OpenAPI operation
Data boundaryNo full card number in prompt or trace
Error behaviorIf lookup fails, escalate to human and do not infer transaction details
EvalTool selection and argument correctness >= threshold
EvidenceTool call span includes trace id, case id, policy decision, response status

这类需求比普通 user story 更适合 AI 系统, 因为它把“能做什么”和“如何安全地做”放在一起。


9. Common Failure Modes

Failure mode表现修正
Prompt-only tools工具边界只写在 prompt 里建立 tool registry + schema + policy
Schema without side effect只定义字段, 不定义风险加入 risk、approval、idempotency、audit
No negative cases只测成功调用测越权、错误参数、超时、业务规则拒绝
Breaking change surpriseAPI 改了, agent 没跑回归versioning + compatibility eval
Event without trace事件能跑但无法查证CloudEvents metadata + trace context
Agent sees too many tools工具暴露过宽capability discovery by role/risk/task
Audit afterthought上线后才补日志evidence contract before implementation

10. Templates

10.1 Tool Contract Card

Field内容
Tool name工具名称
Business purpose支持的业务任务
Contract linkOpenAPI operation / schema
Input / output字段、类型、枚举、required
Data classification输入输出数据等级
Side effectnone / reversible / compensatable / irreversible
Risk levelread / draft / write / high-risk
Authorizationrole、scope、policy profile
Approvalnone / sampled / required / dual-control
Idempotencykey、dedupe window
Error behaviorvalidation、auth、policy、business、transient
Telemetryrequired spans、metrics、audit event
Eval suitepositive、negative、trajectory、regression

10.2 Event Contract Card

Field内容
Event type事件名称
Producer / consumer生产者和消费者
Trigger什么时候发出
Payload schemaJSON Schema / AsyncAPI message
Metadataid、source、subject、time、traceparent
Orderingordering key
Retry / DLQ重试和死信策略
Privacy不允许出现的数据
Evidence事件存储、trace、audit
Compatibility版本策略

10.3 Compatibility Policy

RulePolicy
Required field change新 major version
Enum removal新 major version
Side-effect changeADR + security/risk review
Policy relaxationrisk approval
Error contract changeeval regression
Deprecation通知、迁移窗口、consumer inventory

11. 面试表达

30 秒版本:

我会用 contract-first 设计 AI agent 的工具和事件集成。Prompt 可以让模型提出工具调用, 但真正的边界要由 OpenAPI/AsyncAPI/JSON Schema、policy、approval、idempotency 和 telemetry 定义。这样工具调用可以被验证、版本化、审计和回归测试, 不会把企业系统暴露给不可控的自然语言约定。

2 分钟版本:

以争议处理 agent 为例, 我会把 transaction lookup、policy search、case note、approval request 都做成工具或事件契约。每个契约说明输入输出、数据等级、副作用、权限、审批、幂等、错误行为和审计事件。Agent 只能发现符合当前 role/risk/task 的工具; 高风险动作不暴露或必须走 HITL。上线前跑 schema validation、negative tests、policy tests、trajectory eval 和 telemetry evidence check。这样 AI 集成不是 demo glue code, 而是企业级集成架构。

深挖追问:

追问回答要点
OpenAPI 和 AsyncAPI 怎么分工同步 HTTP tool 用 OpenAPI, 事件驱动 workflow 用 AsyncAPI
JSON Schema 的价值把模型输入输出变成可验证对象
如何控制 tool side effectside-effect classification、policy、approval、idempotency、audit
如何处理版本变化compatibility policy、consumer inventory、regression eval
如何防 prompt injection最小工具暴露、policy enforcement、schema validation、negative tests

12. Practice Assignment

为一个 AI agent use case 设计 contract pack:

  1. 3 张 tool contract cards。
  2. 2 张 event contract cards。
  3. 1 个 structured output schema。
  4. 1 张 side-effect matrix。
  5. 1 套 negative contract tests。
  6. 1 条 release gate: contract evidence completeness。

完成标准:

  • 每个 tool 都有 risk、permission、approval、idempotency、audit。
  • 每个 event 都有 schema、metadata、retry、trace。
  • 至少 5 个 negative cases 覆盖越权、错误参数、policy block、timeout、business rule。
  • 能解释为什么某个高风险动作不应该暴露给 agent。