UNPKG

@langchain/core

Version:
1 lines 7.59 kB
{"version":3,"file":"base.cjs","names":["Runnable"],"sources":["../../src/output_parsers/base.ts"],"sourcesContent":["import { Runnable } from \"../runnables/index.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport type { BaseMessage, ContentBlock } from \"../messages/index.js\";\nimport type { Callbacks } from \"../callbacks/manager.js\";\nimport type { Generation, ChatGeneration } from \"../outputs.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\n\n/**\n * Options for formatting instructions.\n */\nexport interface FormatInstructionsOptions {}\n\n/**\n * Abstract base class for parsing the output of a Large Language Model\n * (LLM) call. It provides methods for parsing the result of an LLM call\n * and invoking the parser with a given input.\n */\nexport abstract class BaseLLMOutputParser<T = unknown> extends Runnable<\n string | BaseMessage,\n T\n> {\n /**\n * Parses the result of an LLM call. This method is meant to be\n * implemented by subclasses to define how the output from the LLM should\n * be parsed.\n * @param generations The generations from an LLM call.\n * @param callbacks Optional callbacks.\n * @returns A promise of the parsed output.\n */\n abstract parseResult(\n generations: Generation[] | ChatGeneration[],\n callbacks?: Callbacks\n ): Promise<T>;\n\n /**\n * Parses the result of an LLM call with a given prompt. By default, it\n * simply calls `parseResult`.\n * @param generations The generations from an LLM call.\n * @param _prompt The prompt used in the LLM call.\n * @param callbacks Optional callbacks.\n * @returns A promise of the parsed output.\n */\n parseResultWithPrompt(\n generations: Generation[] | ChatGeneration[],\n _prompt: BasePromptValueInterface,\n callbacks?: Callbacks\n ): Promise<T> {\n return this.parseResult(generations, callbacks);\n }\n\n protected _baseMessageToString(message: BaseMessage): string {\n return typeof message.content === \"string\"\n ? message.content\n : this._baseMessageContentToString(message.content);\n }\n\n protected _baseMessageContentToString(content: ContentBlock[]): string {\n return JSON.stringify(content);\n }\n\n /**\n * Calls the parser with a given input and optional configuration options.\n * If the input is a string, it creates a generation with the input as\n * text and calls `parseResult`. If the input is a `BaseMessage`, it\n * creates a generation with the input as a message and the content of the\n * input as text, and then calls `parseResult`.\n * @param input The input to the parser, which can be a string or a `BaseMessage`.\n * @param options Optional configuration options.\n * @returns A promise of the parsed output.\n */\n async invoke(\n input: string | BaseMessage,\n options?: RunnableConfig\n ): Promise<T> {\n if (typeof input === \"string\") {\n return this._callWithConfig(\n async (input: string, options): Promise<T> =>\n this.parseResult([{ text: input }], options?.callbacks),\n input,\n { ...options, runType: \"parser\" }\n );\n } else {\n return this._callWithConfig(\n async (input: BaseMessage, options): Promise<T> =>\n this.parseResult(\n [\n {\n message: input,\n text: this._baseMessageToString(input),\n },\n ],\n options?.callbacks\n ),\n input,\n { ...options, runType: \"parser\" }\n );\n }\n }\n}\n\n/**\n * Class to parse the output of an LLM call.\n */\nexport abstract class BaseOutputParser<\n T = unknown,\n> extends BaseLLMOutputParser<T> {\n parseResult(\n generations: Generation[] | ChatGeneration[],\n callbacks?: Callbacks\n ): Promise<T> {\n return this.parse(generations[0].text, callbacks);\n }\n\n /**\n * Parse the output of an LLM call.\n *\n * @param text - LLM output to parse.\n * @returns Parsed output.\n */\n abstract parse(text: string, callbacks?: Callbacks): Promise<T>;\n\n async parseWithPrompt(\n text: string,\n _prompt: BasePromptValueInterface,\n callbacks?: Callbacks\n ): Promise<T> {\n return this.parse(text, callbacks);\n }\n\n /**\n * Return a string describing the format of the output.\n * @returns Format instructions.\n * @param options - Options for formatting instructions.\n * @example\n * ```json\n * {\n * \"foo\": \"bar\"\n * }\n * ```\n */\n abstract getFormatInstructions(options?: FormatInstructionsOptions): string;\n\n /**\n * Return the string type key uniquely identifying this class of parser\n */\n _type(): string {\n throw new Error(\"_type not implemented\");\n }\n}\n\n/**\n * Exception that output parsers should raise to signify a parsing error.\n *\n * This exists to differentiate parsing errors from other code or execution errors\n * that also may arise inside the output parser. OutputParserExceptions will be\n * available to catch and handle in ways to fix the parsing error, while other\n * errors will be raised.\n *\n * @param message - The error that's being re-raised or an error message.\n * @param llmOutput - String model output which is error-ing.\n * @param observation - String explanation of error which can be passed to a\n * model to try and remediate the issue.\n * @param sendToLLM - Whether to send the observation and llm_output back to an Agent\n * after an OutputParserException has been raised. This gives the underlying\n * model driving the agent the context that the previous output was improperly\n * structured, in the hopes that it will update the output to the correct\n * format.\n */\nexport class OutputParserException extends Error {\n llmOutput?: string;\n\n observation?: string;\n\n sendToLLM: boolean;\n\n constructor(\n message: string,\n llmOutput?: string,\n observation?: string,\n sendToLLM = false\n ) {\n super(message);\n this.llmOutput = llmOutput;\n this.observation = observation;\n this.sendToLLM = sendToLLM;\n\n if (sendToLLM) {\n if (observation === undefined || llmOutput === undefined) {\n throw new Error(\n \"Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true\"\n );\n }\n }\n\n addLangChainErrorFields(this, \"OUTPUT_PARSING_FAILURE\");\n }\n}\n"],"mappings":";;;;;;;;;;AAkBA,IAAsB,sBAAtB,cAA+DA,sBAG7D;;;;;;;;;CAsBA,sBACE,aACA,SACA,WACY;AACZ,SAAO,KAAK,YAAY,aAAa,UAAU;;CAGjD,AAAU,qBAAqB,SAA8B;AAC3D,SAAO,OAAO,QAAQ,YAAY,WAC9B,QAAQ,UACR,KAAK,4BAA4B,QAAQ,QAAQ;;CAGvD,AAAU,4BAA4B,SAAiC;AACrE,SAAO,KAAK,UAAU,QAAQ;;;;;;;;;;;;CAahC,MAAM,OACJ,OACA,SACY;AACZ,MAAI,OAAO,UAAU,SACnB,QAAO,KAAK,gBACV,OAAO,OAAe,YACpB,KAAK,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,EAAE,SAAS,UAAU,EACzD,OACA;GAAE,GAAG;GAAS,SAAS;GAAU,CAClC;MAED,QAAO,KAAK,gBACV,OAAO,OAAoB,YACzB,KAAK,YACH,CACE;GACE,SAAS;GACT,MAAM,KAAK,qBAAqB,MAAM;GACvC,CACF,EACD,SAAS,UACV,EACH,OACA;GAAE,GAAG;GAAS,SAAS;GAAU,CAClC;;;;;;AAQP,IAAsB,mBAAtB,cAEU,oBAAuB;CAC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