-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
Feedback: Clarify Zod Schema Example in withStructuredOutput
Usage
When following the LangChain documentation example for using withStructuredOutput
with a Zod schema, the current example can cause a TypeScript error.
Problem
The docs currently show something like:
const modelWithStructure = model.withStructuredOutput(ResponseFormatter);
This can throw the following TypeScript error:
Type instantiation is excessively deep and possibly infinite.
const modelWithStructure = model.withStructuredOutput(ResponseFormatter);
Cause
TypeScript’s type inference struggles with deeply nested Zod schemas, causing excessive type instantiation during inference.
Fix
Adding an explicit generic type argument resolves the issue:
const modelWithStructure = model.withStructuredOutput<typeof ResponseFormatter>(ResponseFormatter);
This ensures TypeScript correctly infers the type from the Zod schema and prevents the infinite type instantiation error.
Suggested Documentation Update
Update the withStructuredOutput
+ Zod schema example to include the generic type argument, or add a note explaining that TypeScript users should include the explicit type for complex schemas.
Example revised snippet:
// ✅ Recommended version
const modelWithStructure = model.withStructuredOutput<typeof ResponseFormatter>(ResponseFormatter);
Explanation:
Including <typeof ResponseFormatter>
helps TypeScript properly infer schema types and avoids “Type instantiation is excessively deep and possibly infinite” errors with complex Zod schemas.