• 简体中文
  • v6.5.0
  • 结构化输出

    内置的 generate_object 工具会让配置的 LLM 生成 JSON 对象,对响应执行你提供的 JSON Schema 校验,并且只在零退出码结果中返回校验后的对象。当你需要机器可读的结果时 使用它:抽取、分类、配置生成,或者作为另一个程序的输入。

    你可以通过 session.tool('generate_object', ...) 直接调用它。工具结果会把校验后的对象以 JSON 形式放在 result.output 上——解析它并读取 object 字段。同一个工具也支持 agent 自主调用,即模型在 send 过程中自行决定调用它。

    直接工具调用

    最简单的方式:直接调用 generate_object,先检查工具退出码,再从结果中解析出校验后的对象。

    Node.js
    Python

    校验后的值位于解析输出的 object 键上。当 result.exitCode(Node)/ result.exit_code(Python)为零时,required 中声明的字段已经通过运行时校验。 如果模型在修复重试后仍无法满足 schema,工具会报告非零退出码。

    枚举分类

    enum 把字段约束到一个固定集合。这会把自由文本分类变成带 schema 闸门的结果。

    Node.js
    Python
    TypeScript
    const result = await session.tool('generate_object', {
    schema: {
    type: 'object',
    required: ['sentiment', 'confidence'],
    properties: {
    sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
    confidence: { type: 'number', minimum: 0, maximum: 1 },
    },
    },
    prompt: 'Classify sentiment: "This is the worst product I have ever used."',
    schema_name: 'sentiment',
    });
    const { object } = JSON.parse(result.output);
    console.log(object.sentiment, object.confidence); // "negative" 0.97

    嵌套 schema 与数组

    Schema 可以任意深度地嵌套对象和数组,运行时会校验整个结构。这能在一次调用中建模真实的配置文件、清单或 API 载荷。

    Node.js
    Python

    Agent 自主调用

    你也可以让 agent 自行决定何时使用结构化输出。让它在 send 过程中调用 generate_object;它会先收集上下文,再输出对象。

    Node.js
    Python
    TypeScript
    const result = await session.send(
    'Use the generate_object tool to extract the following into an object ' +
    'with fields "title" (string), "year" (integer), "genre" (string): ' +
    'The movie "Inception" was released in 2010 and is a sci-fi thriller.',
    );
    console.log(
    `tool calls: ${result.toolCallsCount}, tokens: ${result.totalTokens}`,
    );

    Schema 校验覆盖

    内置校验器支持:

    • type(包括 nullable 数组如 ["string", "null"]
    • requiredpropertiesadditionalProperties
    • enumconst
    • anyOfoneOf
    • minLengthmaxLengthpattern
    • minimummaximumexclusiveMinimumexclusiveMaximum
    • minItemsmaxItemsitems
    • 嵌套对象和数组校验

    说明

    • 校验后的值位于解析后 result.outputobject 键上。当前跨 provider 默认路径传 mode: 'tool',仅 prompt 的回退方式传 mode: 'prompt'autostrictjson 在当前运行路径中都会解析为 tool
    • 把你依赖的每个字段都列入 required——运行时会强制执行,因此缺失或类型错误的字段会导致校验失败,而不是悄悄返回部分数据。
    • generate_object 是独立注册的内置工具,不依赖 built-in skills。
    • 直接 session.tool(...) 调用是宿主控制面调用。允许模型在 send / run / stream 中自行选择工具时使用 permissionPolicy;直接 SDK 调用前应使用宿主自己的授权逻辑。

    可运行版本随源码提供,位于 crates/code/sdk/node/examples/basic/test_generate_object.tscrates/code/sdk/python/examples/test_generate_object.py