langchain
Version:
Typescript bindings for langchain
167 lines (165 loc) • 7.29 kB
text/typescript
import { MultipleStructuredOutputsError, StructuredOutputParsingError } from "./errors.cjs";
import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
import { AIMessage } from "@langchain/core/messages";
import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
//#region src/agents/responses.d.ts
/**
* Special type to indicate that no response format is provided.
* When this type is used, the structuredResponse property should not be present in the result.
*/
type ResponseFormatUndefined = {
__responseFormatUndefined: true;
};
/**
* Information for tracking structured output tool metadata.
* This contains all necessary information to handle structured responses generated
* via tool calls, including the original schema, its type classification, and the
* corresponding tool implementation used by the tools strategy.
*/
declare class ToolStrategy<_T = unknown> {
readonly schema: Record<string, unknown>;
readonly tool: {
type: "function";
function: FunctionDefinition;
};
readonly options?: ToolStrategyOptions | undefined;
private constructor();
get name(): string;
static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;
static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;
/**
* Parse tool arguments according to the schema.
*
* @throws {StructuredOutputParsingError} if the response is not valid
* @param toolArgs - The arguments from the tool call
* @returns The parsed response according to the schema type
*/
parse(toolArgs: Record<string, unknown>): Record<string, unknown>;
}
declare class ProviderStrategy<T = unknown> {
private _schemaType?;
/**
* The schema to use for the provider strategy
*/
readonly schema: Record<string, unknown>;
/**
* Whether to use strict mode for the provider strategy
*/
readonly strict: boolean;
private constructor();
private constructor();
static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;
static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;
/**
* Parse tool arguments according to the schema. If the response is not valid, return undefined.
*
* @param response - The AI message response to parse
* @returns The parsed response according to the schema type
*/
parse(response: AIMessage): any;
}
type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;
/**
* Branded type for ToolStrategy arrays that preserves type information
*/
interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {
_schemaType?: T;
}
type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;
interface ToolStrategyOptions {
/**
* Allows you to customize the message that appears in the conversation history when structured
* output is generated.
*/
toolMessageContent?: string;
/**
* Handle errors from the structured output tool call. Using tools to generate structured output
* can cause errors, e.g. if:
* - you provide multiple structured output schemas and the model calls multiple structured output tools
* - if the structured output generated by the tool call doesn't match provided schema
*
* This property allows to handle these errors in different ways:
* - `true` - retry the tool call
* - `false` - throw an error
* - `string` - retry the tool call with the provided message
* - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error
*
* @default true
*/
handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);
}
declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;
declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{ [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]>;
declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;
/**
* Creates a provider strategy for structured output using native JSON schema support.
*
* This function is used to configure structured output for agents when the underlying model
* supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).
* Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`
* leverages the provider's native structured output capabilities, resulting in more efficient
* and reliable schema enforcement.
*
* When used with a model that supports JSON schema output, the model will return responses
* that directly conform to the provided schema without requiring tool calls. This is the
* recommended approach for structured output when your model supports it.
*
* @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag
* @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`
*
* @example
* ```ts
* import { providerStrategy, createAgent } from "langchain";
* import { z } from "zod";
*
* const agent = createAgent({
* model: "claude-haiku-4-5",
* responseFormat: providerStrategy(
* z.object({
* answer: z.string().describe("The answer to the question"),
* confidence: z.number().min(0).max(1),
* })
* ),
* });
* ```
*
* @example
* ```ts
* // Using strict mode for stricter schema enforcement
* const agent = createAgent({
* model: "claude-haiku-4-5",
* responseFormat: providerStrategy({
* schema: z.object({
* name: z.string(),
* age: z.number(),
* }),
* strict: true
* }),
* });
* ```
*/
declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {
schema: T;
strict?: boolean;
}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;
declare function providerStrategy(responseFormat: JsonSchemaFormat | {
schema: JsonSchemaFormat;
strict?: boolean;
}): ProviderStrategy<Record<string, unknown>>;
/**
* Type representing a JSON Schema object format.
* This is a strict type that excludes ToolStrategy and ProviderStrategy instances.
*/
type JsonSchemaFormat = {
type: "null" | "boolean" | "object" | "array" | "number" | "string" | "integer";
properties?: Record<string, unknown>;
required?: string[];
additionalProperties?: boolean;
[key: string]: unknown;
} & {
__brand?: never;
};
//#endregion
export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
//# sourceMappingURL=responses.d.cts.map