跳到内容

Zod 模式

Zod 是一个 TypeScript 优先的模式声明和验证库。它被设计为易于与 TypeScript 一起使用,并与该语言很好地契合。它是进行 prompt engineering 的主要方式,请注意 response_model 必须是 z.object

基本用法

import { z } from 'zod';

const schema = z.object({
  name: z.string(),
  age: z.number(),
});

描述即 Prompt

Instructor 的核心之一是它能够将这些描述用作 prompt 的一部分。

const userDetails = z.object({
  name: z.string().description('Your full name'),
  age: z.number(),
}).description('Fully extracted user detail');

推断类型

我们还可以使用 Zod 模式生成类型。

const schema = z.object({
  name: z.string(),
  age: z.number(),
});

type SchemaType = z.infer<typeof schema>;

默认值

为了帮助语言模型,我们还可以为值定义默认值。

const schema = z.object({
  name: z.string(),
  age: z.number().optional(),
  isStudent: z.boolean().default(false),
});

可选值

我们还可以定义可选值。

const schema = z.object({
  name: z.string(),
  age: z.number().optional(),
});

嵌套模式

通过嵌套模式可以创建强大的模式。

const schema = z.object({
  name: z.string(),
  address: z.object({
    street: z.string(),
    city: z.string(),
  }),
});

数组

可以使用 z.array 方法定义数组

const schema = z.object({
  name: z.string(),
  friends: z.array(z.string()),
});

枚举

可以使用 z.enum 方法定义枚举

const schema = z.object({
  name: z.string(),
  role: z.enum(['admin', 'user']),
});