langchain.js
    Preparing search index...

    Function toolStrategy

    Creates a tool strategy for structured output using function calling.

    This function configures structured output by converting schemas into function tools that the model calls. Unlike providerStrategy, which uses native JSON schema support, toolStrategy works with any model that supports function calling, making it more widely compatible across providers and model versions.

    The model will call a function with arguments matching your schema, and the agent will extract and validate the structured output from the tool call. This approach is automatically used when your model doesn't support native JSON schema output.

    The schema(s) to enforce. Can be a single Zod schema, an array of Zod schemas, a JSON schema object, or an array of JSON schema objects.

    Optional configuration for the tool strategy

    How to handle errors when the model calls multiple structured output tools or when the output doesn't match the schema. Defaults to true (auto-retry). Can be false (throw), a string (retry with message), or a function (custom handler).

    Custom message content to include in conversation history when structured output is generated via tool call

    A TypedToolStrategy instance that can be used as the responseFormat in createAgent

    import { toolStrategy, createAgent } from "langchain";
    import { z } from "zod";

    const agent = createAgent({
    model: "claude-haiku-4-5",
    responseFormat: toolStrategy(
    z.object({
    answer: z.string(),
    confidence: z.number().min(0).max(1),
    })
    ),
    });
    // Multiple schemas - model can choose which one to use
    const agent = createAgent({
    model: "claude-haiku-4-5",
    responseFormat: toolStrategy([
    z.object({ name: z.string(), age: z.number() }),
    z.object({ email: z.string(), phone: z.string() }),
    ]),
    });
    • Type Parameters

      • T extends InteropZodType<any>

      Parameters

      • responseFormat: T
      • Optionaloptions: ToolStrategyOptions

      Returns TypedToolStrategy<T extends InteropZodType<U> ? U : never>

    • Type Parameters

      • T extends readonly InteropZodType<any>[]

      Parameters

      • responseFormat: T
      • Optionaloptions: ToolStrategyOptions

      Returns TypedToolStrategy<
          {
              [K in string
              | number
              | symbol]: T[K<K>] extends InteropZodType<U> ? U : never
          }[number],
      >

    • Parameters

      • responseFormat: JsonSchemaFormat
      • Optionaloptions: ToolStrategyOptions

      Returns TypedToolStrategy<Record<string, unknown>>

    • Parameters

      • responseFormat: JsonSchemaFormat[]
      • Optionaloptions: ToolStrategyOptions

      Returns TypedToolStrategy<Record<string, unknown>>