{"version":3,"file":"agent_executor.cjs","names":["BaseChain","ListStepContainer","LLMPlanner","LLMChain","getPlannerChatPrompt","PlanOutputParser","DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE","StructuredChatAgent","ChainStepExecutor","AgentExecutor","ChatAgent"],"sources":["../../../src/experimental/plan_and_execute/agent_executor.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { Tool, DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { BaseChain, ChainInputs } from \"../../chains/base.js\";\nimport {\n  BasePlanner,\n  BaseStepContainer,\n  BaseStepExecutor,\n  ListStepContainer,\n  LLMPlanner,\n  ChainStepExecutor,\n} from \"./base.js\";\nimport { AgentExecutor } from \"../../agents/executor.js\";\nimport {\n  DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE,\n  getPlannerChatPrompt,\n} from \"./prompt.js\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { PlanOutputParser } from \"./outputParser.js\";\nimport { ChatAgent } from \"../../agents/chat/index.js\";\nimport { StructuredChatAgent } from \"../../agents/index.js\";\nimport { SerializedLLMChain } from \"../../chains/serde.js\";\n\n/**\n * A utility function to distiguish a dynamicstructuredtool over other tools.\n * @param tool the tool to test\n * @returns bool\n */\nexport function isDynamicStructuredTool(\n  tool: Tool | DynamicStructuredTool\n): tool is DynamicStructuredTool {\n  // We check for the existence of the static lc_name method in the object's constructor\n  return (\n    // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n    typeof (tool.constructor as any).lc_name === \"function\" &&\n    // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n    (tool.constructor as any).lc_name() === \"DynamicStructuredTool\"\n  );\n}\n\n/**\n * Interface for the input to the PlanAndExecuteAgentExecutor class. It\n * extends ChainInputs and includes additional properties for the planner,\n * step executor, step container, and input and output keys.\n */\nexport interface PlanAndExecuteAgentExecutorInput extends ChainInputs {\n  planner: BasePlanner;\n  stepExecutor: BaseStepExecutor;\n  stepContainer?: BaseStepContainer;\n  inputKey?: string;\n  outputKey?: string;\n}\n\n/**\n * Class representing a plan-and-execute agent executor. This agent\n * decides on the full sequence of actions upfront, then executes them all\n * without updating the plan. This is suitable for complex or long-running\n * tasks that require maintaining long-term objectives and focus.\n */\nexport class PlanAndExecuteAgentExecutor extends BaseChain {\n  static lc_name() {\n    return \"PlanAndExecuteAgentExecutor\";\n  }\n\n  private planner: BasePlanner;\n\n  private stepExecutor: BaseStepExecutor;\n\n  private stepContainer: BaseStepContainer = new ListStepContainer();\n\n  private inputKey = \"input\";\n\n  private outputKey = \"output\";\n\n  constructor(input: PlanAndExecuteAgentExecutorInput) {\n    super(input);\n    this.planner = input.planner;\n    this.stepExecutor = input.stepExecutor;\n    this.stepContainer = input.stepContainer ?? this.stepContainer;\n    this.inputKey = input.inputKey ?? this.inputKey;\n    this.outputKey = input.outputKey ?? this.outputKey;\n  }\n\n  get inputKeys() {\n    return [this.inputKey];\n  }\n\n  get outputKeys() {\n    return [this.outputKey];\n  }\n\n  /**\n   * Static method that returns a default planner for the agent. It creates\n   * a new LLMChain with a given LLM and a fixed prompt, and uses it to\n   * create a new LLMPlanner with a PlanOutputParser.\n   * @param llm The Large Language Model (LLM) used to generate responses.\n   * @returns A new LLMPlanner instance.\n   */\n\n  static async getDefaultPlanner({\n    llm,\n    tools,\n  }: {\n    llm: BaseLanguageModelInterface;\n    tools: Tool[] | DynamicStructuredTool[];\n  }) {\n    const plannerLlmChain = new LLMChain({\n      llm,\n      prompt: await getPlannerChatPrompt(tools),\n    });\n    return new LLMPlanner(plannerLlmChain, new PlanOutputParser());\n  }\n\n  /**\n   * Static method that returns a default step executor for the agent. It\n   * creates a new ChatAgent from a given LLM and a set of tools, and uses\n   * it to create a new ChainStepExecutor.\n   * @param llm The Large Language Model (LLM) used to generate responses.\n   * @param tools The set of tools used by the agent.\n   * @param humanMessageTemplate The template for human messages. If not provided, a default template is used.\n   * @returns A new ChainStepExecutor instance.\n   */\n  static getDefaultStepExecutor({\n    llm,\n    tools,\n    humanMessageTemplate = DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE,\n  }: {\n    llm: BaseLanguageModelInterface;\n    tools: Tool[] | DynamicStructuredTool[];\n    humanMessageTemplate?: string;\n  }) {\n    let agent;\n\n    if (tools.length > 0 && isDynamicStructuredTool(tools[0])) {\n      agent = StructuredChatAgent.fromLLMAndTools(llm, tools, {\n        humanMessageTemplate,\n        inputVariables: [\"previous_steps\", \"current_step\", \"agent_scratchpad\"],\n      });\n      return new ChainStepExecutor(\n        AgentExecutor.fromAgentAndTools({\n          agent,\n          tools,\n        })\n      );\n    }\n\n    agent = ChatAgent.fromLLMAndTools(llm, tools as Tool[], {\n      humanMessageTemplate,\n    });\n    return new ChainStepExecutor(\n      AgentExecutor.fromAgentAndTools({\n        agent,\n        tools,\n      })\n    );\n  }\n\n  /**\n   * Static method that creates a new PlanAndExecuteAgentExecutor from a\n   * given LLM, a set of tools, and optionally a human message template. It\n   * uses the getDefaultPlanner and getDefaultStepExecutor methods to create\n   * the planner and step executor for the new agent executor.\n   * @param llm The Large Language Model (LLM) used to generate responses.\n   * @param tools The set of tools used by the agent.\n   * @param humanMessageTemplate The template for human messages. If not provided, a default template is used.\n   * @returns A new PlanAndExecuteAgentExecutor instance.\n   */\n  static async fromLLMAndTools({\n    llm,\n    tools,\n    humanMessageTemplate,\n  }: {\n    llm: BaseLanguageModelInterface;\n    tools: Tool[] | DynamicStructuredTool[];\n    humanMessageTemplate?: string;\n  } & Omit<PlanAndExecuteAgentExecutorInput, \"planner\" | \"stepExecutor\">) {\n    const executor = new PlanAndExecuteAgentExecutor({\n      planner: await PlanAndExecuteAgentExecutor.getDefaultPlanner({\n        llm,\n        tools,\n      }),\n      stepExecutor: PlanAndExecuteAgentExecutor.getDefaultStepExecutor({\n        llm,\n        tools,\n        humanMessageTemplate,\n      }),\n    });\n    return executor;\n  }\n\n  /** @ignore */\n  async _call(\n    inputs: ChainValues,\n    runManager?: CallbackManagerForChainRun\n  ): Promise<ChainValues> {\n    const plan = await this.planner.plan(inputs.input, runManager?.getChild());\n    if (!plan.steps?.length) {\n      throw new Error(\n        \"Could not create and parse a plan to answer your question - please try again.\"\n      );\n    }\n    plan.steps[plan.steps.length - 1].text +=\n      ` The original question was: ${inputs.input}.`;\n    for (const step of plan.steps) {\n      const newInputs = {\n        ...inputs,\n        previous_steps: JSON.stringify(this.stepContainer.getSteps()),\n        current_step: step.text,\n      };\n      const response = await this.stepExecutor.step(\n        newInputs,\n        runManager?.getChild()\n      );\n      this.stepContainer.addStep(step, response);\n    }\n    return { [this.outputKey]: this.stepContainer.getFinalResponse() };\n  }\n\n  _chainType() {\n    return \"agent_executor\" as const;\n  }\n\n  serialize(): SerializedLLMChain {\n    throw new Error(\"Cannot serialize an AgentExecutor\");\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,SAAgB,wBACd,MAC+B;AAE/B,QAEE,OAAQ,KAAK,YAAoB,YAAY,cAE5C,KAAK,YAAoB,SAAS,KAAK;;;;;;;;AAuB5C,IAAa,8BAAb,MAAa,oCAAoCA,aAAAA,UAAU;CACzD,OAAO,UAAU;AACf,SAAO;;CAGT;CAEA;CAEA,gBAA2C,IAAIC,eAAAA,mBAAmB;CAElE,WAAmB;CAEnB,YAAoB;CAEpB,YAAY,OAAyC;AACnD,QAAM,MAAM;AACZ,OAAK,UAAU,MAAM;AACrB,OAAK,eAAe,MAAM;AAC1B,OAAK,gBAAgB,MAAM,iBAAiB,KAAK;AACjD,OAAK,WAAW,MAAM,YAAY,KAAK;AACvC,OAAK,YAAY,MAAM,aAAa,KAAK;;CAG3C,IAAI,YAAY;AACd,SAAO,CAAC,KAAK,SAAS;;CAGxB,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,UAAU;;;;;;;;;CAWzB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