langchain-structured-output
使用 Zod 模式、类型安全响应和自动验证从 LangChain 代理和模型获取结构化的验证输出
npx skills add majiayu000/claude-skill-registry --skill langchain-structured-output --agent claude-code
Same command for any agent — swap --agent for codex, cursor, copilot.
Weekly change comes from our own snapshots, not the repository page — it measures attention, not adoption.
# langchain-structured-output (JavaScript/TypeScript) ## 概述 结构化输出将非结构化的模型响应转换为经过验证的、类型化的数据。不是解析自由文本,而是获得符合您模式的 JSON 对象——非常适合数据提取、构建表单或与下游系统集成。 **核心概念:** - **responseFormat**:定义预期的输出模式 - **Zod 验证**:具有自动验证的类型安全模式 - **withStructuredOutput()**:用于直接结构化输出的模型方法 - **工具策略**:对于不支持原生功能的模型,底层使用工具调用 ## 决策表 ### 何时使用结构化输出 | 使用场景 | 使用结构化输出? | 原因 | |----------|------------------|------| | 提取联系信息、日期等 | ✅ 是 | 可靠的数据提取 | | 表单填写 | ✅ 是 | 验证所有必填字段 | | API 集成 | ✅ 是 | 类型安全的响应 | | 分类任务 | ✅ 是 | 枚举验证 | | 开放式问答 | ❌ 否 | 自由文本即可 | | 创意写作 | ❌ 否 | 不要限制创造力 | ### 模式选项 | 模式类型 | 使用时机 | 示例 | |---------|---------|------| | Zod 模式 | TypeScript 项目(推荐) | `z.object({...})` | | JSON 模式 | 互操作性 | `{ type: "object", properties: {...} }` | | 联合类型 | 多种可能的格式 | `z.union([schema1, schema2])` | ## 代码示例 ### 使用代理的基本结构化输出 ```typescript 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)
- 概述
- 决策表
- 何时使用结构化输出
- 模式选项
- 代码示例
- 使用代理的基本结构化输出
- 模型直接结构化输出
- 复杂嵌套模式
- 枚举和字面量类型
- 可选字段和默认值
- 联合类型(多种模式)
- 数组提取
- 包含原始 AIMessage
- 错误处理
What does the langchain-structured-output skill do?
使用 Zod 模式、类型安全响应和自动验证从 LangChain 代理和模型获取结构化的验证输出
How do I install it?
Run `npx skills add majiayu000/claude-skill-registry --skill langchain-structured-output --agent claude-code` — it drops the skill into your project so the agent can pick it up. Swap the --agent value for codex, cursor or copilot if you use one of those.
Where does this skill come from?
From majiayu000/claude-skill-registry, a repository with 534 stars. We read it straight from the repository tree rather than a submitted listing, so what you see here is what is actually published.
Is a popular skill a good skill?
Not necessarily. Stars measure attention, not adoption — a repository can trend for a week and be abandoned. That is why we show the weekly change from our own snapshots next to the total, instead of a single flattering number.
