with one click
langchain-structured-output
使用 Zod 模式、类型安全响应和自动验证从 LangChain 代理和模型获取结构化的验证输出
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Menu
使用 Zod 模式、类型安全响应和自动验证从 LangChain 代理和模型获取结构化的验证输出
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Based on SOC occupation classification
Mac 系统深度清理和优化工具。使用 Mole (mo 命令) 执行系统清理、磁盘分析、应用卸载、系统优化等任务。 触发场景(当用户提到以下任一内容时使用此 skill): - 清理 Mac、清理磁盘、释放空间、清理缓存、清理系统 - 卸载应用、删除应用、移除应用及其残留 - 磁盘分析、查看磁盘占用、大文件查找、空间分析 - 系统优化、系统维护、刷新系统、重建缓存 - 系统状态、系统监控、CPU/内存/磁盘监控 - 清理 node_modules、清理构建产物、清理项目依赖 - 清理安装包、删除 dmg/pkg 文件 - Mac 清理工具、类似 CleanMyMac 的功能 - "我的 Mac 太慢了"、"磁盘空间不足"、"电脑卡顿" - 即使没有明确说 "Mole",只要涉及上述场景就应使用
快速搭建和配置 pnpm monorepo 项目结构,包含 TypeScript、tsup 构建、私有 npm registry 配置。当用户需要"创建 monorepo"、"初始化 monorepo 项目"、"配置 pnpm workspace"、"设置 monorepo 构建"、"monorepo setup"时使用。特别适合需要统一管理多个包、配置构建工具、处理 TypeScript 路径问题的场景。即使用户只是说"帮我搭建项目结构"或"配置构建",如果涉及多包管理也应该使用此 skill。
智能拆分暂存区的代码变更为多个符合 Conventional Commits 规范的逻辑提交。当用户需要将大量变更按逻辑关系分组提交时使用,比如"拆分这些提交"、"把暂存区的变更分成多个 commit"、"按功能分别提交"、"split commits"等场景。特别适合处理包含多个模块、多种类型文件(配置、代码、测试、文档)的复杂变更集。
OKR 优化与质量评估专家。当用户需要:(1) 评估现有 OKR 的质量,(2) 优化模糊或不可量化的关键结果,(3) 检查 OKR 是否符合核心原则(聚焦、可量化、有挑战),(4) 将任务型 KR 转化为结果型 KR,(5) 提供具体的改进建议时使用。触发词包括"帮我优化 OKR"、"检查这个 OKR"、"这个 KR 写得好吗"、"如何量化这个目标"。
基于 git commits 自动生成 CHANGELOG.md 变更日志。支持语义化版本、分类整理、多格式输出。触发场景包括"生成变更日志"、"更新 CHANGELOG"、"版本记录"。
GitHub PR 代码审查技能。检查代码质量、安全性、性能和最佳实践,生成结构化审查报告。触发场景包括"审查 PR"、"代码检查"、"review pull request"。
| name | langchain-structured-output |
| description | 使用 Zod 模式、类型安全响应和自动验证从 LangChain 代理和模型获取结构化的验证输出 |
| language | js |
结构化输出将非结构化的模型响应转换为经过验证的、类型化的数据。不是解析自由文本,而是获得符合您模式的 JSON 对象——非常适合数据提取、构建表单或与下游系统集成。
核心概念:
| 使用场景 | 使用结构化输出? | 原因 |
|---|---|---|
| 提取联系信息、日期等 | ✅ 是 | 可靠的数据提取 |
| 表单填写 | ✅ 是 | 验证所有必填字段 |
| API 集成 | ✅ 是 | 类型安全的响应 |
| 分类任务 | ✅ 是 | 枚举验证 |
| 开放式问答 | ❌ 否 | 自由文本即可 |
| 创意写作 | ❌ 否 | 不要限制创造力 |
| 模式类型 | 使用时机 | 示例 |
|---|---|---|
| Zod 模式 | TypeScript 项目(推荐) | z.object({...}) |
| JSON 模式 | 互操作性 | { type: "object", properties: {...} } |
| 联合类型 | 多种可能的格式 | z.union([schema1, schema2]) |
import { createAgent } from "langchain";
import { z } from "zod";
const ContactInfo = z.object({
name: z.string(),
email: z.string().email(),
phone: z.string(),
});
const agent = createAgent({
model: "gpt-4.1",
responseFormat: ContactInfo,
});
const result = await agent.invoke({
messages: [{
role: "user",
content: "提取:John Doe, john@example.com, (555) 123-4567"
}],
});
console.log(result.structuredResponse);
// { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
const MovieSchema = z.object({
title: z.string().describe("电影标题"),
year: z.number().describe("上映年份"),
director: z.string(),
rating: z.number().min(0).max(10),
});
const model = new ChatOpenAI({ model: "gpt-4.1" });
const structuredModel = model.withStructuredOutput(MovieSchema);
const response = await structuredModel.invoke("告诉我《盗梦空间》");
console.log(response);
// { title: "Inception", year: 2010, director: "Christopher Nolan", rating: 8.8 }
import { z } from "zod";
const AddressSchema = z.object({
street: z.string(),
city: z.string(),
state: z.string(),
zip: z.string(),
});
const PersonSchema = z.object({
name: z.string(),
age: z.number().int().positive(),
email: z.string().email(),
address: AddressSchema,
tags: z.array(z.string()),
});
const agent = createAgent({
model: "gpt-4.1",
responseFormat: PersonSchema,
});
import { z } from "zod";
const ClassificationSchema = z.object({
category: z.enum(["urgent", "normal", "low"]),
sentiment: z.enum(["positive", "neutral", "negative"]),
confidence: z.number().min(0).max(1),
});
const agent = createAgent({
model: "gpt-4.1",
responseFormat: ClassificationSchema,
});
const result = await agent.invoke({
messages: [{
role: "user",
content: "分类:这非常重要,而且我很高兴!"
}],
});
// { category: "urgent", sentiment: "positive", confidence: 0.95 }
import { z } from "zod";
const EventSchema = z.object({
title: z.string(),
date: z.string(),
location: z.string().optional(),
attendees: z.array(z.string()).default([]),
confirmed: z.boolean().default(false),
});
import { z } from "zod";
const EmailSchema = z.object({
type: z.literal("email"),
to: z.string().email(),
subject: z.string(),
});
const PhoneSchema = z.object({
type: z.literal("phone"),
number: z.string(),
message: z.string(),
});
const ContactSchema = z.union([EmailSchema, PhoneSchema]);
const agent = createAgent({
model: "gpt-4.1",
responseFormat: ContactSchema,
});
// 模型根据输入选择使用哪种模式
import { z } from "zod";
const TaskListSchema = z.object({
tasks: z.array(z.object({
title: z.string(),
priority: z.enum(["high", "medium", "low"]),
dueDate: z.string().optional(),
})),
});
const agent = createAgent({
model: "gpt-4.1",
responseFormat: TaskListSchema,
});
const result = await agent.invoke({
messages: [{
role: "user",
content: "提取任务:1. 修复 bug(高优先级,明天到期)2. 更新文档"
}],
});
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
const schema = z.object({ name: z.string(), age: z.number() });
const model = new ChatOpenAI({ model: "gpt-4.1" });
const structuredModel = model.withStructuredOutput(schema, {
includeRaw: true,
});
const response = await structuredModel.invoke("人员:Alice,30岁");
console.log(response);
// {
// raw: AIMessage { ... },
// parsed: { name: "Alice", age: 30 }
// }
import { createAgent } from "langchain";
import { z } from "zod";
const StrictSchema = z.object({
email: z.string().email(),
age: z.number().int().min(0).max(120),
});
const agent = createAgent({
model: "gpt-4.1",
responseFormat: StrictSchema,
});
try {
const result = await agent.invoke({
messages: [{ role: "user", content: "邮箱:invalid,年龄:-5" }],
});
} catch (error) {
console.error("验证失败:", error);
// 模型将重试或返回错误
}
✅ 模式结构:任何有效的 Zod 模式 ✅ 字段验证:类型、范围、正则表达式等 ✅ 可选与必填:控制字段存在性 ✅ 嵌套对象:复杂的层次结构 ✅ 数组:项目列表 ✅ 枚举:受限的值
❌ 模型推理:无法控制模型如何生成数据 ❌ 保证 100% 准确性:模型仍可能出错 ❌ 在上下文缺少数据时强制有效数据:模型无法编造缺失信息
// ❌ 问题:访问错误的属性
const result = await agent.invoke(input);
console.log(result.response); // undefined!
// ✅ 解决方案:使用 structuredResponse
console.log(result.structuredResponse);
// ❌ 问题:没有字段描述
const schema = z.object({
date: z.string(), // 什么格式?
amount: z.number(), // 什么单位?
});
// ✅ 解决方案:添加描述
const schema = z.object({
date: z.string().describe("YYYY-MM-DD 格式的日期"),
amount: z.number().describe("美元金额"),
});
// ❌ 问题:对模型来说太严格
const schema = z.object({
code: z.string().regex(/^[A-Z]{2}-\d{4}-[A-Z]{3}$/), // 太具体!
});
// ✅ 解决方案:后处理验证或使用更宽松的模式
const schema = z.object({
code: z.string().describe("格式:XX-0000-XXX(字母和数字)"),
});
// ❌ 问题:没有错误处理
const result = await agent.invoke(input);
const data = result.structuredResponse; // 可能抛出异常!
// ✅ 解决方案:try/catch 或检查错误
try {
const result = await agent.invoke(input);
const data = result.structuredResponse;
} catch (error) {
console.error("获取结构化输出失败:", error);
}
// ❌ 问题:错误地使用 responseFormat 和 tools
const agent = createAgent({
model: "gpt-4.1",
tools: [searchTool],
responseFormat: MySchema, // 仅从最终响应中提取
});
// 工具先运行,然后从最终响应中提取模式
// ✅ 如果您需要工具 + 结构化最终输出,这是正确的
// 只需理解这个流程