import { ResponseFormatUndefined } from "./responses.js"; import { InvokeConfiguration, StreamConfiguration } from "./runtime.js"; import { AgentMiddleware, AnyAnnotationRoot, InferContextInput, InferMiddlewareContextInputs, InferMiddlewareInputStates, InferMiddlewareStates, InferSchemaValue, ToAnnotationRoot } from "./middleware/types.js"; import { AgentTypeConfig, BuiltInState, CreateAgentParams, ToolsToMessageToolSet, UserInput } from "./types.js"; import { AgentRunStream, InferStreamExtensions } from "./stream.js"; import { MessageStructure } from "@langchain/core/messages"; import { Runnable, RunnableConfig } from "@langchain/core/runnables"; import { IterableReadableStream } from "@langchain/core/utils/stream"; import { ClientTool, ServerTool } from "@langchain/core/tools"; import { Command, CompiledStateGraph, GetStateOptions, LangGraphRunnableConfig, StateGraph, StreamMode, StreamOutputMap, StreamTransformer } from "@langchain/langgraph"; import { InteropZodObject } from "@langchain/core/utils/types"; import { BaseCheckpointSaver, BaseStore, CheckpointListOptions } from "@langchain/langgraph-checkpoint"; import { StreamEvent } from "@langchain/core/tracers/log_stream"; //#region src/agents/ReactAgent.d.ts type MergedAgentState = InferSchemaValue & (Types["Response"] extends ResponseFormatUndefined ? Omit>>, "jumpTo"> : Omit>>, "jumpTo"> & { structuredResponse: Types["Response"]; }) & InferMiddlewareStates; type InvokeStateParameter = (UserInput & InferMiddlewareInputStates) | Command | null; type AgentGraph = CompiledStateGraph, ToAnnotationRoot["spec"], unknown>; /** * ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines * language models with tools and middleware. * * The agent is parameterized by a single type bag `Types` that encapsulates all * type information: * * @typeParam Types - An {@link AgentTypeConfig} that bundles: * - `Response`: The structured response type * - `State`: The custom state schema type * - `Context`: The context schema type * - `Middleware`: The middleware array type * - `Tools`: The combined tools type from agent and middleware * * @example * ```typescript * // Using the type bag pattern * type MyTypes = AgentTypeConfig< * { name: string }, // Response * typeof myState, // State * typeof myContext, // Context * typeof middleware, // Middleware * typeof tools // Tools * >; * * const agent: ReactAgent = createAgent({ ... }); * ``` */ declare class ReactAgent, undefined, AnyAnnotationRoot, readonly AgentMiddleware[], readonly (ClientTool | ServerTool)[], ReadonlyArray<() => StreamTransformer>>> { #private; options: CreateAgentParams; /** * Type marker for extracting the AgentTypeConfig from a ReactAgent instance. * This is a phantom property used only for type inference. * @internal */ readonly "~agentTypes": Types; constructor(options: CreateAgentParams, defaultConfig?: RunnableConfig); /** * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}. */ get graph(): AgentGraph; get checkpointer(): BaseCheckpointSaver | boolean | undefined; set checkpointer(value: BaseCheckpointSaver | boolean | undefined); get store(): BaseStore | undefined; set store(value: BaseStore | undefined); /** * Creates a new ReactAgent with the given config merged into the existing config. * Follows the same pattern as LangGraph's Pregel.withConfig(). * * The merged config is applied as a default that gets merged with any config * passed at invocation time (invoke/stream). Invocation-time config takes precedence. * * @param config - Configuration to merge with existing config * @returns A new ReactAgent instance with the merged configuration * * @example * ```typescript * const agent = createAgent({ model: "gpt-4o", tools: [...] }); * * // Set a default recursion limit * const configuredAgent = agent.withConfig({ recursionLimit: 1000 }); * * // Chain multiple configs * const debugAgent = agent * .withConfig({ recursionLimit: 1000 }) * .withConfig({ tags: ["debug"] }); * ``` */ withConfig(config: Omit): ReactAgent; /** * Executes the agent with the given state and returns the final state after all processing. * * This method runs the agent's entire workflow synchronously, including: * - Processing the input messages through any configured middleware * - Calling the language model to generate responses * - Executing any tool calls made by the model * - Running all middleware hooks (beforeModel, afterModel, etc.) * * @param state - The initial state for the agent execution. Can be: * - An object containing `messages` array and any middleware-specific state properties * - A Command object for more advanced control flow * * @param config - Optional runtime configuration including: * @param config.context - The context for the agent execution. * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}. * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution. * @param config.recursionLimit - The recursion limit for the agent execution. * * @returns A Promise that resolves to the final agent state after execution completes. * The returned state includes: * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results) * - a `structuredResponse` property containing the structured response (if configured) * - all state values defined in the middleware * * @example * ```typescript * const agent = new ReactAgent({ * llm: myModel, * tools: [calculator, webSearch], * responseFormat: z.object({ * weather: z.string(), * }), * }); * * const result = await agent.invoke({ * messages: [{ role: "human", content: "What's the weather in Paris?" }] * }); * * console.log(result.structuredResponse.weather); // outputs: "It's sunny and 75°F." * ``` */ invoke(state: InvokeStateParameter, config?: InvokeConfiguration & InferMiddlewareContextInputs>): Promise>; /** * Executes the agent with streaming, returning an async iterable of state updates as they occur. * * This method runs the agent's workflow similar to `invoke`, but instead of waiting for * completion, it streams high-level state updates in real-time. This allows you to: * - Display intermediate results to users as they're generated * - Monitor the agent's progress through each step * - React to state changes as nodes complete * * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead. * * @param state - The initial state for the agent execution. Can be: * - An object containing `messages` array and any middleware-specific state properties * - A Command object for more advanced control flow * * @param config - Optional runtime configuration including: * @param config.context - The context for the agent execution. * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}. * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution. * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}. * @param config.recursionLimit - The recursion limit for the agent execution. * * @returns A Promise that resolves to an IterableReadableStream of state updates. * Each update contains the current state after a node completes. * * @example * ```typescript * const agent = new ReactAgent({ * llm: myModel, * tools: [calculator, webSearch] * }); * * const stream = await agent.stream({ * messages: [{ role: "human", content: "What's 2+2 and the weather in NYC?" }] * }); * * for await (const chunk of stream) { * console.log(chunk); // State update from each node * } * ``` */ stream(state: InvokeStateParameter, config?: StreamConfiguration & InferMiddlewareContextInputs, TStreamMode, TSubgraphs, TEncoding>): Promise, MergedAgentState, string, unknown, unknown, TEncoding>>>; /** * Executes the agent with the v3 streaming interface, returning an * {@link AgentRunStream} that provides ergonomic, typed projections for * messages, tool calls, and middleware events — without requiring knowledge * of Pregel channels, stream modes, or namespace routing. * * Pass `version: "v3"` to opt into this projection-oriented stream. Omitting * `version` preserves the legacy internal LangGraph event-stream behavior * for compatibility with LangGraph Platform integrations. * * This v3 stream is experimental and its API may change in future releases. * It will become the default in a future major release. * * @param state - The initial state for the agent execution. Can be: * - An object containing `messages` array and any middleware-specific state properties * - A Command object for more advanced control flow * * @param config - Runtime configuration including: * @param config.version - Must be `"v3"` to use the {@link AgentRunStream} * interface. The default legacy event stream is maintained for internal * integrations and should not be used for new user-facing agent streaming. * @param config.context - The context for the agent execution. * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. * @param config.store - The store for the agent execution for persisting state. * @param config.signal - An optional AbortSignal for the agent execution. * @param config.recursionLimit - The recursion limit for the agent execution. * @param config.transformers - Additional call-site stream transformers. These * run after the built-in agent transformers and any transformers registered * at creation time via `createAgent({ streamTransformers })`. * * @returns A Promise that resolves to an {@link AgentRunStream} providing: * - `run.messages` — all AI message lifecycles with streaming `.text` and `.reasoning` * - `run.toolCalls` — individual tool call streams with `.input`, `.output`, `.status` * - `run.middleware` — middleware lifecycle events (before/after agent/model) * - `run.values` — state snapshots (async iterable + promise-like) * - `run.output` — final agent state when the run completes * - `run.subgraphs` — child subgraph run streams * - `run.extensions` — merged projections from user-supplied transformers * * @example * ```typescript * const run = await agent.streamEvents( * { * messages: [{ role: "user", content: "What's the weather in Paris?" }], * }, * { version: "v3" } * ); * * // Stream all messages * for await (const msg of run.messages) { * for await (const token of msg.text) { * process.stdout.write(token); * } * } * * // Observe tool calls * for await (const call of run.toolCalls) { * console.log(`Tool: ${call.name}`, call.input); * console.log(`Result:`, await call.output); * } * * // Get final state * const state = await run.output; * ``` */ streamEvents(state: InvokeStateParameter, config: InvokeConfiguration & InferMiddlewareContextInputs> & { version: "v3"; transformers?: ReadonlyArray<() => StreamTransformer>; }): Promise, Types["Tools"], InferStreamExtensions>>; streamEvents(state: InvokeStateParameter, config?: StreamConfiguration & InferMiddlewareContextInputs, StreamMode | StreamMode[] | undefined, boolean, "text/event-stream" | undefined> & { version?: "v1" | "v2"; }, streamOptions?: Parameters[2]): IterableReadableStream; streamEvents(state: InvokeStateParameter, config: (StreamConfiguration & InferMiddlewareContextInputs, StreamMode | StreamMode[] | undefined, boolean, "text/event-stream" | undefined> & { version?: "v1" | "v2"; }) | undefined, streamOptions: Parameters[2]): IterableReadableStream; /** * Visualize the graph as a PNG image. * @param params - Parameters for the drawMermaidPng method. * @param params.withStyles - Whether to include styles in the graph. * @param params.curveStyle - The style of the graph's curves. * @param params.nodeColors - The colors of the graph's nodes. * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label. * @param params.backgroundColor - The background color of the graph. * @returns PNG image as a buffer */ drawMermaidPng(params?: { withStyles?: boolean; curveStyle?: string; nodeColors?: Record; wrapLabelNWords?: number; backgroundColor?: string; }): Promise>; /** * Draw the graph as a Mermaid string. * @param params - Parameters for the drawMermaid method. * @param params.withStyles - Whether to include styles in the graph. * @param params.curveStyle - The style of the graph's curves. * @param params.nodeColors - The colors of the graph's nodes. * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label. * @param params.backgroundColor - The background color of the graph. * @returns Mermaid string */ drawMermaid(params?: { withStyles?: boolean; curveStyle?: string; nodeColors?: Record; wrapLabelNWords?: number; backgroundColor?: string; }): Promise; /** * The following are internal methods to enable support for LangGraph Platform. * They are not part of the createAgent public API. * * Note: we intentionally return as `never` to avoid type errors due to type inference. */ /** * @internal */ getGraphAsync(config?: RunnableConfig): never; /** * @internal */ getState(config: RunnableConfig, options?: GetStateOptions): never; /** * @internal */ getStateHistory(config: RunnableConfig, options?: CheckpointListOptions): never; /** * @internal */ getSubgraphs(namespace?: string, recurse?: boolean): never; /** * @internal */ getSubgraphsAsync(namespace?: string, recurse?: boolean): never; /** * @internal */ updateState(inputConfig: LangGraphRunnableConfig, values: Record | unknown, asNode?: string): never; /** * @internal */ get builder(): StateGraph; } //#endregion export { ReactAgent }; //# sourceMappingURL=ReactAgent.d.ts.map