{"version":3,"file":"react_agent_executor.cjs","names":["Runnable","RunnableLambda","SystemMessage","RunnableSequence","RunnableBinding","Annotation","messagesStateReducer","ToolNode","withAgentName","StateGraph","START","isToolMessage","Send","END"],"sources":["../../src/prebuilt/react_agent_executor.ts"],"sourcesContent":["import {\n  BaseChatModel,\n  BindToolsInput,\n} from \"@langchain/core/language_models/chat_models\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport {\n  BaseMessage,\n  BaseMessageLike,\n  isAIMessage,\n  isBaseMessage,\n  isToolMessage,\n  SystemMessage,\n  type AIMessage,\n} from \"@langchain/core/messages\";\nimport {\n  Runnable,\n  RunnableLambda,\n  RunnableToolLike,\n  RunnableSequence,\n  RunnableBinding,\n  type RunnableLike,\n} from \"@langchain/core/runnables\";\nimport { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n  InteropZodObject,\n  InteropZodType,\n} from \"@langchain/core/utils/types\";\nimport {\n  All,\n  BaseCheckpointSaver,\n  BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\n\nimport {\n  StateGraph,\n  type CompiledStateGraph,\n  AnnotationRoot,\n} from \"../graph/index.js\";\nimport { MessagesAnnotation } from \"../graph/messages_annotation.js\";\nimport { ToolNode } from \"./tool_node.js\";\nimport { LangGraphRunnableConfig, Runtime } from \"../pregel/runnable_types.js\";\nimport { Annotation } from \"../graph/annotation.js\";\nimport { Messages, messagesStateReducer } from \"../graph/messages_reducer.js\";\nimport { END, Send, START } from \"../constants.js\";\nimport { withAgentName } from \"./agentName.js\";\nimport type { InteropZodToStateDefinition } from \"../graph/zod/meta.js\";\n\n/**\n * @deprecated `AgentState` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { AgentState } from \"langchain\";`\n */\nexport interface AgentState<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  StructuredResponseType extends Record<string, any> = Record<string, any>,\n> {\n  messages: BaseMessage[];\n  // TODO: This won't be set until we\n  // implement managed values in LangGraphJS\n  // Will be useful for inserting a message on\n  // graph recursion end\n  // is_last_step: boolean;\n  structuredResponse: StructuredResponseType;\n}\n\nexport type N = typeof START | \"agent\" | \"tools\";\n\ntype StructuredResponseSchemaOptions<StructuredResponseType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  schema: InteropZodType<StructuredResponseType> | Record<string, any>;\n  prompt?: string;\n\n  strict?: boolean;\n  [key: string]: unknown;\n};\n\nfunction _convertMessageModifierToPrompt(\n  messageModifier: MessageModifier\n): Prompt {\n  // Handle string or SystemMessage\n  if (\n    typeof messageModifier === \"string\" ||\n    (isBaseMessage(messageModifier) && messageModifier._getType() === \"system\")\n  ) {\n    return messageModifier;\n  }\n\n  // Handle callable function\n  if (typeof messageModifier === \"function\") {\n    return async (state: typeof MessagesAnnotation.State) =>\n      messageModifier(state.messages);\n  }\n\n  // Handle Runnable\n  if (Runnable.isRunnable(messageModifier)) {\n    return RunnableLambda.from(\n      (state: typeof MessagesAnnotation.State) => state.messages\n    ).pipe(messageModifier);\n  }\n\n  throw new Error(\n    `Unexpected type for messageModifier: ${typeof messageModifier}`\n  );\n}\n\nconst PROMPT_RUNNABLE_NAME = \"prompt\";\n\nfunction _getPromptRunnable(prompt?: Prompt): Runnable {\n  let promptRunnable: Runnable;\n\n  if (prompt == null) {\n    promptRunnable = RunnableLambda.from(\n      (state: typeof MessagesAnnotation.State) => state.messages\n    ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n  } else if (typeof prompt === \"string\") {\n    const systemMessage = new SystemMessage(prompt);\n    promptRunnable = RunnableLambda.from(\n      (state: typeof MessagesAnnotation.State) => {\n        return [systemMessage, ...(state.messages ?? [])];\n      }\n    ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n  } else if (isBaseMessage(prompt) && prompt._getType() === \"system\") {\n    promptRunnable = RunnableLambda.from(\n      (state: typeof MessagesAnnotation.State) => [prompt, ...state.messages]\n    ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n  } else if (typeof prompt === \"function\") {\n    promptRunnable = RunnableLambda.from(prompt).withConfig({\n      runName: PROMPT_RUNNABLE_NAME,\n    });\n  } else if (Runnable.isRunnable(prompt)) {\n    promptRunnable = prompt;\n  } else {\n    throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n  }\n\n  return promptRunnable;\n}\n\ntype ServerTool = Record<string, unknown>;\ntype ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\n\nfunction isClientTool(tool: ClientTool | ServerTool): tool is ClientTool {\n  return Runnable.isRunnable(tool);\n}\n\nfunction _getPrompt(\n  prompt?: Prompt,\n  stateModifier?: CreateReactAgentParams[\"stateModifier\"],\n  messageModifier?: CreateReactAgentParams[\"messageModifier\"]\n): Runnable {\n  // Check if multiple modifiers exist\n  const definedCount = [prompt, stateModifier, messageModifier].filter(\n    (x) => x != null\n  ).length;\n  if (definedCount > 1) {\n    throw new Error(\n      \"Expected only one of prompt, stateModifier, or messageModifier, got multiple values\"\n    );\n  }\n\n  let finalPrompt = prompt;\n  if (stateModifier != null) {\n    finalPrompt = stateModifier;\n  } else if (messageModifier != null) {\n    finalPrompt = _convertMessageModifierToPrompt(messageModifier);\n  }\n\n  return _getPromptRunnable(finalPrompt);\n}\n\nfunction _isBaseChatModel(model: LanguageModelLike): model is BaseChatModel {\n  return (\n    \"invoke\" in model &&\n    typeof model.invoke === \"function\" &&\n    \"_modelType\" in model\n  );\n}\n\ninterface ConfigurableModelInterface {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  _queuedMethodOperations: Record<string, any>;\n  _model: () => Promise<BaseChatModel>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _isConfigurableModel(model: any): model is ConfigurableModelInterface {\n  return (\n    \"_queuedMethodOperations\" in model &&\n    \"_model\" in model &&\n    typeof model._model === \"function\"\n  );\n}\n\nfunction _isChatModelWithBindTools(\n  llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n  if (!_isBaseChatModel(llm)) return false;\n  return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\nexport async function _shouldBindTools(\n  llm: LanguageModelLike,\n  tools: (ClientTool | ServerTool)[]\n): Promise<boolean> {\n  // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n  let model = llm;\n  if (RunnableSequence.isRunnableSequence(model)) {\n    model =\n      model.steps.find(\n        (step) =>\n          RunnableBinding.isRunnableBinding(step) ||\n          _isBaseChatModel(step) ||\n          _isConfigurableModel(step)\n      ) || model;\n  }\n\n  if (_isConfigurableModel(model)) {\n    model = await model._model();\n  }\n\n  // If not a RunnableBinding, we should bind tools\n  if (!RunnableBinding.isRunnableBinding(model)) {\n    return true;\n  }\n\n  let boundTools = (() => {\n    // check if model.kwargs contain the tools key\n    if (\n      model.kwargs != null &&\n      typeof model.kwargs === \"object\" &&\n      \"tools\" in model.kwargs &&\n      Array.isArray(model.kwargs.tools)\n    ) {\n      return (model.kwargs.tools ?? null) as BindToolsInput[] | null;\n    }\n\n    // Some models can bind the tools via `withConfig()` instead of `bind()`\n    if (\n      model.config != null &&\n      typeof model.config === \"object\" &&\n      \"tools\" in model.config &&\n      Array.isArray(model.config.tools)\n    ) {\n      return (model.config.tools ?? null) as BindToolsInput[] | null;\n    }\n\n    return null;\n  })();\n\n  // google-style\n  if (\n    boundTools != null &&\n    boundTools.length === 1 &&\n    \"functionDeclarations\" in boundTools[0]\n  ) {\n    boundTools = boundTools[0].functionDeclarations;\n  }\n\n  // If no tools in kwargs, we should bind tools\n  if (boundTools == null) return true;\n\n  // Check if tools count matches\n  if (tools.length !== boundTools.length) {\n    throw new Error(\n      \"Number of tools in the model.bindTools() and tools passed to createReactAgent must match\"\n    );\n  }\n\n  const toolNames = new Set<string>(\n    tools.flatMap((tool) => (isClientTool(tool) ? tool.name : []))\n  );\n\n  const boundToolNames = new Set<string>();\n\n  for (const boundTool of boundTools) {\n    let boundToolName: string | undefined;\n\n    // OpenAI-style tool\n    if (\"type\" in boundTool && boundTool.type === \"function\") {\n      boundToolName = boundTool.function.name;\n    }\n    // Anthropic or Google-style tool\n    else if (\"name\" in boundTool) {\n      boundToolName = boundTool.name;\n    }\n    // Bedrock-style tool\n    else if (\"toolSpec\" in boundTool && \"name\" in boundTool.toolSpec) {\n      boundToolName = boundTool.toolSpec.name;\n    }\n    // unknown tool type so we'll ignore it\n    else {\n      continue;\n    }\n\n    if (boundToolName) {\n      boundToolNames.add(boundToolName);\n    }\n  }\n\n  const missingTools = [...toolNames].filter((x) => !boundToolNames.has(x));\n  if (missingTools.length > 0) {\n    throw new Error(\n      `Missing tools '${missingTools}' in the model.bindTools().` +\n        `Tools in the model.bindTools() must match the tools passed to createReactAgent.`\n    );\n  }\n\n  return false;\n}\n\nconst _simpleBindTools = (\n  llm: LanguageModelLike,\n  toolClasses: (ClientTool | ServerTool)[]\n) => {\n  if (_isChatModelWithBindTools(llm)) {\n    return llm.bindTools(toolClasses);\n  }\n\n  if (\n    RunnableBinding.isRunnableBinding(llm) &&\n    _isChatModelWithBindTools(llm.bound)\n  ) {\n    const newBound = llm.bound.bindTools(toolClasses);\n\n    if (RunnableBinding.isRunnableBinding(newBound)) {\n      return new RunnableBinding({\n        bound: newBound.bound,\n        config: { ...llm.config, ...newBound.config },\n        kwargs: { ...llm.kwargs, ...newBound.kwargs },\n        configFactories: newBound.configFactories ?? llm.configFactories,\n      });\n    }\n\n    return new RunnableBinding({\n      bound: newBound,\n      config: llm.config,\n      kwargs: llm.kwargs,\n      configFactories: llm.configFactories,\n    });\n  }\n\n  return null;\n};\n\nexport async function _bindTools(\n  llm: LanguageModelLike,\n  toolClasses: (ClientTool | ServerTool)[]\n) {\n  const model = _simpleBindTools(llm, toolClasses);\n  if (model) return model;\n\n  if (_isConfigurableModel(llm)) {\n    const model = _simpleBindTools(await llm._model(), toolClasses);\n    if (model) return model;\n  }\n\n  if (RunnableSequence.isRunnableSequence(llm)) {\n    const modelStep = llm.steps.findIndex(\n      (step) =>\n        RunnableBinding.isRunnableBinding(step) ||\n        _isBaseChatModel(step) ||\n        _isConfigurableModel(step)\n    );\n\n    if (modelStep >= 0) {\n      const model = _simpleBindTools(llm.steps[modelStep], toolClasses);\n      if (model) {\n        const nextSteps: unknown[] = llm.steps.slice();\n        nextSteps.splice(modelStep, 1, model);\n\n        return RunnableSequence.from(\n          nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n        );\n      }\n    }\n  }\n\n  throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\nexport async function _getModel(\n  llm: LanguageModelLike | ConfigurableModelInterface\n): Promise<LanguageModelLike> {\n  // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n  let model = llm;\n  if (RunnableSequence.isRunnableSequence(model)) {\n    model =\n      model.steps.find(\n        (step) =>\n          RunnableBinding.isRunnableBinding(step) ||\n          _isBaseChatModel(step) ||\n          _isConfigurableModel(step)\n      ) || model;\n  }\n\n  if (_isConfigurableModel(model)) {\n    model = await model._model();\n  }\n\n  // Get the underlying model from a RunnableBinding\n  if (RunnableBinding.isRunnableBinding(model)) {\n    model = model.bound;\n  }\n\n  if (!_isBaseChatModel(model)) {\n    throw new Error(\n      `Expected \\`llm\\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${model.constructor.name}`\n    );\n  }\n\n  return model;\n}\n\nexport type Prompt =\n  | SystemMessage\n  | string\n  | ((\n      state: typeof MessagesAnnotation.State,\n      config: LangGraphRunnableConfig\n    ) => BaseMessageLike[])\n  | ((\n      state: typeof MessagesAnnotation.State,\n      config: LangGraphRunnableConfig\n    ) => Promise<BaseMessageLike[]>)\n  | Runnable;\n\n/** @deprecated Use Prompt instead. */\nexport type StateModifier = Prompt;\n\n/** @deprecated Use Prompt instead. */\nexport type MessageModifier =\n  | SystemMessage\n  | string\n  | ((messages: BaseMessage[]) => BaseMessage[])\n  | ((messages: BaseMessage[]) => Promise<BaseMessage[]>)\n  | Runnable;\n\nexport const createReactAgentAnnotation = <\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  T extends Record<string, any> = Record<string, any>,\n>() =>\n  Annotation.Root({\n    messages: Annotation<BaseMessage[], Messages>({\n      reducer: messagesStateReducer,\n      default: () => [],\n    }),\n    structuredResponse: Annotation<T>,\n  });\n\ntype WithStateGraphNodes<K extends string, Graph> =\n  Graph extends StateGraph<\n    infer SD,\n    infer S,\n    infer U,\n    infer N,\n    infer I,\n    infer O,\n    infer C\n  >\n    ? StateGraph<SD, S, U, N | K, I, O, C>\n    : never;\n\nconst PreHookAnnotation = Annotation.Root({\n  llmInputMessages: Annotation<BaseMessage[], Messages>({\n    reducer: (_, update) => messagesStateReducer([], update),\n    default: () => [],\n  }),\n});\n\ntype PreHookAnnotation = typeof PreHookAnnotation;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyAnnotationRoot = AnnotationRoot<any>;\n\ntype ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n  A extends AnyAnnotationRoot\n    ? A\n    : A extends InteropZodObject\n      ? AnnotationRoot<InteropZodToStateDefinition<A>>\n      : never;\n\n/**\n * @deprecated `CreateReactAgentParams` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { CreateAgentParams } from \"langchain\";`\n */\nexport type CreateReactAgentParams<\n  A extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  StructuredResponseType extends Record<string, any> = Record<string, any>,\n  C extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n> = {\n  /** The chat model that can utilize OpenAI-style tool calling. */\n  llm:\n    | LanguageModelLike\n    | ((\n        state: ToAnnotationRoot<A>[\"State\"] & PreHookAnnotation[\"State\"],\n        runtime: Runtime<ToAnnotationRoot<C>[\"State\"]>\n      ) => Promise<LanguageModelLike> | LanguageModelLike);\n\n  /** A list of tools or a ToolNode. */\n  tools: ToolNode | (ServerTool | ClientTool)[];\n\n  /**\n   * @deprecated Use prompt instead.\n   */\n  messageModifier?: MessageModifier;\n\n  /**\n   * @deprecated Use prompt instead.\n   */\n  stateModifier?: StateModifier;\n\n  /**\n   * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n   *\n   * Can take a few different forms:\n   *\n   * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n   * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n   * - Function: This function should take in full graph state and the output is then passed to the language model.\n   * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n   *\n   * Note:\n   * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n   * This is now deprecated and will be removed in a future release.\n   */\n  prompt?: Prompt;\n\n  /**\n   * Additional state schema for the agent.\n   */\n  stateSchema?: A;\n\n  /**\n   * An optional schema for the context.\n   */\n  contextSchema?: C;\n  /** An optional checkpoint saver to persist the agent's state. */\n  checkpointSaver?: BaseCheckpointSaver | boolean;\n  /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n  checkpointer?: BaseCheckpointSaver | boolean;\n  /** An optional list of node names to interrupt before running. */\n  interruptBefore?: N[] | All;\n  /** An optional list of node names to interrupt after running. */\n  interruptAfter?: N[] | All;\n  store?: BaseStore;\n  /**\n   * An optional schema for the final agent output.\n   *\n   * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n   * If not provided, `structuredResponse` will not be present in the output state.\n   *\n   * Can be passed in as:\n   *   - Zod schema\n   *   - JSON schema\n   *   - { prompt, schema }, where schema is one of the above.\n   *        The prompt will be used together with the model that is being used to generate the structured response.\n   *\n   * @remarks\n   * **Important**: `responseFormat` requires the model to support `.withStructuredOutput()`.\n   *\n   * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n   * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n   */\n  responseFormat?:\n    | InteropZodType<StructuredResponseType>\n    | StructuredResponseSchemaOptions<StructuredResponseType>\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    | Record<string, any>;\n\n  /**\n   * An optional name for the agent.\n   */\n  name?: string;\n\n  /**\n   * An optional description for the agent.\n   * This can be used to describe the agent to the underlying supervisor LLM.\n   */\n  description?: string | undefined;\n\n  /**\n   * Use to specify how to expose the agent name to the underlying supervisor LLM.\n\n      - undefined: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n      - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n          Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n   */\n  includeAgentName?: \"inline\" | undefined;\n\n  /**\n   * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n   * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n   */\n  preModelHook?: RunnableLike<\n    ToAnnotationRoot<A>[\"State\"] & PreHookAnnotation[\"State\"],\n    ToAnnotationRoot<A>[\"Update\"] & PreHookAnnotation[\"Update\"],\n    LangGraphRunnableConfig\n  >;\n\n  /**\n   * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n   * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n   */\n  postModelHook?: RunnableLike<\n    ToAnnotationRoot<A>[\"State\"],\n    ToAnnotationRoot<A>[\"Update\"],\n    LangGraphRunnableConfig\n  >;\n\n  /**\n   * Determines the version of the graph to create.\n   *\n   * Can be one of\n   * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n   *           executed in parallel within the tool node.\n   * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n   *           multiple instances of the tool node using the Send API.\n   *\n   * @default `\"v1\"`\n   */\n  version?: \"v1\" | \"v2\";\n};\n\n/**\n * @deprecated `createReactAgent` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { createAgent } from \"langchain\";`\n *\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n * import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n *\n * const model = new ChatOpenAI({\n *   model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n *   if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n *     return \"It's 60 degrees and foggy.\";\n *   } else {\n *     return \"It's 90 degrees and sunny.\";\n *   }\n * }, {\n *   name: \"get_weather\",\n *   description: \"Call to get the current weather.\",\n *   schema: z.object({\n *     location: z.string().describe(\"Location to get the weather for.\"),\n *   })\n * })\n *\n * const agent = createReactAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n *   messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n *   console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\nexport function createReactAgent<\n  A extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n  C extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n>(\n  params: CreateReactAgentParams<A, StructuredResponseFormat, C>\n): CompiledStateGraph<\n  ToAnnotationRoot<A>[\"State\"],\n  ToAnnotationRoot<A>[\"Update\"],\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  any,\n  typeof MessagesAnnotation.spec & ToAnnotationRoot<A>[\"spec\"],\n  ReturnType<\n    typeof createReactAgentAnnotation<StructuredResponseFormat>\n  >[\"spec\"] &\n    ToAnnotationRoot<A>[\"spec\"]\n> {\n  const {\n    llm,\n    tools,\n    messageModifier,\n    stateModifier,\n    prompt,\n    stateSchema,\n    contextSchema,\n    checkpointSaver,\n    checkpointer,\n    interruptBefore,\n    interruptAfter,\n    store,\n    responseFormat,\n    preModelHook,\n    postModelHook,\n    name,\n    description,\n    version = \"v1\",\n    includeAgentName,\n  } = params;\n\n  let toolClasses: (ClientTool | ServerTool)[];\n\n  let toolNode: ToolNode;\n  if (!Array.isArray(tools)) {\n    toolClasses = tools.tools;\n    toolNode = tools;\n  } else {\n    toolClasses = tools;\n    toolNode = new ToolNode(toolClasses.filter(isClientTool));\n  }\n\n  let cachedStaticModel: Runnable | null = null;\n\n  const _getStaticModel = async (llm: LanguageModelLike): Promise<Runnable> => {\n    if (cachedStaticModel) return cachedStaticModel;\n\n    let modelWithTools: LanguageModelLike;\n    if (await _shouldBindTools(llm, toolClasses)) {\n      modelWithTools = await _bindTools(llm, toolClasses);\n    } else {\n      modelWithTools = llm;\n    }\n\n    const promptRunnable = _getPrompt(prompt, stateModifier, messageModifier);\n    const modelRunnable =\n      includeAgentName === \"inline\"\n        ? withAgentName(modelWithTools, includeAgentName)\n        : modelWithTools;\n\n    cachedStaticModel = promptRunnable.pipe(modelRunnable);\n    return cachedStaticModel;\n  };\n\n  const _getDynamicModel = async (\n    llm: (\n      state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n      runtime: Runtime<ToAnnotationRoot<C>[\"State\"]>\n    ) => Promise<LanguageModelLike> | LanguageModelLike,\n    state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n    config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n  ) => {\n    const model = await llm(state, config);\n\n    return _getPrompt(prompt, stateModifier, messageModifier).pipe(\n      includeAgentName === \"inline\"\n        ? withAgentName(model, includeAgentName)\n        : model\n    );\n  };\n\n  // If any of the tools are configured to return_directly after running,\n  // our graph needs to check if these were called\n  const shouldReturnDirect = new Set(\n    toolClasses\n      .filter(isClientTool)\n      .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n      .map((tool) => tool.name)\n  );\n\n  function getModelInputState(\n    state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"]\n  ): Omit<AgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n    const { messages, llmInputMessages, ...rest } = state;\n    if (llmInputMessages != null && llmInputMessages.length > 0) {\n      return { messages: llmInputMessages, ...rest };\n    }\n    return { messages, ...rest };\n  }\n\n  const generateStructuredResponse = async (\n    state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n    config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n  ) => {\n    if (responseFormat == null) {\n      throw new Error(\n        \"Attempted to generate structured output with no passed response schema. Please contact us for help.\"\n      );\n    }\n    const messages = [...state.messages];\n    let modelWithStructuredOutput;\n\n    const model: LanguageModelLike =\n      typeof llm === \"function\"\n        ? await llm(state, config)\n        : await _getModel(llm);\n\n    if (!_isBaseChatModel(model)) {\n      throw new Error(\n        `Expected \\`llm\\` to be a ChatModel with .withStructuredOutput() method, got ${model.constructor.name}`\n      );\n    }\n\n    if (typeof responseFormat === \"object\" && \"schema\" in responseFormat) {\n      const { prompt, schema, ...options } =\n        responseFormat as StructuredResponseSchemaOptions<StructuredResponseFormat>;\n\n      modelWithStructuredOutput = model.withStructuredOutput(schema, options);\n      if (prompt != null) {\n        messages.unshift(new SystemMessage({ content: prompt }));\n      }\n    } else {\n      modelWithStructuredOutput = model.withStructuredOutput(responseFormat);\n    }\n\n    const response = await modelWithStructuredOutput.invoke(messages, config);\n    return { structuredResponse: response };\n  };\n\n  const callModel = async (\n    state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n    config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n  ) => {\n    // NOTE: we're dynamically creating the model runnable here\n    // to ensure that we can validate ConfigurableModel properly\n    const modelRunnable: Runnable =\n      typeof llm === \"function\"\n        ? await _getDynamicModel(llm, state, config)\n        : await _getStaticModel(llm);\n\n    // TODO: Auto-promote streaming.\n    const response = (await modelRunnable.invoke(\n      getModelInputState(state),\n      config\n    )) as BaseMessage;\n    // add agent name to the AIMessage\n    // TODO: figure out if we can avoid mutating the message directly\n    response.name = name;\n    response.lc_kwargs.name = name;\n    return { messages: [response] };\n  };\n\n  const schema =\n    stateSchema ?? createReactAgentAnnotation<StructuredResponseFormat>();\n\n  const workflow = new StateGraph(\n    schema as AnyAnnotationRoot,\n    contextSchema\n  ).addNode(\"tools\", toolNode);\n\n  if (!(\"messages\" in workflow._schemaDefinition)) {\n    throw new Error(\"Missing required `messages` key in state schema.\");\n  }\n\n  const allNodeWorkflows = workflow as WithStateGraphNodes<\n    | \"pre_model_hook\"\n    | \"post_model_hook\"\n    | \"generate_structured_response\"\n    | \"agent\",\n    typeof workflow\n  >;\n\n  const conditionalMap = <T extends string>(map: Record<string, T | null>) => {\n    return Object.fromEntries(\n      Object.entries(map).filter(([_, v]) => v != null) as [string, T][]\n    );\n  };\n\n  let entrypoint: \"agent\" | \"pre_model_hook\" = \"agent\";\n  let inputSchema: AnnotationRoot<ToAnnotationRoot<A>[\"spec\"]> | undefined;\n  if (preModelHook != null) {\n    allNodeWorkflows\n      .addNode(\"pre_model_hook\", preModelHook)\n      .addEdge(\"pre_model_hook\", \"agent\");\n    entrypoint = \"pre_model_hook\";\n\n    inputSchema = Annotation.Root({\n      ...workflow._schemaDefinition,\n      ...PreHookAnnotation.spec,\n    });\n  } else {\n    entrypoint = \"agent\";\n  }\n\n  allNodeWorkflows\n    .addNode(\"agent\", callModel, { input: inputSchema })\n    .addEdge(START, entrypoint);\n\n  if (postModelHook != null) {\n    allNodeWorkflows\n      .addNode(\"post_model_hook\", postModelHook)\n      .addEdge(\"agent\", \"post_model_hook\")\n      .addConditionalEdges(\n        \"post_model_hook\",\n        (state) => {\n          const { messages } = state as AgentState<StructuredResponseFormat>;\n\n          const toolMessageIds: Set<string> = new Set(\n            messages.filter(isToolMessage).map((msg) => msg.tool_call_id)\n          );\n\n          let lastAiMessage: AIMessage | undefined;\n          for (let i = messages.length - 1; i >= 0; i -= 1) {\n            const message = messages[i];\n            if (isAIMessage(message)) {\n              lastAiMessage = message;\n              break;\n            }\n          }\n\n          const pendingToolCalls =\n            lastAiMessage?.tool_calls?.filter(\n              (i) => i.id == null || !toolMessageIds.has(i.id)\n            ) ?? [];\n\n          const lastMessage = messages[messages.length - 1];\n          if (pendingToolCalls.length > 0) {\n            if (version === \"v2\") {\n              return pendingToolCalls.map(\n                (toolCall) =>\n                  new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n              );\n            }\n            return \"tools\";\n          }\n\n          if (lastMessage && isToolMessage(lastMessage)) return entrypoint;\n          if (responseFormat != null) return \"generate_structured_response\";\n          return END;\n        },\n        conditionalMap({\n          tools: \"tools\",\n          [entrypoint]: entrypoint,\n          generate_structured_response:\n            responseFormat != null ? \"generate_structured_response\" : null,\n          [END]: responseFormat != null ? null : END,\n        })\n      );\n  }\n\n  if (responseFormat !== undefined) {\n    workflow\n      .addNode(\"generate_structured_response\", generateStructuredResponse)\n      .addEdge(\"generate_structured_response\", END);\n  }\n\n  if (postModelHook == null) {\n    allNodeWorkflows.addConditionalEdges(\n      \"agent\",\n      (state) => {\n        const { messages } = state;\n        const lastMessage = messages[messages.length - 1];\n\n        // if there's no function call, we finish\n        if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) {\n          if (responseFormat != null) return \"generate_structured_response\";\n          return END;\n        }\n\n        // there are function calls, we continue\n        if (version === \"v2\") {\n          return lastMessage.tool_calls.map(\n            (toolCall) =>\n              new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n          );\n        }\n\n        return \"tools\";\n      },\n      conditionalMap({\n        tools: \"tools\",\n        generate_structured_response:\n          responseFormat != null ? \"generate_structured_response\" : null,\n        [END]: responseFormat != null ? null : END,\n      })\n    );\n  }\n\n  if (shouldReturnDirect.size > 0) {\n    allNodeWorkflows.addConditionalEdges(\n      \"tools\",\n      (state) => {\n        const agentState = state;\n        // Check the last consecutive tool calls\n        for (let i = agentState.messages.length - 1; i >= 0; i -= 1) {\n          const message = agentState.messages[i];\n          if (!isToolMessage(message)) break;\n\n          // Check if this tool is configured to return directly\n          if (\n            message.name !== undefined &&\n            shouldReturnDirect.has(message.name)\n          ) {\n            return END;\n          }\n        }\n\n        return entrypoint;\n      },\n      conditionalMap({ [entrypoint]: entrypoint, [END]: END })\n    );\n  } else {\n    allNodeWorkflows.addEdge(\"tools\", entrypoint);\n  }\n\n  return allNodeWorkflows.compile({\n    checkpointer: checkpointer ?? checkpointSaver,\n    interruptBefore,\n    interruptAfter,\n    store,\n    name,\n    description,\n  });\n}\n"],"mappings":";;;;;;;;;;AA2EA,SAAS,gCACP,iBACQ;AAER,KACE,OAAO,oBAAoB,aAAA,GAAA,yBAAA,eACZ,gBAAgB,IAAI,gBAAgB,UAAU,KAAK,SAElE,QAAO;AAIT,KAAI,OAAO,oBAAoB,WAC7B,QAAO,OAAO,UACZ,gBAAgB,MAAM,SAAS;AAInC,KAAIA,0BAAAA,SAAS,WAAW,gBAAgB,CACtC,QAAOC,0BAAAA,eAAe,MACnB,UAA2C,MAAM,SACnD,CAAC,KAAK,gBAAgB;AAGzB,OAAM,IAAI,MACR,wCAAwC,OAAO,kBAChD;;AAGH,MAAM,uBAAuB;AAE7B,SAAS,mBAAmB,QAA2B;CACrD,IAAI;AAEJ,KAAI,UAAU,KACZ,kBAAiBA,0BAAAA,eAAe,MAC7B,UAA2C,MAAM,SACnD,CAAC,WAAW,EAAE,SAAS,sBAAsB,CAAC;UACtC,OAAO,WAAW,UAAU;EACrC,MAAM,gBAAgB,IAAIC,yBAAAA,cAAc,OAAO;AAC/C,mBAAiBD,0BAAAA,eAAe,MAC7B,UAA2C;AAC1C,UAAO,CAAC,eAAe,GAAI,MAAM,YAAY,EAAE,CAAE;IAEpD,CAAC,WAAW,EAAE,SAAS,sBAAsB,CAAC;wDACxB,OAAO,IAAI,OAAO,UAAU,KAAK,SACxD,kBAAiBA,0BAAAA,eAAe,MAC7B,UAA2C,CAAC,QAAQ,GAAG,MAAM,SAAS,CACxE,CAAC,WAAW,EAAE,SAAS,sBAAsB,CAAC;UACtC,O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