Skip to content

DOC: <Issue related to /docs/concepts/structured_outputs/> #9115

@kaleabteweld

Description

@kaleabteweld

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions