Structured output 允许 agents 以特定且可预测的格式返回数据。你无需解析自然语言响应,而是可以获得带类型的结构化数据。
本页介绍如何通过 createAgent 在 agents 中使用 structured output。如需直接在模型上使用 structured output(在 agents 之外),请参阅 Models - Structured output
LangChain 的预构建 ReAct agent createAgent 会自动处理 structured output。用户设置所需的 structured output schema,当模型生成结构化数据时,数据会被捕获、验证,并在 agent state 的 structuredResponse key 中返回。
type ResponseFormat = (
    | ZodSchema<StructuredResponseT> // a Zod schema
    | StandardSchema<StructuredResponseT> // any Standard Schema library
    | Record<string, unknown> // a JSON Schema
)

const agent = createAgent({
    // ...
    responseFormat: ResponseFormat | ResponseFormat[]
})

Response format

控制 agent 如何返回结构化数据。你可以提供 Zod schema、任何兼容 Standard Schema 的 schema,或 JSON Schema object。默认情况下,agent 使用 tool calling strategy,即通过额外的工具调用创建输出。某些模型支持原生 structured output,在这种情况下 agent 会改用该策略。 可以通过用 toolStrategyproviderStrategy 函数调用包装 ResponseFormat 来控制行为:
import { toolStrategy, providerStrategy } from "langchain";

const agent = createAgent({
    // use a provider strategy if supported by the model
    responseFormat: providerStrategy(z.object({ ... }))
    // or enforce a tool strategy
    responseFormat: toolStrategy(z.object({ ... }))
})
结构化响应会在 agent 最终 state 的 structuredResponse key 中返回。
如果使用 langchain>=1.1,对原生 structured output 功能的支持会从模型的 profile data 中动态读取。如果数据不可用,请使用其他条件或手动指定:
const customProfile: ModelProfile = {
    structuredOutput: true,
    // ...
}
const model = await initChatModel("...", { profile: customProfile });
如果指定了 tools,模型必须支持同时使用 tools 和 structured output。

Provider strategy

一些 model providers 通过其 APIs 原生支持 structured output,例如 OpenAI、xAI (Grok)、Gemini、Anthropic (Claude)。如果可用,这是最可靠的方法。 如需使用该策略,请配置 ProviderStrategy
function providerStrategy<StructuredResponseT>(
    schema: ZodSchema<StructuredResponseT> | SerializableSchema | JsonSchemaFormat
): ProviderStrategy<StructuredResponseT>
schema
required
定义 structured output 格式的 schema。支持:
  • Zod Schema:zod schema
  • Standard Schema:实现 Standard Schema 规范的任何 schema
  • JSON Schema:JSON schema object
当你将 schema 类型直接传给 createAgent.responseFormat,且模型支持原生 structured output 时,LangChain 会自动使用 ProviderStrategy
import * as z from "zod";
import { createAgent, providerStrategy } from "langchain";

const ContactInfo = z.object({
    name: z.string().describe("The name of the person"),
    email: z.string().describe("The email address of the person"),
    phone: z.string().describe("The phone number of the person"),
});

const agent = createAgent({
    model: "gpt-5.4",
    tools: [],
    responseFormat: providerStrategy(ContactInfo)
});

const result = await agent.invoke({
    messages: [{"role": "user", "content": "Extract contact info from: John Doe, john@example.com, (555) 123-4567"}]
});

console.log(result.structuredResponse);
// { name: "John Doe", email: "john@example.com", phone: "(555) 123-4567" }
Provider-native structured output 由模型 provider 强制执行 schema,因此可靠性高且验证严格。可用时请优先使用。
如果 provider 对你选择的模型原生支持 structured output,写 responseFormat: contactInfoSchema 与写 responseFormat: providerStrategy(contactInfoSchema) 在功能上等价。无论哪种写法,如果不支持 structured output,agent 都会 fallback 到 tool calling strategy。

Tool calling strategy

对于不支持原生 structured output 的模型,LangChain 使用 tool calling 实现相同结果。这适用于所有支持 tool calling 的模型(大多数现代模型)。 如需使用该策略,请配置 ToolStrategy
function toolStrategy<StructuredResponseT>(
    responseFormat:
        | JsonSchemaFormat
        | ZodSchema<StructuredResponseT>
        | SerializableSchema
        | (ZodSchema<StructuredResponseT> | SerializableSchema | JsonSchemaFormat)[]
    options?: ToolStrategyOptions
): ToolStrategy<StructuredResponseT>
schema
required
定义 structured output 格式的 schema。支持:
  • Zod Schema:zod schema
  • Standard Schema:实现 Standard Schema 规范的任何 schema
  • JSON Schema:JSON schema object
options.toolMessageContent
生成 structured output 时返回的 tool message 的自定义内容。 如果未提供,默认使用显示结构化响应数据的 message。
options.handleError
Options 参数包含可选的 handleError 参数,用于自定义错误处理策略。
  • true:使用默认错误模板捕获所有错误(默认)
  • False:不重试,让异常继续抛出
  • (error: ToolStrategyError) => string | Promise<string>:使用提供的 message 重试,或抛出错误
import * as z from "zod";
import { createAgent, toolStrategy } from "langchain";

const ProductReview = z.object({
    rating: z.number().min(1).max(5).optional(),
    sentiment: z.enum(["positive", "negative"]),
    keyPoints: z.array(z.string()).describe("The key points of the review. Lowercase, 1-3 words each."),
});

const agent = createAgent({
    model: "gpt-5.4",
    tools: [],
    responseFormat: toolStrategy(ProductReview)
})

const result = await agent.invoke({
    "messages": [{"role": "user", "content": "Analyze this review: 'Great product: 5 out of 5 stars. Fast shipping, but expensive'"}]
})

console.log(result.structuredResponse);
// { "rating": 5, "sentiment": "positive", "keyPoints": ["fast shipping", "expensive"] }

Custom tool message content

toolMessageContent 参数允许你自定义生成 structured output 时出现在对话历史中的 message:
import * as z from "zod";
import { createAgent, toolStrategy } from "langchain";

const MeetingAction = z.object({
    task: z.string().describe("The specific task to be completed"),
    assignee: z.string().describe("Person responsible for the task"),
    priority: z.enum(["low", "medium", "high"]).describe("Priority level"),
});

const agent = createAgent({
    model: "gpt-5.4",
    tools: [],
    responseFormat: toolStrategy(MeetingAction, {
        toolMessageContent: "Action item captured and added to meeting notes!"
    })
});

const result = await agent.invoke({
    messages: [{"role": "user", "content": "From our meeting: Sarah needs to update the project timeline as soon as possible"}]
});

console.log(result);
/**
 * {
 *   messages: [
 *     { role: "user", content: "From our meeting: Sarah needs to update the project timeline as soon as possible" },
 *     { role: "assistant", content: "Action item captured and added to meeting notes!", tool_calls: [ { name: "MeetingAction", args: { task: "update the project timeline", assignee: "Sarah", priority: "high" }, id: "call_456" } ] },
 *     { role: "tool", content: "Action item captured and added to meeting notes!", tool_call_id: "call_456", name: "MeetingAction" }
 *   ],
 *   structuredResponse: { task: "update the project timeline", assignee: "Sarah", priority: "high" }
 * }
 */
如果没有 toolMessageContent,会看到:
# console.log(result);
/**
 * {
 *   messages: [
 *     ...
 *     { role: "tool", content: "Returning structured response: {'task': 'update the project timeline', 'assignee': 'Sarah', 'priority': 'high'}", tool_call_id: "call_456", name: "MeetingAction" }
 *   ],
 *   structuredResponse: { task: "update the project timeline", assignee: "Sarah", priority: "high" }
 * }
 */

Error handling

Models 通过 tool calling 生成 structured output 时可能出错。LangChain 提供智能重试机制来自动处理这些错误。

Multiple structured outputs error

当模型错误地调用多个 structured output tools 时,agent 会在 ToolMessage 中提供错误反馈,并提示模型重试:
import * as z from "zod";
import { createAgent, toolStrategy } from "langchain";

const ContactInfo = z.object({
    name: z.string().describe("Person's name"),
    email: z.string().describe("Email address"),
});

const EventDetails = z.object({
    event_name: z.string().describe("Name of the event"),
    date: z.string().describe("Event date"),
});

const agent = createAgent({
    model: "gpt-5.4",
    tools: [],
    responseFormat: toolStrategy([ContactInfo, EventDetails]),
});

const result = await agent.invoke({
    messages: [
        {
        role: "user",
        content:
            "Extract info: John Doe (john@email.com) is organizing Tech Conference on March 15th",
        },
    ],
});

console.log(result);

/**
 * {
 *   messages: [
 *     { role: "user", content: "Extract info: John Doe (john@email.com) is organizing Tech Conference on March 15th" },
 *     { role: "assistant", content: "", tool_calls: [ { name: "ContactInfo", args: { name: "John Doe", email: "john@email.com" }, id: "call_1" }, { name: "EventDetails", args: { event_name: "Tech Conference", date: "March 15th" }, id: "call_2" } ] },
 *     { role: "tool", content: "Error: Model incorrectly returned multiple structured responses (ContactInfo, EventDetails) when only one is expected.\n Please fix your mistakes.", tool_call_id: "call_1", name: "ContactInfo" },
 *     { role: "tool", content: "Error: Model incorrectly returned multiple structured responses (ContactInfo, EventDetails) when only one is expected.\n Please fix your mistakes.", tool_call_id: "call_2", name: "EventDetails" },
 *     { role: "assistant", content: "", tool_calls: [ { name: "ContactInfo", args: { name: "John Doe", email: "john@email.com" }, id: "call_3" } ] },
 *     { role: "tool", content: "Returning structured response: {'name': 'John Doe', 'email': 'john@email.com'}", tool_call_id: "call_3", name: "ContactInfo" }
 *   ],
 *   structuredResponse: { name: "John Doe", email: "john@email.com" }
 * }
 */

Schema validation error

当 structured output 与预期 schema 不匹配时,agent 会提供具体错误反馈:
import * as z from "zod";
import { createAgent, toolStrategy } from "langchain";

const ProductRating = z.object({
    rating: z.number().min(1).max(5).describe("Rating from 1-5"),
    comment: z.string().describe("Review comment"),
});

const agent = createAgent({
    model: "gpt-5.4",
    tools: [],
    responseFormat: toolStrategy(ProductRating),
});

const result = await agent.invoke({
    messages: [
        {
        role: "user",
        content: "Parse this: Amazing product, 10/10!",
        },
    ],
});

console.log(result);

/**
 * {
 *   messages: [
 *     { role: "user", content: "Parse this: Amazing product, 10/10!" },
 *     { role: "assistant", content: "", tool_calls: [ { name: "ProductRating", args: { rating: 10, comment: "Amazing product" }, id: "call_1" } ] },
 *     { role: "tool", content: "Error: Failed to parse structured output for tool 'ProductRating': 1 validation error for ProductRating\nrating\n  Input should be less than or equal to 5 [type=less_than_equal, input_value=10, input_type=int].\n Please fix your mistakes.", tool_call_id: "call_1", name: "ProductRating" },
 *     { role: "assistant", content: "", tool_calls: [ { name: "ProductRating", args: { rating: 5, comment: "Amazing product" }, id: "call_2" } ] },
 *     { role: "tool", content: "Returning structured response: {'rating': 5, 'comment': 'Amazing product'}", tool_call_id: "call_2", name: "ProductRating" }
 *   ],
 *   structuredResponse: { rating: 5, comment: "Amazing product" }
 * }
 */

Error handling strategies

可以使用 handleErrors 参数自定义错误处理方式: 自定义错误 message:
const responseFormat = toolStrategy(ProductRating, {
    handleError: "Please provide a valid rating between 1-5 and include a comment."
)

// 错误 message 变为:
// { role: "tool", content: "Please provide a valid rating between 1-5 and include a comment." }
仅处理特定异常:
import { ToolInputParsingException } from "@langchain/core/tools";

const responseFormat = toolStrategy(ProductRating, {
    handleError: (error: ToolStrategyError) => {
        if (error instanceof ToolInputParsingException) {
        return "Please provide a valid rating between 1-5 and include a comment.";
        }
        return error.message;
    }
)

// 只有验证错误会使用默认 message 重试:
// { role: "tool", content: "Error: Failed to parse structured output for tool 'ProductRating': ...\n Please fix your mistakes." }
处理多个异常类型:
const responseFormat = toolStrategy(ProductRating, {
    handleError: (error: ToolStrategyError) => {
        if (error instanceof ToolInputParsingException) {
        return "Please provide a valid rating between 1-5 and include a comment.";
        }
        if (error instanceof CustomUserError) {
        return "This is a custom user error.";
        }
        return error.message;
    }
)
不处理错误:
const responseFormat = toolStrategy(ProductRating, {
    handleError: false  // All errors raised
)