Zod Schema 工程通用指南¶
使用 Zod 定义和验证 Schema 时,应遵循确保清晰度、模块化和灵活性的原则,这与 Pydantic 类似。
- 模块化:构建独立的 Schema 以供重用。
- 自我描述:使用 Zod 的
.describe()
方法描述字段以提高清晰度。 - 可选性:对于可选字段,使用
z.union
和z.undefined()
。 - 标准化:对于具有特定值集合的字段,使用
z.enum
,包含一个“其他”选项以处理模糊情况。 - 动态数据:对于任意属性,应用
z.record(z.string())
,并控制键值对。 - 实体关系:通过显式标识符和关系字段定义关系。
- 上下文逻辑:添加一个可选的“思维链”字段以提供上下文。
模块化思维链¶
利用 Zod 的灵活性实现模块化“思维链”,从而提高数据质量。
import { z } from 'zod';
const Role = z.object({
chainOfThought: z.string().describe("Sequential reasoning to determine the correct title"),
title: z.string(),
});
const UserDetail = z.object({
age: z.number(),
name: z.string(),
role: Role,
});
利用可选属性¶
对于可选字段,使用 z.union
和 z.undefined()
。
Schema 内的错误处理¶
创建一个包装 Schema 来处理成功和错误状态。
const MaybeUser = z.object({
result: UserDetail.optional(),
error: z.boolean(),
message: z.string().optional(),
});
// `MaybeUser` can now encapsulate both a result and an error state.
通过动态模式简化¶
利用 Zod 的动态 Schema 创建功能来简化错误处理。
const Maybe = (schema) => z.object({
result: schema.optional(),
error: z.boolean(),
message: z.string().optional(),
});
const MaybeUser = Maybe(UserDetail);
枚举技巧¶
为标准化字段实现 z.enum
,包含一个“其他”选项。
const Role = z.enum(["PRINCIPAL", "TEACHER", "STUDENT", "OTHER"]);
const UserDetail = z.object({
age: z.number(),
name: z.string(),
role: Role,
});
重申长指令¶
对于复杂属性,在字段描述中重述指令。
const Role = z.object({
instructions: z.string().describe("Repeat the rules for determining the title."),
title: z.string(),
});
处理任意属性¶
对于未定义的属性,使用 z.record(z.string())
。
const UserDetail = z.object({
age: z.number(),
name: z.string(),
properties: z.record(z.string()).describe("Arbitrary key-value pairs"),
});
限制列表长度¶
通过 Zod 的数组验证来控制列表长度。
const Property = z.object({
key: z.string(),
value: z.string(),
});
const UserDetail = z.object({
age: z.number(),
name: z.string(),
properties: z.array(Property).max(6).describe("Manageable set of properties"),
});
定义实体关系¶
在您的 Schema 中显式定义关系,例如用户好友的 ID。
const UserDetail = z.object({
id: z.number(),
age: z.number(),
name: z.string(),
friends: z.array(z.number()).describe("List of friend IDs, representing user relationships"),
});
在不同上下文中重用组件¶
通过单独定义组件,可以在各种上下文中重用它们。
const TimeRange = z.object({
startTime: z.number().describe("Start time in hours."),
endTime: z.number().describe("End time in hours."),
});
const UserDetail = z.object({
id: z.number(),
age: z.number(),
name: z.string(),
workTime: TimeRange,
leisureTime: TimeRange,
});
这些指南应能简化和增强您的 Zod Schema 创建和验证过程。