{"version":3,"file":"index.cjs","names":["Agent","ZeroShotAgentOutputParser","PREFIX","SUFFIX","PromptTemplate","FORMAT_INSTRUCTIONS","LLMChain","deserializeHelper"],"sources":["../../../src/agents/mrkl/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { ToolInterface } from \"@langchain/core/tools\";\nimport { PromptTemplate, renderTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { deserializeHelper } from \"../helpers.js\";\nimport {\n  AgentInput,\n  SerializedFromLLMAndTools,\n  SerializedZeroShotAgent,\n} from \"../types.js\";\nimport { ZeroShotAgentOutputParser } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\n\n/**\n * Interface for creating a prompt for the ZeroShotAgent.\n */\nexport interface ZeroShotCreatePromptArgs {\n  /** String to put after the list of tools. */\n  suffix?: string;\n  /** String to put before the list of tools. */\n  prefix?: string;\n  /** List of input variables the final prompt will expect. */\n  inputVariables?: string[];\n}\n\n/**\n * Type for the input to the ZeroShotAgent, with the 'outputParser'\n * property made optional.\n */\nexport type ZeroShotAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n * @example\n * ```typescript\n *\n * const agent = new ZeroShotAgent({\n *   llmChain: new LLMChain({\n *     llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n *     prompt: ZeroShotAgent.createPrompt([new SerpAPI(), new Calculator()], {\n *       prefix: `Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:`,\n *       suffix: `Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Args\"\n * Question: {input}\n * {agent_scratchpad}`,\n *       inputVariables: [\"input\", \"agent_scratchpad\"],\n *     }),\n *   }),\n *   allowedTools: [\"search\", \"calculator\"],\n * });\n *\n * const result = await agent.invoke({\n *   input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,\n * });\n * ```\n */\nexport class ZeroShotAgent extends Agent {\n  static lc_name() {\n    return \"ZeroShotAgent\";\n  }\n\n  lc_namespace = [\"langchain\", \"agents\", \"mrkl\"];\n\n  declare ToolType: ToolInterface;\n\n  constructor(input: ZeroShotAgentInput) {\n    const outputParser =\n      input?.outputParser ?? ZeroShotAgent.getDefaultOutputParser();\n    super({ ...input, outputParser });\n  }\n\n  _agentType() {\n    return \"zero-shot-react-description\" as const;\n  }\n\n  observationPrefix() {\n    return \"Observation: \";\n  }\n\n  llmPrefix() {\n    return \"Thought:\";\n  }\n\n  /**\n   * Returns the default output parser for the ZeroShotAgent.\n   * @param fields Optional arguments for the output parser.\n   * @returns An instance of ZeroShotAgentOutputParser.\n   */\n  static getDefaultOutputParser(fields?: OutputParserArgs) {\n    return new ZeroShotAgentOutputParser(fields);\n  }\n\n  /**\n   * Validates the tools for the ZeroShotAgent. Throws an error if any tool\n   * does not have a description.\n   * @param tools List of tools to validate.\n   */\n  static validateTools(tools: ToolInterface[]) {\n    const descriptionlessTool = tools.find((tool) => !tool.description);\n    if (descriptionlessTool) {\n      const msg =\n        `Got a tool ${descriptionlessTool.name} without a description.` +\n        ` This agent requires descriptions for all tools.`;\n      throw new Error(msg);\n    }\n  }\n\n  /**\n   * Create prompt in the style of the zero shot agent.\n   *\n   * @param tools - List of tools the agent will have access to, used to format the prompt.\n   * @param args - Arguments to create the prompt with.\n   * @param args.suffix - String to put after the list of tools.\n   * @param args.prefix - String to put before the list of tools.\n   * @param args.inputVariables - List of input variables the final prompt will expect.\n   */\n  static createPrompt(tools: ToolInterface[], args?: ZeroShotCreatePromptArgs) {\n    const {\n      prefix = PREFIX,\n      suffix = SUFFIX,\n      inputVariables = [\"input\", \"agent_scratchpad\"],\n    } = args ?? {};\n    const toolStrings = tools\n      .map((tool) => `${tool.name}: ${tool.description}`)\n      .join(\"\\n\");\n\n    const toolNames = tools.map((tool) => `\"${tool.name}\"`).join(\", \");\n\n    const formatInstructions = renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n      tool_names: toolNames,\n    });\n\n    const template = [prefix, toolStrings, formatInstructions, suffix].join(\n      \"\\n\\n\"\n    );\n\n    return new PromptTemplate({\n      template,\n      inputVariables,\n    });\n  }\n\n  /**\n   * Creates a ZeroShotAgent from a Large Language Model and a set of tools.\n   * @param llm The Large Language Model to use.\n   * @param tools The tools for the agent to use.\n   * @param args Optional arguments for creating the agent.\n   * @returns A new instance of ZeroShotAgent.\n   */\n  static fromLLMAndTools(\n    llm: BaseLanguageModelInterface,\n    tools: ToolInterface[],\n    args?: ZeroShotCreatePromptArgs & AgentArgs\n  ) {\n    ZeroShotAgent.validateTools(tools);\n    const prompt = ZeroShotAgent.createPrompt(tools, args);\n    const outputParser =\n      args?.outputParser ?? ZeroShotAgent.getDefaultOutputParser();\n    const chain = new LLMChain({\n      prompt,\n      llm,\n      callbacks: args?.callbacks ?? args?.callbackManager,\n    });\n\n    return new ZeroShotAgent({\n      llmChain: chain,\n      allowedTools: tools.map((t) => t.name),\n      outputParser,\n    });\n  }\n\n  static async deserialize(\n    data: SerializedZeroShotAgent & {\n      llm?: BaseLanguageModelInterface;\n      tools?: ToolInterface[];\n    }\n  ): Promise<ZeroShotAgent> {\n    const { llm, tools, ...rest } = data;\n    return deserializeHelper(\n      llm,\n      tools,\n      rest,\n      (\n        llm: BaseLanguageModelInterface,\n        tools: ToolInterface[],\n        args: SerializedFromLLMAndTools\n      ) =>\n        ZeroShotAgent.fromLLMAndTools(llm, tools, {\n          prefix: args.prefix,\n          suffix: args.suffix,\n          inputVariables: args.input_variables,\n        }),\n      (args) => new ZeroShotAgent(args)\n    );\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAa,gBAAb,MAAa,sBAAsBA,cAAAA,MAAM;CACvC,OAAO,UAAU;A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