langchain.js
    Preparing search index...

    Interface ReactAgent<Types>

    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:

    // 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<MyTypes> = createAgent({ ... });
    interface ReactAgent<
        Types extends
            AgentTypeConfig = AgentTypeConfig<
            Record<string, any>,
            undefined,
            AnyAnnotationRoot,
            readonly AgentMiddleware[],
            readonly (BaseMessage | BaseMessage)[],
        >,
    > {
        options: CreateAgentParams<
            Types["Response"],
            Types["State"],
            Types["Context"],
        >;
        get graph(): AgentGraph<Types>;
        drawMermaid(
            params?: {
                backgroundColor?: string;
                curveStyle?: string;
                nodeColors?: Record<string, string>;
                withStyles?: boolean;
                wrapLabelNWords?: number;
            },
        ): Promise<any>;
        drawMermaidPng(
            params?: {
                backgroundColor?: string;
                curveStyle?: string;
                nodeColors?: Record<string, string>;
                withStyles?: boolean;
                wrapLabelNWords?: number;
            },
        ): Promise<Uint8Array<any>>;
        invoke(
            state: InvokeStateParameter<Types>,
            config?: any,
        ): Promise<MergedAgentState<Types>>;
        stream<
            TStreamMode extends undefined
            | StreamMode
            | StreamMode[],
            TSubgraphs extends boolean,
            TEncoding extends undefined | "text/event-stream",
        >(
            state: InvokeStateParameter<Types>,
            config?: any,
        ): Promise<
            IterableReadableStream<
                StreamOutputMap<
                    TStreamMode,
                    TSubgraphs,
                    MergedAgentState<Types>,
                    MergedAgentState<Types>,
                    string,
                    unknown,
                    unknown,
                    TEncoding,
                >,
            >,
        >;
        withConfig(
            config: Omit<BaseMessage, "store" | "writer" | "interrupt">,
        ): ReactAgent<Types>;
    }

    Type Parameters

    Index

    Properties

    options: CreateAgentParams<Types["Response"], Types["State"], Types["Context"]>

    Accessors

    • get graph(): AgentGraph<Types>

      Get the compiled StateGraph.

      Returns AgentGraph<Types>

    Methods

    • Draw the graph as a Mermaid string.

      Parameters

      • Optionalparams: {
            backgroundColor?: string;
            curveStyle?: string;
            nodeColors?: Record<string, string>;
            withStyles?: boolean;
            wrapLabelNWords?: number;
        }

        Parameters for the drawMermaid method.

        • OptionalbackgroundColor?: string

          The background color of the graph.

        • OptionalcurveStyle?: string

          The style of the graph's curves.

        • OptionalnodeColors?: Record<string, string>

          The colors of the graph's nodes.

        • OptionalwithStyles?: boolean

          Whether to include styles in the graph.

        • OptionalwrapLabelNWords?: number

          The maximum number of words to wrap in a node's label.

      Returns Promise<any>

      Mermaid string

    • Visualize the graph as a PNG image.

      Parameters

      • Optionalparams: {
            backgroundColor?: string;
            curveStyle?: string;
            nodeColors?: Record<string, string>;
            withStyles?: boolean;
            wrapLabelNWords?: number;
        }

        Parameters for the drawMermaidPng method.

        • OptionalbackgroundColor?: string

          The background color of the graph.

        • OptionalcurveStyle?: string

          The style of the graph's curves.

        • OptionalnodeColors?: Record<string, string>

          The colors of the graph's nodes.

        • OptionalwithStyles?: boolean

          Whether to include styles in the graph.

        • OptionalwrapLabelNWords?: number

          The maximum number of words to wrap in a node's label.

      Returns Promise<Uint8Array<any>>

      PNG image as a buffer

    • 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.)

      Parameters

      • state: InvokeStateParameter<Types>

        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
      • Optionalconfig: any

        Optional runtime configuration including:

      Returns Promise<MergedAgentState<Types>>

      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

      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."
    • 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.

      Type Parameters

      • TStreamMode extends undefined | StreamMode | StreamMode[]
      • TSubgraphs extends boolean
      • TEncoding extends undefined | "text/event-stream"

      Parameters

      • state: InvokeStateParameter<Types>

        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
      • Optionalconfig: any

        Optional runtime configuration including:

      Returns Promise<
          IterableReadableStream<
              StreamOutputMap<
                  TStreamMode,
                  TSubgraphs,
                  MergedAgentState<Types>,
                  MergedAgentState<Types>,
                  string,
                  unknown,
                  unknown,
                  TEncoding,
              >,
          >,
      >

      A Promise that resolves to an IterableReadableStream of state updates. Each update contains the current state after a node completes.

      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
      }
    • 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.

      Parameters

      • config: Omit<BaseMessage, "store" | "writer" | "interrupt">

        Configuration to merge with existing config

      Returns ReactAgent<Types>

      A new ReactAgent instance with the merged configuration

      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"] });