AIHero
    08 / 16Vercel AI SDK 教程

    使用 Vercel AI SDK 生成结构化输出

    了解如何结合 OpenAI 使用 Vercel AI SDK 生成结构化输出,并按预定义格式高效获取数据。

    Matt Pocock
    Matt Pocock
    源代码下一课
    本页目录

    很多时候,你希望 LLM 返回的不是文本,而是某种对象。

    例如,你可能想扫描银行对账单,提取账号、余额等多个属性。

    最高效的实现方式是使用结构化输出。

    它允许你向 LLM 提问,指定答案格式,模型就会按该格式返回信息。

    在这个示例中,我们让 LLM 生成食谱,包括食谱名称、配料数组,以及厨师制作菜品所需的步骤数组。

    {
    "recipe": {
    "name": "Chocolate Cake",
    "ingredients": [
    {
    "name": "flour",
    "amount": "2 cups"
    },
    {
    "name": "sugar",
    "amount": "2 cups"
    }
    // ...
    ],
    "steps": [
    "Preheat the oven to 350 degrees F.",
    "Mix the flour, sugar, cocoa powder, baking powder, baking soda, and salt in a large bowl."
    // ...
    ]
    }
    }

    滚动式代码讲解

    1

    第一步是创建一个 zod Schema,用来描述希望 LLM 返回的数据类型。

    如果以前没有接触过 zod ,我准备了一份 免费教程 ,位于姐妹站点 Total TypeScript。

    为了描述这里的食谱结构, zod Schema 可以写成这样:

    2

    可以把这个 Schema 直接传给 AI SDK 的 generateObject AI SDK 函数。

    3

    这里还添加了一个简单的系统提示词,让 AI 理解我们正在做什么。

    返回结果包含一个名为 object 的属性,其中保存食谱。

    得益于 TypeScript 的类型推断,我们还能以类型安全的方式访问 name, ingredients以及 steps.

    import { z } from "zod";
    const schema = z.object({
    recipe: z.object({
    name: z.string(),
    ingredients: z.array(
    z.object({
    name: z.string(),
    amount: z.string(),
    }),
    ),
    steps: z.array(z.string()),
    }),
    });

    描述属性

    但工作还没有完成。我们应该向 AI 提供更多信息,说明每个属性的含义。

    目前,AI 只能依据 name, ingredients以及 steps.

    可以通过为每个属性添加 zoddescribe 函数来完成。

    const schema = z.object({
    recipe: z.object({
    name: z
    .string()
    .describe("The title of the recipe"),
    ingredients: z
    .array(
    z.object({
    name: z.string(),
    amount: z.string(),
    }),
    )
    .describe(
    "The ingredients needed for the recipe",
    ),
    steps: z
    .array(z.string())
    .describe("The steps to make the recipe"),
    }),
    });

    现在 AI 能清楚理解每个属性需要什么。当属性名本身不够直观时,这尤其有用。

    最后,可以向 schemaName 传入一个属性,交给 generateObject 函数:

    const { object } = await generateObject({
    model,
    system:
    `You are helping a user create a recipe. ` +
    `Use British English variants of ingredient names, like Coriander over Cilantro.`,
    schemaName: "Recipe",
    schema,
    prompt,
    });

    运行看看输出结果。我们询问如何制作 Baba Ganoush。

    const recipe = await createRecipe(
    "How to make baba ganoush?",
    );
    console.dir(recipe, { depth: null });

    运行后,会得到一份 Baba Ganoush 食谱。

    pnpm run example v 08
    {
    "name": "Baba Ganoush",
    "ingredients": [
    { "name": "Aubergine", "amount": "2 large" },
    { "name": "Tahini", "amount": "3 tablespoons" }
    // ...
    ],
    "steps": [
    "Preheat the oven to 200°C (400°F).",
    "Pierce the aubergines several times with a fork."
    // ...
    ]
    }

    这就是从 AI SDK 获取结构化输出的方法。

    登录以保存进度。