{"version":3,"file":"outputParser.cjs","names":["AgentActionOutputParser","OutputParserException","AGENT_ACTION_FORMAT_INSTRUCTIONS","FORMAT_INSTRUCTIONS","OutputFixingParser"],"sources":["../../../src/agents/structured_chat/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport {\n  AGENT_ACTION_FORMAT_INSTRUCTIONS,\n  FORMAT_INSTRUCTIONS,\n} from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\n/**\n * A class that provides a custom implementation for parsing the output of\n * a StructuredChatAgent action. It extends the `AgentActionOutputParser`\n * class and extracts the action and action input from the text output,\n * returning an `AgentAction` or `AgentFinish` object.\n */\nexport class StructuredChatOutputParser extends AgentActionOutputParser {\n  lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n  private toolNames: string[];\n\n  constructor(fields: { toolNames: string[] }) {\n    super(...arguments);\n    this.toolNames = fields.toolNames;\n  }\n\n  /**\n   * Parses the given text and returns an `AgentAction` or `AgentFinish`\n   * object. If an `OutputFixingParser` is provided, it is used for parsing;\n   * otherwise, the base parser is used.\n   * @param text The text to parse.\n   * @param callbacks Optional callbacks for asynchronous operations.\n   * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n   */\n  async parse(text: string): Promise<AgentAction | AgentFinish> {\n    try {\n      const regex = /```(?:json)?(.*)(```)/gs;\n      const actionMatch = regex.exec(text);\n      if (actionMatch === null) {\n        throw new OutputParserException(\n          `Could not parse an action. The agent action must be within a markdown code block, and \"action\" must be a provided tool or \"Final Answer\"`\n        );\n      }\n      const response = JSON.parse(actionMatch[1].trim());\n      const { action, action_input } = response;\n\n      if (action === \"Final Answer\") {\n        return { returnValues: { output: action_input }, log: text };\n      }\n      return { tool: action, toolInput: action_input || {}, log: text };\n    } catch (e) {\n      throw new OutputParserException(\n        `Failed to parse. Text: \"${text}\". Error: ${e}`\n      );\n    }\n  }\n\n  /**\n   * Returns the format instructions for parsing the output of an agent\n   * action in the style of the StructuredChatAgent.\n   * @returns A string representing the format instructions.\n   */\n  getFormatInstructions(): string {\n    return renderTemplate(AGENT_ACTION_FORMAT_INSTRUCTIONS, \"f-string\", {\n      tool_names: this.toolNames.join(\", \"),\n    });\n  }\n}\n\n/**\n * An interface for the arguments used to construct a\n * `StructuredChatOutputParserWithRetries` instance.\n */\nexport interface StructuredChatOutputParserArgs {\n  baseParser?: StructuredChatOutputParser;\n  outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n  toolNames?: string[];\n}\n\n/**\n * A class that provides a wrapper around the `StructuredChatOutputParser`\n * and `OutputFixingParser` classes. It extends the\n * `AgentActionOutputParser` class and allows for retrying the output\n * parsing using the `OutputFixingParser` if it is provided.\n * @example\n * ```typescript\n * const outputParser = new StructuredChatOutputParserWithRetries.fromLLM(\n *   new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n *   {\n *     toolNames: [\"calculator\", \"random-number-generator\"],\n *   },\n * );\n * const result = await outputParser.parse(\n *  \"What is a random number between 5 and 10 raised to the second power?\"\n * );\n * ```\n */\nexport class StructuredChatOutputParserWithRetries extends AgentActionOutputParser {\n  lc_namespace = [\"langchain\", \"agents\", \"structured_chat\"];\n\n  private baseParser: StructuredChatOutputParser;\n\n  private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n  private toolNames: string[] = [];\n\n  constructor(fields: StructuredChatOutputParserArgs) {\n    super(fields);\n    this.toolNames = fields.toolNames ?? this.toolNames;\n    this.baseParser =\n      fields?.baseParser ??\n      new StructuredChatOutputParser({ toolNames: this.toolNames });\n    this.outputFixingParser = fields?.outputFixingParser;\n  }\n\n  /**\n   * Parses the given text and returns an `AgentAction` or `AgentFinish`\n   * object. Throws an `OutputParserException` if the parsing fails.\n   * @param text The text to parse.\n   * @returns A Promise that resolves to an `AgentAction` or `AgentFinish` object.\n   */\n  async parse(\n    text: string,\n    callbacks?: Callbacks\n  ): Promise<AgentAction | AgentFinish> {\n    if (this.outputFixingParser !== undefined) {\n      return this.outputFixingParser.parse(text, callbacks);\n    }\n    return this.baseParser.parse(text);\n  }\n\n  /**\n   * Returns the format instructions for parsing the output of an agent\n   * action in the style of the StructuredChatAgent.\n   * @returns A string representing the format instructions.\n   */\n  getFormatInstructions(): string {\n    return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n      tool_names: this.toolNames.join(\", \"),\n    });\n  }\n\n  /**\n   * Creates a new `StructuredChatOutputParserWithRetries` instance from a\n   * `BaseLanguageModel` and options. The options can include a base parser\n   * and tool names.\n   * @param llm A `BaseLanguageModel` instance.\n   * @param options Options for creating a `StructuredChatOutputParserWithRetries` instance.\n   * @returns A new `StructuredChatOutputParserWithRetries` instance.\n   */\n  static fromLLM(\n    llm: BaseLanguageModelInterface,\n    options: Omit<StructuredChatOutputParserArgs, \"outputFixingParser\">\n  ): StructuredChatOutputParserWithRetries {\n    const baseParser =\n      options.baseParser ??\n      new StructuredChatOutputParser({ toolNames: options.toolNames ?? [] });\n    const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n    return new StructuredChatOutputParserWithRetries({\n      baseParser,\n      outputFixingParser,\n      toolNames: options.toolNames,\n    });\n  }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAa,6BAAb,cAAgDA,cAAAA,wBAAwB;CACtE,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD;CAEA,YAAY,QAAiC;AAC3C,QAAM,GAAG,UAAU;AACnB,OAAK,YAAY,OAAO;;;;;;;;;;CAW1B,MAAM,MAAM,MAAkD;AAC5D,MAAI;GAEF,MAAM,cADQ,0BACY,KAAK,KAAK;AACpC,OAAI,gBAAgB,KAClB,OAAM,IAAIC,+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