← Back to learning path

This chapter has not been reviewed in English; the original Simplified Chinese is shown.

Chapter · Published

结构化输出与工具调用:把模型接入业务代码 (original language)

使用 schema 校验模型输出,隔离工具权限和业务副作用。

Source: knowledge/p24-c/collection_0587a2bfc47ea3584d1b1c59/tutorials/ai-app-structured-outputs.mdAI application development
Chapter progress 0%Learning path progress 0% · 0/10 chapters completedContinue learning path →

自由文本不适合作为业务 API 的输入。结构化输出可以降低解析歧义,但仍需要服务端校验字段、权限和业务状态。

核心概念

模型输出校验、业务校验和权限校验是三层边界。工具函数应返回稳定错误码,写操作使用幂等键,模型不能直接访问数据库或环境变量。

可运行示例

from pydantic import BaseModel, Field

class TicketDecision(BaseModel):
    category: str
    priority: str = Field(pattern='^(low|normal|high)$')
    needs_human: bool

def safe_dispatch(decision: TicketDecision) -> dict:
    if decision.category not in {'product', 'billing', 'security'}:
        raise ValueError('unknown category')
    return {'status': 'needs_human' if decision.needs_human else 'ready', 'category': decision.category}

操作步骤

  1. 为每个模型输出定义版本化 schema 和枚举值。
  2. 解析后再次检查长度、权限、资源归属和业务状态。
  3. 把只读工具与写工具分组,写工具默认进入待确认队列。
  4. 用未知字段、缺字段、重复请求和越权输入做测试。

Use cases

适合工单分流、CRM 助手、审批建议和需要稳定 API 的 AI 产品。

常见问题

结构化输出能保证正确吗? 只能保证形状,不能保证事实和权限正确。

模型能调用写接口吗? 需要独立授权、幂等和人工确认,不应直接拥有高风险凭证。

官方参考

OpenAI Function Calling;OpenAI Structured Outputs。

最后核对日期:2026-11-16。版本、接口和安全边界以链接的官方资料为准;本文不虚构性能或费用结论。

Related practical cases

Knowledge实战:FastAPI 结构化 AI 接口 (original language)

Further reading

KnowledgeStructured Outputs and Tool Contracts for Safe Agents
Product Hub Demo · V0.3