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({ ... }))})
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", tools: 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"}]});result.structuredResponse;// { name: "John Doe", email: "john@example.com", phone: "(555) 123-4567" }
提供商本地结构化输出提供高可靠性和严格验证,因为模型提供商强制执行模式。在可用时使用它。
If the provider natively supports structured output for your model choice, it is functionally equivalent to write responseFormat: contactInfoSchema instead of responseFormat: toolStrategy(contactInfoSchema). In either case, if structured output is not supported, the agent will fall back to a tool calling strategy.
Custom content for the tool message returned when structured output is generated.
If not provided, defaults to a message showing the structured response data.
Models can make mistakes when generating structured output via tool calling. LangChain provides intelligent retry mechanisms to handle these errors automatically.
You can customize how errors are handled using the handleErrors parameter:Custom error message:
Copy
const responseFormat = toolStrategy(ProductRating, { handleError: "Please provide a valid rating between 1-5 and include a comment.")// Error message becomes:// { role: "tool", content: "Please provide a valid rating between 1-5 and include a comment." }
Handle specific exceptions only:
Copy
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; })// Only validation errors get retried with default message:// { role: "tool", content: "Error: Failed to parse structured output for tool 'ProductRating': ...\n Please fix your mistakes." }
Handle multiple exception types:
Copy
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; })