文档

基础知识

结构化响应

使用 Pydantic (Python)、Zod (TypeScript) 或 JSON Schema 强制模型返回结构化响应

您可以通过向 `.respond()` 方法提供模式(JSON 或 `zod`)来强制 LLM 返回特定的响应格式。这保证了模型的输出符合您提供的模式。

使用 `zod` 模式强制执行

如果您希望模型生成符合给定模式的 JSON,建议使用 `zod` 提供模式。当提供 `zod` 模式时,预测结果将包含一个额外的字段 `parsed`,其中包含已解析、已验证和已类型化的结果。

定义 `zod` 模式

import { z } from "zod";

// A zod schema for a book
const bookSchema = z.object({
  title: z.string(),
  author: z.string(),
  year: z.number().int(),
});

生成结构化响应

const result = await model.respond("Tell me about The Hobbit.",
  { structured: bookSchema },
  maxTokens: 100, // Recommended to avoid getting stuck
);

const book = result.parsed;
console.info(book);
//           ^
// Note that `book` is now correctly typed as { title: string, author: string, year: number }

使用 JSON Schema 强制执行

您还可以使用 JSON 模式强制执行结构化响应。

定义 JSON Schema

// A JSON schema for a book
const schema = {
  type: "object",
  properties: {
    title: { type: "string" },
    author: { type: "string" },
    year: { type: "integer" },
  },
  required: ["title", "author", "year"],
};

生成结构化响应

const result = await model.respond("Tell me about The Hobbit.", {
  structured: {
    type: "json",
    jsonSchema: schema,
  },
  maxTokens: 100, // Recommended to avoid getting stuck
});

const book = JSON.parse(result.content);
console.info(book);
注意

结构化生成通过限制模型仅生成符合所提供模式的标记来工作。这在正常情况下确保了有效输出,但也存在两个重要的限制:

  • 模型(尤其是较小的模型)偶尔会陷入未闭合的结构(例如开放的括号),当它们“忘记”自己处于这种结构中时,由于模式要求而无法停止。因此,建议始终包含 `maxTokens` 参数以防止无限生成。

  • 模式合规性仅在完全成功生成时才能保证。如果生成中断(由于取消、达到 `maxTokens` 限制或其他原因),输出很可能会违反模式。使用 `zod` 模式输入时,这将引发错误;使用 JSON 模式时,您将收到一个不符合模式的无效字符串。

本页的源代码可在 GitHub 上找到