@langchain/classic 1.0.44 → 1.0.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/_virtual/_rolldown/runtime.cjs +1 -1
- package/dist/agents/agent.cjs.map +1 -1
- package/dist/agents/chat/index.cjs +2 -1
- package/dist/agents/chat/index.cjs.map +1 -1
- package/dist/agents/chat/index.js +2 -1
- package/dist/agents/chat/index.js.map +1 -1
- package/dist/agents/chat_convo/index.cjs +7 -5
- package/dist/agents/chat_convo/index.cjs.map +1 -1
- package/dist/agents/chat_convo/index.js +7 -5
- package/dist/agents/chat_convo/index.js.map +1 -1
- package/dist/agents/chat_convo/outputParser.cjs.map +1 -1
- package/dist/agents/executor.cjs +22 -19
- package/dist/agents/executor.cjs.map +1 -1
- package/dist/agents/executor.js +22 -19
- package/dist/agents/executor.js.map +1 -1
- package/dist/agents/format_scratchpad/log_to_message.cjs.map +1 -1
- package/dist/agents/format_scratchpad/openai_functions.cjs.map +1 -1
- package/dist/agents/mrkl/index.cjs +9 -6
- package/dist/agents/mrkl/index.cjs.map +1 -1
- package/dist/agents/mrkl/index.js +9 -6
- package/dist/agents/mrkl/index.js.map +1 -1
- package/dist/agents/mrkl/outputParser.d.cts +1 -1
- package/dist/agents/openai_functions/index.cjs +2 -1
- package/dist/agents/openai_functions/index.cjs.map +1 -1
- package/dist/agents/openai_functions/index.js +2 -1
- package/dist/agents/openai_functions/index.js.map +1 -1
- package/dist/agents/openai_functions/output_parser.cjs.map +1 -1
- package/dist/agents/openai_tools/index.cjs.map +1 -1
- package/dist/agents/openai_tools/output_parser.cjs.map +1 -1
- package/dist/agents/react/output_parser.cjs.map +1 -1
- package/dist/agents/structured_chat/index.cjs +6 -5
- package/dist/agents/structured_chat/index.cjs.map +1 -1
- package/dist/agents/structured_chat/index.js +6 -5
- package/dist/agents/structured_chat/index.js.map +1 -1
- package/dist/agents/structured_chat/outputParser.cjs.map +1 -1
- package/dist/agents/tool_calling/output_parser.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.cjs +2 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.js +2 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.js.map +1 -1
- package/dist/agents/toolkits/json/json.cjs +10 -8
- package/dist/agents/toolkits/json/json.cjs.map +1 -1
- package/dist/agents/toolkits/json/json.js +10 -8
- package/dist/agents/toolkits/json/json.js.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.cjs +12 -9
- package/dist/agents/toolkits/openapi/openapi.cjs.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.js +12 -9
- package/dist/agents/toolkits/openapi/openapi.js.map +1 -1
- package/dist/agents/toolkits/sql/sql.cjs +10 -8
- package/dist/agents/toolkits/sql/sql.cjs.map +1 -1
- package/dist/agents/toolkits/sql/sql.js +10 -8
- package/dist/agents/toolkits/sql/sql.js.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.cjs +20 -16
- package/dist/agents/toolkits/vectorstore/vectorstore.cjs.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.js +20 -16
- package/dist/agents/toolkits/vectorstore/vectorstore.js.map +1 -1
- package/dist/agents/xml/index.cjs +2 -1
- package/dist/agents/xml/index.cjs.map +1 -1
- package/dist/agents/xml/index.js +2 -1
- package/dist/agents/xml/index.js.map +1 -1
- package/dist/chains/base.cjs.map +1 -1
- package/dist/chains/chat_vector_db_chain.cjs +2 -1
- package/dist/chains/chat_vector_db_chain.cjs.map +1 -1
- package/dist/chains/chat_vector_db_chain.js +2 -1
- package/dist/chains/chat_vector_db_chain.js.map +1 -1
- package/dist/chains/conversational_retrieval_chain.cjs +2 -1
- package/dist/chains/conversational_retrieval_chain.cjs.map +1 -1
- package/dist/chains/conversational_retrieval_chain.js +2 -1
- package/dist/chains/conversational_retrieval_chain.js.map +1 -1
- package/dist/chains/openai_functions/base.cjs.map +1 -1
- package/dist/chains/openai_functions/extraction.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs +9 -8
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.js +9 -8
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/chains/openai_functions/tagging.cjs.map +1 -1
- package/dist/chains/openai_moderation.cjs.map +1 -1
- package/dist/chains/query_constructor/index.cjs +15 -9
- package/dist/chains/query_constructor/index.cjs.map +1 -1
- package/dist/chains/query_constructor/index.js +15 -9
- package/dist/chains/query_constructor/index.js.map +1 -1
- package/dist/chains/query_constructor/parser.cjs +12 -6
- package/dist/chains/query_constructor/parser.cjs.map +1 -1
- package/dist/chains/query_constructor/parser.js +12 -6
- package/dist/chains/query_constructor/parser.js.map +1 -1
- package/dist/chains/question_answering/load.cjs +35 -29
- package/dist/chains/question_answering/load.cjs.map +1 -1
- package/dist/chains/question_answering/load.js +35 -29
- package/dist/chains/question_answering/load.js.map +1 -1
- package/dist/chains/router/multi_prompt.cjs +5 -3
- package/dist/chains/router/multi_prompt.cjs.map +1 -1
- package/dist/chains/router/multi_prompt.js +5 -3
- package/dist/chains/router/multi_prompt.js.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs +18 -11
- package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.js +18 -11
- package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
- package/dist/chains/sequential_chain.cjs +6 -5
- package/dist/chains/sequential_chain.cjs.map +1 -1
- package/dist/chains/sequential_chain.js +6 -5
- package/dist/chains/sequential_chain.js.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.cjs +2 -1
- package/dist/chains/sql_db/sql_db_chain.cjs.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.js +2 -1
- package/dist/chains/sql_db/sql_db_chain.js.map +1 -1
- package/dist/chains/summarization/load.cjs +35 -29
- package/dist/chains/summarization/load.cjs.map +1 -1
- package/dist/chains/summarization/load.js +35 -29
- package/dist/chains/summarization/load.js.map +1 -1
- package/dist/chat_models/universal.cjs +12 -10
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.js +12 -10
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/document_loaders/fs/buffer.cjs.map +1 -1
- package/dist/document_loaders/fs/directory.cjs.map +1 -1
- package/dist/document_loaders/fs/multi_file.cjs.map +1 -1
- package/dist/document_loaders/fs/text.cjs.map +1 -1
- package/dist/document_transformers/openai_functions.cjs.map +1 -1
- package/dist/embeddings/cache_backed.cjs.map +1 -1
- package/dist/evaluation/comparison/pairwise.cjs +4 -2
- package/dist/evaluation/comparison/pairwise.cjs.map +1 -1
- package/dist/evaluation/comparison/pairwise.js +4 -2
- package/dist/evaluation/comparison/pairwise.js.map +1 -1
- package/dist/evaluation/criteria/criteria.cjs +4 -2
- package/dist/evaluation/criteria/criteria.cjs.map +1 -1
- package/dist/evaluation/criteria/criteria.js +4 -2
- package/dist/evaluation/criteria/criteria.js.map +1 -1
- package/dist/experimental/autogpt/agent.cjs +8 -7
- package/dist/experimental/autogpt/agent.cjs.map +1 -1
- package/dist/experimental/autogpt/agent.js +8 -7
- package/dist/experimental/autogpt/agent.js.map +1 -1
- package/dist/experimental/autogpt/prompt.cjs +2 -1
- package/dist/experimental/autogpt/prompt.cjs.map +1 -1
- package/dist/experimental/autogpt/prompt.js +2 -1
- package/dist/experimental/autogpt/prompt.js.map +1 -1
- package/dist/experimental/autogpt/prompt_generator.cjs.map +1 -1
- package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.cjs.map +1 -1
- package/dist/experimental/openai_assistant/index.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.cjs +3 -2
- package/dist/experimental/plan_and_execute/agent_executor.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.js +3 -2
- package/dist/experimental/plan_and_execute/agent_executor.js.map +1 -1
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs +2 -1
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.js +2 -1
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs +4 -2
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.js +4 -2
- package/dist/hub/node.js.map +1 -1
- package/dist/load/index.cjs.map +1 -1
- package/dist/memory/buffer_memory.cjs.map +1 -1
- package/dist/memory/buffer_token_memory.cjs.map +1 -1
- package/dist/memory/buffer_window_memory.cjs.map +1 -1
- package/dist/memory/chat_memory.cjs.map +1 -1
- package/dist/memory/entity_memory.cjs +2 -1
- package/dist/memory/entity_memory.cjs.map +1 -1
- package/dist/memory/entity_memory.js +2 -1
- package/dist/memory/entity_memory.js.map +1 -1
- package/dist/memory/summary.cjs.map +1 -1
- package/dist/memory/summary_buffer.cjs.map +1 -1
- package/dist/memory/vector_store.cjs.map +1 -1
- package/dist/output_parsers/fix.cjs +2 -1
- package/dist/output_parsers/fix.cjs.map +1 -1
- package/dist/output_parsers/fix.js +2 -1
- package/dist/output_parsers/fix.js.map +1 -1
- package/dist/output_parsers/openai_functions.cjs.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.cjs +2 -1
- package/dist/retrievers/document_compressors/chain_extract.cjs.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.js +2 -1
- package/dist/retrievers/document_compressors/chain_extract.js.map +1 -1
- package/dist/retrievers/matryoshka_retriever.cjs.map +1 -1
- package/dist/retrievers/multi_query.cjs +2 -1
- package/dist/retrievers/multi_query.cjs.map +1 -1
- package/dist/retrievers/multi_query.js +2 -1
- package/dist/retrievers/multi_query.js.map +1 -1
- package/dist/smith/runner_utils.cjs.map +1 -1
- package/dist/stores/file/node.cjs.map +1 -1
- package/dist/tools/render.cjs.map +1 -1
- package/dist/tools/retriever.cjs +2 -1
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.js +2 -1
- package/dist/tools/retriever.js.map +1 -1
- package/dist/tools/webbrowser.cjs +2 -1
- package/dist/tools/webbrowser.cjs.map +1 -1
- package/dist/tools/webbrowser.js +2 -1
- package/dist/tools/webbrowser.js.map +1 -1
- package/dist/util/hub.cjs.map +1 -1
- package/dist/vectorstores/memory.cjs +2 -1
- package/dist/vectorstores/memory.cjs.map +1 -1
- package/dist/vectorstores/memory.js +2 -1
- package/dist/vectorstores/memory.js.map +1 -1
- package/package.json +23 -23
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @langchain/classic
|
|
2
2
|
|
|
3
|
+
## 1.0.46
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`53dbfc2`](https://github.com/langchain-ai/langchainjs/commit/53dbfc2fa033250fe7b711d7c3c8f6e7bfea9216)]:
|
|
8
|
+
- @langchain/openai@1.5.11
|
|
9
|
+
|
|
10
|
+
## 1.0.45
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Updated dependencies [[`c26c87e`](https://github.com/langchain-ai/langchainjs/commit/c26c87e41bccd01111e170c32ba1e5eec94ba3a6)]:
|
|
15
|
+
- @langchain/openai@1.5.10
|
|
16
|
+
|
|
3
17
|
## 1.0.44
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
|
@@ -25,7 +25,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
25
25
|
return to;
|
|
26
26
|
};
|
|
27
27
|
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
28
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
29
29
|
value: mod,
|
|
30
30
|
enumerable: true
|
|
31
31
|
}) : target, mod));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.cjs","names":["Serializable","RunnableSequence"],"sources":["../../src/agents/agent.ts"],"sourcesContent":["import type {\n StructuredToolInterface,\n ToolInterface,\n} from \"@langchain/core/tools\";\nimport type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { CallbackManager, Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport {\n Runnable,\n patchConfig,\n type RunnableConfig,\n RunnableSequence,\n RunnableLike,\n} from \"@langchain/core/runnables\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport type {\n AgentActionOutputParser,\n AgentInput,\n RunnableMultiActionAgentInput,\n RunnableSingleActionAgentInput,\n SerializedAgent,\n StoppingMethod,\n} from \"./types.js\";\n\n/**\n * Record type for arguments passed to output parsers.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OutputParserArgs = Record<string, any>;\n\n/**\n * Error class for parse errors in LangChain. Contains information about\n * the error message and the output that caused the error.\n */\nclass ParseError extends Error {\n output: string;\n\n constructor(msg: string, output: string) {\n super(msg);\n this.output = output;\n }\n}\n\n/**\n * Abstract base class for agents in LangChain. Provides common\n * functionality for agents, such as handling inputs and outputs.\n */\nexport abstract class BaseAgent extends Serializable {\n declare ToolType: StructuredToolInterface;\n\n abstract get inputKeys(): string[];\n\n get returnValues(): string[] {\n return [\"output\"];\n }\n\n get allowedTools(): string[] | undefined {\n return undefined;\n }\n\n /**\n * Return the string type key uniquely identifying this class of agent.\n */\n _agentType(): string {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Return the string type key uniquely identifying multi or single action agents.\n */\n abstract _agentActionType(): string;\n\n /**\n * Return response when agent has been stopped due to max iterations\n */\n returnStoppedResponse(\n earlyStoppingMethod: StoppingMethod,\n _steps: AgentStep[],\n _inputs: ChainValues,\n _callbackManager?: CallbackManager\n ): Promise<AgentFinish> {\n if (earlyStoppingMethod === \"force\") {\n return Promise.resolve({\n returnValues: { output: \"Agent stopped due to max iterations.\" },\n log: \"\",\n });\n }\n\n throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`);\n }\n\n /**\n * Prepare the agent for output, if needed\n */\n async prepareForOutput(\n _returnValues: AgentFinish[\"returnValues\"],\n _steps: AgentStep[]\n ): Promise<AgentFinish[\"returnValues\"]> {\n return {};\n }\n}\n\n/**\n * Abstract base class for single action agents in LangChain. Extends the\n * BaseAgent class and provides additional functionality specific to\n * single action agents.\n */\nexport abstract class BaseSingleActionAgent extends BaseAgent {\n _agentActionType(): string {\n return \"single\" as const;\n }\n\n /**\n * Decide what to do, given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Action specifying what tool to use.\n */\n abstract plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction | AgentFinish>;\n}\n\n/**\n * Abstract base class for multi-action agents in LangChain. Extends the\n * BaseAgent class and provides additional functionality specific to\n * multi-action agents.\n */\nexport abstract class BaseMultiActionAgent extends BaseAgent {\n _agentActionType(): string {\n return \"multi\" as const;\n }\n\n /**\n * Decide what to do, given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Actions specifying what tools to use.\n */\n abstract plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction[] | AgentFinish>;\n}\n\nfunction isAgentAction(input: unknown): input is AgentAction {\n return !Array.isArray(input) && (input as AgentAction)?.tool !== undefined;\n}\n\nexport function isRunnableAgent(x: BaseAgent) {\n return (\n (x as RunnableMultiActionAgent | RunnableSingleActionAgent).runnable !==\n undefined\n );\n}\n\n// TODO: Remove in the future. Only for backwards compatibility.\n// Allows for the creation of runnables with properties that will\n// be passed to the agent executor constructor.\nexport class AgentRunnableSequence<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n> extends RunnableSequence<RunInput, RunOutput> {\n streamRunnable?: boolean;\n\n singleAction: boolean;\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static fromRunnables<RunInput = any, RunOutput = any>(\n [first, ...runnables]: [\n RunnableLike<RunInput>,\n ...RunnableLike[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunnableLike<any, RunOutput>,\n ],\n config: { singleAction: boolean; streamRunnable?: boolean; name?: string }\n ): AgentRunnableSequence<RunInput, Exclude<RunOutput, Error>> {\n const sequence = RunnableSequence.from(\n [first, ...runnables],\n config.name\n ) as AgentRunnableSequence<RunInput, Exclude<RunOutput, Error>>;\n sequence.singleAction = config.singleAction;\n sequence.streamRunnable = config.streamRunnable;\n return sequence;\n }\n\n static isAgentRunnableSequence(x: Runnable): x is AgentRunnableSequence {\n return typeof (x as AgentRunnableSequence).singleAction === \"boolean\";\n }\n}\n\n/**\n * Class representing a single-action agent powered by runnables.\n * Extends the BaseSingleActionAgent class and provides methods for\n * planning agent actions with runnables.\n */\nexport class RunnableSingleActionAgent extends BaseSingleActionAgent {\n lc_namespace = [\"langchain\", \"agents\", \"runnable\"];\n\n runnable: Runnable<\n ChainValues & { steps: AgentStep[] },\n AgentAction | AgentFinish\n >;\n\n get inputKeys(): string[] {\n return [];\n }\n\n /**\n * Whether to stream from the runnable or not.\n * If true, the underlying LLM is invoked in a streaming fashion to make it\n * possible to get access to the individual LLM tokens when using\n * `streamLog` with the Agent Executor. If false then LLM is invoked in a\n * non-streaming fashion and individual LLM tokens will not be available\n * in `streamLog`.\n *\n * Note that the runnable should still only stream a single action or\n * finish chunk.\n */\n streamRunnable = true;\n\n defaultRunName = \"RunnableAgent\";\n\n constructor(fields: RunnableSingleActionAgentInput) {\n super(fields);\n this.runnable = fields.runnable;\n this.defaultRunName =\n fields.defaultRunName ?? this.runnable.name ?? this.defaultRunName;\n this.streamRunnable = fields.streamRunnable ?? this.streamRunnable;\n }\n\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction | AgentFinish> {\n const combinedInput = { ...inputs, steps };\n const combinedConfig = patchConfig(config, {\n callbacks: callbackManager,\n runName: this.defaultRunName,\n });\n if (this.streamRunnable) {\n const stream = await this.runnable.stream(combinedInput, combinedConfig);\n let finalOutput: AgentAction | AgentFinish | undefined;\n for await (const chunk of stream) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n throw new Error(\n [\n `Multiple agent actions/finishes received in streamed agent output.`,\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n }\n if (finalOutput === undefined) {\n throw new Error(\n [\n \"No streaming output received from underlying runnable.\",\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n return finalOutput;\n } else {\n return this.runnable.invoke(combinedInput, combinedConfig);\n }\n }\n}\n\n/**\n * Class representing a multi-action agent powered by runnables.\n * Extends the BaseMultiActionAgent class and provides methods for\n * planning agent actions with runnables.\n */\nexport class RunnableMultiActionAgent extends BaseMultiActionAgent {\n lc_namespace = [\"langchain\", \"agents\", \"runnable\"];\n\n // TODO: Rename input to \"intermediate_steps\"\n runnable: Runnable<\n ChainValues & { steps: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n\n defaultRunName = \"RunnableAgent\";\n\n stop?: string[];\n\n streamRunnable = true;\n\n get inputKeys(): string[] {\n return [];\n }\n\n constructor(fields: RunnableMultiActionAgentInput) {\n super(fields);\n this.runnable = fields.runnable;\n this.stop = fields.stop;\n this.defaultRunName =\n fields.defaultRunName ?? this.runnable.name ?? this.defaultRunName;\n this.streamRunnable = fields.streamRunnable ?? this.streamRunnable;\n }\n\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction[] | AgentFinish> {\n const combinedInput = { ...inputs, steps };\n const combinedConfig = patchConfig(config, {\n callbacks: callbackManager,\n runName: this.defaultRunName,\n });\n let output;\n if (this.streamRunnable) {\n const stream = await this.runnable.stream(combinedInput, combinedConfig);\n let finalOutput: AgentAction | AgentFinish | AgentAction[] | undefined;\n for await (const chunk of stream) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n throw new Error(\n [\n `Multiple agent actions/finishes received in streamed agent output.`,\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n }\n if (finalOutput === undefined) {\n throw new Error(\n [\n \"No streaming output received from underlying runnable.\",\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n output = finalOutput;\n } else {\n output = await this.runnable.invoke(combinedInput, combinedConfig);\n }\n\n if (isAgentAction(output)) {\n return [output];\n }\n\n return output;\n }\n}\n\nexport class RunnableAgent extends RunnableMultiActionAgent {}\n\n/**\n * Interface for input data for creating a LLMSingleActionAgent.\n */\nexport interface LLMSingleActionAgentInput {\n llmChain: LLMChain;\n outputParser: AgentActionOutputParser;\n stop?: string[];\n}\n\n/**\n * Class representing a single action agent using a LLMChain in LangChain.\n * Extends the BaseSingleActionAgent class and provides methods for\n * planning agent actions based on LLMChain outputs.\n * @example\n * ```typescript\n * const customPromptTemplate = new CustomPromptTemplate({\n * tools: [new Calculator()],\n * inputVariables: [\"input\", \"agent_scratchpad\"],\n * });\n * const customOutputParser = new CustomOutputParser();\n * const agent = new LLMSingleActionAgent({\n * llmChain: new LLMChain({\n * prompt: customPromptTemplate,\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * }),\n * outputParser: customOutputParser,\n * stop: [\"\\nObservation\"],\n * });\n * const executor = new AgentExecutor({\n * agent,\n * tools: [new Calculator()],\n * });\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport class LLMSingleActionAgent extends BaseSingleActionAgent {\n lc_namespace = [\"langchain\", \"agents\"];\n\n llmChain: LLMChain;\n\n outputParser: AgentActionOutputParser;\n\n stop?: string[];\n\n constructor(input: LLMSingleActionAgentInput) {\n super(input);\n this.stop = input.stop;\n this.llmChain = input.llmChain;\n this.outputParser = input.outputParser;\n }\n\n get inputKeys(): string[] {\n return this.llmChain.inputKeys;\n }\n\n /**\n * Decide what to do given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Action specifying what tool to use.\n */\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n const output = await this.llmChain.call(\n {\n intermediate_steps: steps,\n stop: this.stop,\n ...inputs,\n },\n callbackManager\n );\n return this.outputParser.parse(\n output[this.llmChain.outputKey],\n callbackManager\n );\n }\n}\n\n/**\n * Interface for arguments used to create an agent in LangChain.\n */\nexport interface AgentArgs {\n outputParser?: AgentActionOutputParser;\n\n callbacks?: Callbacks;\n\n /**\n * @deprecated Use `callbacks` instead.\n */\n callbackManager?: CallbackManager;\n}\n\n/**\n * Class responsible for calling a language model and deciding an action.\n *\n * @remarks This is driven by an LLMChain. The prompt in the LLMChain *must*\n * include a variable called \"agent_scratchpad\" where the agent can put its\n * intermediary work.\n */\nexport abstract class Agent extends BaseSingleActionAgent {\n llmChain: LLMChain;\n\n outputParser: AgentActionOutputParser | undefined;\n\n private _allowedTools?: string[] = undefined;\n\n get allowedTools(): string[] | undefined {\n return this._allowedTools;\n }\n\n get inputKeys(): string[] {\n return this.llmChain.inputKeys.filter((k) => k !== \"agent_scratchpad\");\n }\n\n constructor(input: AgentInput) {\n super(input);\n\n this.llmChain = input.llmChain;\n this._allowedTools = input.allowedTools;\n this.outputParser = input.outputParser;\n }\n\n /**\n * Prefix to append the observation with.\n */\n abstract observationPrefix(): string;\n\n /**\n * Prefix to append the LLM call with.\n */\n abstract llmPrefix(): string;\n\n /**\n * Return the string type key uniquely identifying this class of agent.\n */\n abstract _agentType(): string;\n\n /**\n * Get the default output parser for this agent.\n */\n static getDefaultOutputParser(\n _fields?: OutputParserArgs\n ): AgentActionOutputParser {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Create a prompt for this class\n *\n * @param _tools - List of tools the agent will have access to, used to format the prompt.\n * @param _fields - Additional fields used to format the prompt.\n *\n * @returns A PromptTemplate assembled from the given tools and fields.\n * */\n static createPrompt(\n _tools: StructuredToolInterface[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _fields?: Record<string, any>\n ): BasePromptTemplate {\n throw new Error(\"Not implemented\");\n }\n\n /** Construct an agent from an LLM and a list of tools */\n static fromLLMAndTools(\n _llm: BaseLanguageModelInterface,\n _tools: StructuredToolInterface[],\n\n _args?: AgentArgs\n ): Agent {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Validate that appropriate tools are passed in\n */\n static validateTools(_tools: StructuredToolInterface[]): void {}\n\n _stop(): string[] {\n return [`\\n${this.observationPrefix()}`];\n }\n\n /**\n * Name of tool to use to terminate the chain.\n */\n finishToolName(): string {\n return \"Final Answer\";\n }\n\n /**\n * Construct a scratchpad to let the agent continue its thought process\n */\n async constructScratchPad(\n steps: AgentStep[]\n ): Promise<string | BaseMessage[]> {\n return steps.reduce(\n (thoughts, { action, observation }) =>\n thoughts +\n [\n action.log,\n `${this.observationPrefix()}${observation}`,\n this.llmPrefix(),\n ].join(\"\\n\"),\n \"\"\n );\n }\n\n private async _plan(\n steps: AgentStep[],\n inputs: ChainValues,\n suffix?: string,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n const thoughts = await this.constructScratchPad(steps);\n const newInputs: ChainValues = {\n ...inputs,\n agent_scratchpad: suffix ? `${thoughts}${suffix}` : thoughts,\n };\n\n if (this._stop().length !== 0) {\n newInputs.stop = this._stop();\n }\n\n const output = await this.llmChain.predict(newInputs, callbackManager);\n if (!this.outputParser) {\n throw new Error(\"Output parser not set\");\n }\n return this.outputParser.parse(output, callbackManager);\n }\n\n /**\n * Decide what to do given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager to use for this call.\n *\n * @returns Action specifying what tool to use.\n */\n plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n return this._plan(steps, inputs, undefined, callbackManager);\n }\n\n /**\n * Return response when agent has been stopped due to max iterations\n */\n async returnStoppedResponse(\n earlyStoppingMethod: StoppingMethod,\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentFinish> {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: { output: \"Agent stopped due to max iterations.\" },\n log: \"\",\n };\n }\n\n if (earlyStoppingMethod === \"generate\") {\n try {\n const action = await this._plan(\n steps,\n inputs,\n \"\\n\\nI now need to return a final answer based on the previous steps:\",\n callbackManager\n );\n if (\"returnValues\" in action) {\n return action;\n }\n\n return { returnValues: { output: action.log }, log: action.log };\n } catch (err) {\n // fine to use instanceof because we're in the same module\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (!(err instanceof ParseError)) {\n throw err;\n }\n return { returnValues: { output: err.output }, log: err.output };\n }\n }\n\n throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`);\n }\n\n /**\n * Load an agent from a json-like object describing it.\n */\n static async deserialize(\n data: SerializedAgent & {\n llm?: BaseLanguageModelInterface;\n tools?: ToolInterface[];\n }\n ): Promise<Agent> {\n switch (data._type) {\n case \"zero-shot-react-description\": {\n const { ZeroShotAgent } = await import(\"./mrkl/index.js\");\n return ZeroShotAgent.deserialize(data);\n }\n default:\n throw new Error(\"Unknown agent type\");\n }\n }\n}\n"],"mappings":";;;;;;;AAsCA,IAAM,aAAN,cAAyB,MAAM;CAC7B;CAEA,YAAY,KAAa,QAAgB;EACvC,MAAM,GAAG;EACT,KAAK,SAAS;CAChB;AACF;;;;;AAMA,IAAsB,YAAtB,cAAwCA,kCAAAA,aAAa;CAKnD,IAAI,eAAyB;EAC3B,OAAO,CAAC,QAAQ;CAClB;CAEA,IAAI,eAAqC,CAEzC;;;;CAKA,aAAqB;EACnB,MAAM,IAAI,MAAM,iBAAiB;CACnC;;;;CAUA,sBACE,qBACA,QACA,SACA,kBACsB;EACtB,IAAI,wBAAwB,SAC1B,OAAO,QAAQ,QAAQ;GACrB,cAAc,EAAE,QAAQ,uCAAuC;GAC/D,KAAK;EACP,CAAC;EAGH,MAAM,IAAI,MAAM,4BAA4B,qBAAqB;CACnE;;;;CAKA,MAAM,iBACJ,eACA,QACsC;EACtC,OAAO,CAAC;CACV;AACF;;;;;;AAOA,IAAsB,wBAAtB,cAAoD,UAAU;CAC5D,mBAA2B;EACzB,OAAO;CACT;AAiBF;;;;;;AAOA,IAAsB,uBAAtB,cAAmD,UAAU;CAC3D,mBAA2B;EACzB,OAAO;CACT;AAiBF;AAEA,SAAS,cAAc,OAAsC;CAC3D,OAAO,CAAC,MAAM,QAAQ,KAAK,KAAM,OAAuB,SAAS,KAAA;AACnE;AAEA,SAAgB,gBAAgB,GAAc;CAC5C,OACG,EAA2D,aAC5D,KAAA;AAEJ;A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","RunnableSequence","patchConfig"],"sources":["../../src/agents/agent.ts"],"sourcesContent":["import type {\n StructuredToolInterface,\n ToolInterface,\n} from \"@langchain/core/tools\";\nimport type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { CallbackManager, Callbacks } from \"@langchain/core/callbacks/manager\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport {\n Runnable,\n patchConfig,\n type RunnableConfig,\n RunnableSequence,\n RunnableLike,\n} from \"@langchain/core/runnables\";\nimport { LLMChain } from \"../chains/llm_chain.js\";\nimport type {\n AgentActionOutputParser,\n AgentInput,\n RunnableMultiActionAgentInput,\n RunnableSingleActionAgentInput,\n SerializedAgent,\n StoppingMethod,\n} from \"./types.js\";\n\n/**\n * Record type for arguments passed to output parsers.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OutputParserArgs = Record<string, any>;\n\n/**\n * Error class for parse errors in LangChain. Contains information about\n * the error message and the output that caused the error.\n */\nclass ParseError extends Error {\n output: string;\n\n constructor(msg: string, output: string) {\n super(msg);\n this.output = output;\n }\n}\n\n/**\n * Abstract base class for agents in LangChain. Provides common\n * functionality for agents, such as handling inputs and outputs.\n */\nexport abstract class BaseAgent extends Serializable {\n declare ToolType: StructuredToolInterface;\n\n abstract get inputKeys(): string[];\n\n get returnValues(): string[] {\n return [\"output\"];\n }\n\n get allowedTools(): string[] | undefined {\n return undefined;\n }\n\n /**\n * Return the string type key uniquely identifying this class of agent.\n */\n _agentType(): string {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Return the string type key uniquely identifying multi or single action agents.\n */\n abstract _agentActionType(): string;\n\n /**\n * Return response when agent has been stopped due to max iterations\n */\n returnStoppedResponse(\n earlyStoppingMethod: StoppingMethod,\n _steps: AgentStep[],\n _inputs: ChainValues,\n _callbackManager?: CallbackManager\n ): Promise<AgentFinish> {\n if (earlyStoppingMethod === \"force\") {\n return Promise.resolve({\n returnValues: { output: \"Agent stopped due to max iterations.\" },\n log: \"\",\n });\n }\n\n throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`);\n }\n\n /**\n * Prepare the agent for output, if needed\n */\n async prepareForOutput(\n _returnValues: AgentFinish[\"returnValues\"],\n _steps: AgentStep[]\n ): Promise<AgentFinish[\"returnValues\"]> {\n return {};\n }\n}\n\n/**\n * Abstract base class for single action agents in LangChain. Extends the\n * BaseAgent class and provides additional functionality specific to\n * single action agents.\n */\nexport abstract class BaseSingleActionAgent extends BaseAgent {\n _agentActionType(): string {\n return \"single\" as const;\n }\n\n /**\n * Decide what to do, given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Action specifying what tool to use.\n */\n abstract plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction | AgentFinish>;\n}\n\n/**\n * Abstract base class for multi-action agents in LangChain. Extends the\n * BaseAgent class and provides additional functionality specific to\n * multi-action agents.\n */\nexport abstract class BaseMultiActionAgent extends BaseAgent {\n _agentActionType(): string {\n return \"multi\" as const;\n }\n\n /**\n * Decide what to do, given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Actions specifying what tools to use.\n */\n abstract plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction[] | AgentFinish>;\n}\n\nfunction isAgentAction(input: unknown): input is AgentAction {\n return !Array.isArray(input) && (input as AgentAction)?.tool !== undefined;\n}\n\nexport function isRunnableAgent(x: BaseAgent) {\n return (\n (x as RunnableMultiActionAgent | RunnableSingleActionAgent).runnable !==\n undefined\n );\n}\n\n// TODO: Remove in the future. Only for backwards compatibility.\n// Allows for the creation of runnables with properties that will\n// be passed to the agent executor constructor.\nexport class AgentRunnableSequence<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n> extends RunnableSequence<RunInput, RunOutput> {\n streamRunnable?: boolean;\n\n singleAction: boolean;\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static fromRunnables<RunInput = any, RunOutput = any>(\n [first, ...runnables]: [\n RunnableLike<RunInput>,\n ...RunnableLike[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunnableLike<any, RunOutput>,\n ],\n config: { singleAction: boolean; streamRunnable?: boolean; name?: string }\n ): AgentRunnableSequence<RunInput, Exclude<RunOutput, Error>> {\n const sequence = RunnableSequence.from(\n [first, ...runnables],\n config.name\n ) as AgentRunnableSequence<RunInput, Exclude<RunOutput, Error>>;\n sequence.singleAction = config.singleAction;\n sequence.streamRunnable = config.streamRunnable;\n return sequence;\n }\n\n static isAgentRunnableSequence(x: Runnable): x is AgentRunnableSequence {\n return typeof (x as AgentRunnableSequence).singleAction === \"boolean\";\n }\n}\n\n/**\n * Class representing a single-action agent powered by runnables.\n * Extends the BaseSingleActionAgent class and provides methods for\n * planning agent actions with runnables.\n */\nexport class RunnableSingleActionAgent extends BaseSingleActionAgent {\n lc_namespace = [\"langchain\", \"agents\", \"runnable\"];\n\n runnable: Runnable<\n ChainValues & { steps: AgentStep[] },\n AgentAction | AgentFinish\n >;\n\n get inputKeys(): string[] {\n return [];\n }\n\n /**\n * Whether to stream from the runnable or not.\n * If true, the underlying LLM is invoked in a streaming fashion to make it\n * possible to get access to the individual LLM tokens when using\n * `streamLog` with the Agent Executor. If false then LLM is invoked in a\n * non-streaming fashion and individual LLM tokens will not be available\n * in `streamLog`.\n *\n * Note that the runnable should still only stream a single action or\n * finish chunk.\n */\n streamRunnable = true;\n\n defaultRunName = \"RunnableAgent\";\n\n constructor(fields: RunnableSingleActionAgentInput) {\n super(fields);\n this.runnable = fields.runnable;\n this.defaultRunName =\n fields.defaultRunName ?? this.runnable.name ?? this.defaultRunName;\n this.streamRunnable = fields.streamRunnable ?? this.streamRunnable;\n }\n\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction | AgentFinish> {\n const combinedInput = { ...inputs, steps };\n const combinedConfig = patchConfig(config, {\n callbacks: callbackManager,\n runName: this.defaultRunName,\n });\n if (this.streamRunnable) {\n const stream = await this.runnable.stream(combinedInput, combinedConfig);\n let finalOutput: AgentAction | AgentFinish | undefined;\n for await (const chunk of stream) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n throw new Error(\n [\n `Multiple agent actions/finishes received in streamed agent output.`,\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n }\n if (finalOutput === undefined) {\n throw new Error(\n [\n \"No streaming output received from underlying runnable.\",\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n return finalOutput;\n } else {\n return this.runnable.invoke(combinedInput, combinedConfig);\n }\n }\n}\n\n/**\n * Class representing a multi-action agent powered by runnables.\n * Extends the BaseMultiActionAgent class and provides methods for\n * planning agent actions with runnables.\n */\nexport class RunnableMultiActionAgent extends BaseMultiActionAgent {\n lc_namespace = [\"langchain\", \"agents\", \"runnable\"];\n\n // TODO: Rename input to \"intermediate_steps\"\n runnable: Runnable<\n ChainValues & { steps: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n\n defaultRunName = \"RunnableAgent\";\n\n stop?: string[];\n\n streamRunnable = true;\n\n get inputKeys(): string[] {\n return [];\n }\n\n constructor(fields: RunnableMultiActionAgentInput) {\n super(fields);\n this.runnable = fields.runnable;\n this.stop = fields.stop;\n this.defaultRunName =\n fields.defaultRunName ?? this.runnable.name ?? this.defaultRunName;\n this.streamRunnable = fields.streamRunnable ?? this.streamRunnable;\n }\n\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager,\n config?: RunnableConfig\n ): Promise<AgentAction[] | AgentFinish> {\n const combinedInput = { ...inputs, steps };\n const combinedConfig = patchConfig(config, {\n callbacks: callbackManager,\n runName: this.defaultRunName,\n });\n let output;\n if (this.streamRunnable) {\n const stream = await this.runnable.stream(combinedInput, combinedConfig);\n let finalOutput: AgentAction | AgentFinish | AgentAction[] | undefined;\n for await (const chunk of stream) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n throw new Error(\n [\n `Multiple agent actions/finishes received in streamed agent output.`,\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n }\n if (finalOutput === undefined) {\n throw new Error(\n [\n \"No streaming output received from underlying runnable.\",\n `Set \"streamRunnable: false\" when initializing the agent to invoke this agent in non-streaming mode.`,\n ].join(\"\\n\")\n );\n }\n output = finalOutput;\n } else {\n output = await this.runnable.invoke(combinedInput, combinedConfig);\n }\n\n if (isAgentAction(output)) {\n return [output];\n }\n\n return output;\n }\n}\n\nexport class RunnableAgent extends RunnableMultiActionAgent {}\n\n/**\n * Interface for input data for creating a LLMSingleActionAgent.\n */\nexport interface LLMSingleActionAgentInput {\n llmChain: LLMChain;\n outputParser: AgentActionOutputParser;\n stop?: string[];\n}\n\n/**\n * Class representing a single action agent using a LLMChain in LangChain.\n * Extends the BaseSingleActionAgent class and provides methods for\n * planning agent actions based on LLMChain outputs.\n * @example\n * ```typescript\n * const customPromptTemplate = new CustomPromptTemplate({\n * tools: [new Calculator()],\n * inputVariables: [\"input\", \"agent_scratchpad\"],\n * });\n * const customOutputParser = new CustomOutputParser();\n * const agent = new LLMSingleActionAgent({\n * llmChain: new LLMChain({\n * prompt: customPromptTemplate,\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * }),\n * outputParser: customOutputParser,\n * stop: [\"\\nObservation\"],\n * });\n * const executor = new AgentExecutor({\n * agent,\n * tools: [new Calculator()],\n * });\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport class LLMSingleActionAgent extends BaseSingleActionAgent {\n lc_namespace = [\"langchain\", \"agents\"];\n\n llmChain: LLMChain;\n\n outputParser: AgentActionOutputParser;\n\n stop?: string[];\n\n constructor(input: LLMSingleActionAgentInput) {\n super(input);\n this.stop = input.stop;\n this.llmChain = input.llmChain;\n this.outputParser = input.outputParser;\n }\n\n get inputKeys(): string[] {\n return this.llmChain.inputKeys;\n }\n\n /**\n * Decide what to do given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager.\n *\n * @returns Action specifying what tool to use.\n */\n async plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n const output = await this.llmChain.call(\n {\n intermediate_steps: steps,\n stop: this.stop,\n ...inputs,\n },\n callbackManager\n );\n return this.outputParser.parse(\n output[this.llmChain.outputKey],\n callbackManager\n );\n }\n}\n\n/**\n * Interface for arguments used to create an agent in LangChain.\n */\nexport interface AgentArgs {\n outputParser?: AgentActionOutputParser;\n\n callbacks?: Callbacks;\n\n /**\n * @deprecated Use `callbacks` instead.\n */\n callbackManager?: CallbackManager;\n}\n\n/**\n * Class responsible for calling a language model and deciding an action.\n *\n * @remarks This is driven by an LLMChain. The prompt in the LLMChain *must*\n * include a variable called \"agent_scratchpad\" where the agent can put its\n * intermediary work.\n */\nexport abstract class Agent extends BaseSingleActionAgent {\n llmChain: LLMChain;\n\n outputParser: AgentActionOutputParser | undefined;\n\n private _allowedTools?: string[] = undefined;\n\n get allowedTools(): string[] | undefined {\n return this._allowedTools;\n }\n\n get inputKeys(): string[] {\n return this.llmChain.inputKeys.filter((k) => k !== \"agent_scratchpad\");\n }\n\n constructor(input: AgentInput) {\n super(input);\n\n this.llmChain = input.llmChain;\n this._allowedTools = input.allowedTools;\n this.outputParser = input.outputParser;\n }\n\n /**\n * Prefix to append the observation with.\n */\n abstract observationPrefix(): string;\n\n /**\n * Prefix to append the LLM call with.\n */\n abstract llmPrefix(): string;\n\n /**\n * Return the string type key uniquely identifying this class of agent.\n */\n abstract _agentType(): string;\n\n /**\n * Get the default output parser for this agent.\n */\n static getDefaultOutputParser(\n _fields?: OutputParserArgs\n ): AgentActionOutputParser {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Create a prompt for this class\n *\n * @param _tools - List of tools the agent will have access to, used to format the prompt.\n * @param _fields - Additional fields used to format the prompt.\n *\n * @returns A PromptTemplate assembled from the given tools and fields.\n * */\n static createPrompt(\n _tools: StructuredToolInterface[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _fields?: Record<string, any>\n ): BasePromptTemplate {\n throw new Error(\"Not implemented\");\n }\n\n /** Construct an agent from an LLM and a list of tools */\n static fromLLMAndTools(\n _llm: BaseLanguageModelInterface,\n _tools: StructuredToolInterface[],\n\n _args?: AgentArgs\n ): Agent {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Validate that appropriate tools are passed in\n */\n static validateTools(_tools: StructuredToolInterface[]): void {}\n\n _stop(): string[] {\n return [`\\n${this.observationPrefix()}`];\n }\n\n /**\n * Name of tool to use to terminate the chain.\n */\n finishToolName(): string {\n return \"Final Answer\";\n }\n\n /**\n * Construct a scratchpad to let the agent continue its thought process\n */\n async constructScratchPad(\n steps: AgentStep[]\n ): Promise<string | BaseMessage[]> {\n return steps.reduce(\n (thoughts, { action, observation }) =>\n thoughts +\n [\n action.log,\n `${this.observationPrefix()}${observation}`,\n this.llmPrefix(),\n ].join(\"\\n\"),\n \"\"\n );\n }\n\n private async _plan(\n steps: AgentStep[],\n inputs: ChainValues,\n suffix?: string,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n const thoughts = await this.constructScratchPad(steps);\n const newInputs: ChainValues = {\n ...inputs,\n agent_scratchpad: suffix ? `${thoughts}${suffix}` : thoughts,\n };\n\n if (this._stop().length !== 0) {\n newInputs.stop = this._stop();\n }\n\n const output = await this.llmChain.predict(newInputs, callbackManager);\n if (!this.outputParser) {\n throw new Error(\"Output parser not set\");\n }\n return this.outputParser.parse(output, callbackManager);\n }\n\n /**\n * Decide what to do given some input.\n *\n * @param steps - Steps the LLM has taken so far, along with observations from each.\n * @param inputs - User inputs.\n * @param callbackManager - Callback manager to use for this call.\n *\n * @returns Action specifying what tool to use.\n */\n plan(\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentAction | AgentFinish> {\n return this._plan(steps, inputs, undefined, callbackManager);\n }\n\n /**\n * Return response when agent has been stopped due to max iterations\n */\n async returnStoppedResponse(\n earlyStoppingMethod: StoppingMethod,\n steps: AgentStep[],\n inputs: ChainValues,\n callbackManager?: CallbackManager\n ): Promise<AgentFinish> {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: { output: \"Agent stopped due to max iterations.\" },\n log: \"\",\n };\n }\n\n if (earlyStoppingMethod === \"generate\") {\n try {\n const action = await this._plan(\n steps,\n inputs,\n \"\\n\\nI now need to return a final answer based on the previous steps:\",\n callbackManager\n );\n if (\"returnValues\" in action) {\n return action;\n }\n\n return { returnValues: { output: action.log }, log: action.log };\n } catch (err) {\n // fine to use instanceof because we're in the same module\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (!(err instanceof ParseError)) {\n throw err;\n }\n return { returnValues: { output: err.output }, log: err.output };\n }\n }\n\n throw new Error(`Invalid stopping method: ${earlyStoppingMethod}`);\n }\n\n /**\n * Load an agent from a json-like object describing it.\n */\n static async deserialize(\n data: SerializedAgent & {\n llm?: BaseLanguageModelInterface;\n tools?: ToolInterface[];\n }\n ): Promise<Agent> {\n switch (data._type) {\n case \"zero-shot-react-description\": {\n const { ZeroShotAgent } = await import(\"./mrkl/index.js\");\n return ZeroShotAgent.deserialize(data);\n }\n default:\n throw new Error(\"Unknown agent type\");\n }\n }\n}\n"],"mappings":";;;;;;;AAsCA,IAAM,aAAN,cAAyB,MAAM;CAC7B;CAEA,YAAY,KAAa,QAAgB;EACvC,MAAM,GAAG;EACT,KAAK,SAAS;CAChB;AACF;;;;;AAMA,IAAsB,YAAtB,cAAwCA,kCAAAA,aAAa;CAKnD,IAAI,eAAyB;EAC3B,OAAO,CAAC,QAAQ;CAClB;CAEA,IAAI,eAAqC,CAEzC;;;;CAKA,aAAqB;EACnB,MAAM,IAAI,MAAM,iBAAiB;CACnC;;;;CAUA,sBACE,qBACA,QACA,SACA,kBACsB;EACtB,IAAI,wBAAwB,SAC1B,OAAO,QAAQ,QAAQ;GACrB,cAAc,EAAE,QAAQ,uCAAuC;GAC/D,KAAK;EACP,CAAC;EAGH,MAAM,IAAI,MAAM,4BAA4B,qBAAqB;CACnE;;;;CAKA,MAAM,iBACJ,eACA,QACsC;EACtC,OAAO,CAAC;CACV;AACF;;;;;;AAOA,IAAsB,wBAAtB,cAAoD,UAAU;CAC5D,mBAA2B;EACzB,OAAO;CACT;AAiBF;;;;;;AAOA,IAAsB,uBAAtB,cAAmD,UAAU;CAC3D,mBAA2B;EACzB,OAAO;CACT;AAiBF;AAEA,SAAS,cAAc,OAAsC;CAC3D,OAAO,CAAC,MAAM,QAAQ,KAAK,KAAM,OAAuB,SAAS,KAAA;AACnE;AAEA,SAAgB,gBAAgB,GAAc;CAC5C,OACG,EAA2D,aAC5D,KAAA;AAEJ;AAKA,IAAa,wBAAb,cAKUC,0BAAAA,iBAAsC;CAC9C;CAEA;CAGA,OAAO,cACL,CAAC,OAAO,GAAG,YAMX,QAC4D;EAC5D,MAAM,WAAWA,0BAAAA,iBAAiB,KAChC,CAAC,OAAO,GAAG,SAAS,GACpB,OAAO,IACT;EACA,SAAS,eAAe,OAAO;EAC/B,SAAS,iBAAiB,O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AW,eAAe;EACrE,IAAI,CAAC,KAAK,cACR,MAAM,IAAI,MAAM,uBAAuB;EAEzC,OAAO,KAAK,aAAa,MAAM,QAAQ,eAAe;CACxD;;;;;;;;;;CAWA,KACE,OACA,QACA,iBACoC;EACpC,OAAO,KAAK,MAAM,OAAO,QAAQ,KAAA,GAAW,eAAe;CAC7D;;;;CAKA,MAAM,sBACJ,qBACA,OACA,QACA,iBACsB;EACtB,IAAI,wBAAwB,SAC1B,OAAO;GACL,cAAc,EAAE,QAAQ,uCAAuC;GAC/D,KAAK;EACP;EAGF,IAAI,wBAAwB,YAC1B,IAAI;GACF,MAAM,SAAS,MAAM,KAAK,MACxB,OACA,QACA,wEACA,eACF;GACA,IAAI,kBAAkB,QACpB,OAAO;GAGT,OAAO;IAAE,cAAc,EAAE,QAAQ,OAAO,IAAI;IAAG,KAAK,OAAO;GAAI;EACjE,SAAS,KAAK;GAGZ,IAAI,EAAE,eAAe,aACnB,MAAM;GAER,OAAO;IAAE,cAAc,EAAE,QAAQ,IAAI,OAAO;IAAG,KAAK,IAAI;GAAO;EACjE;EAGF,MAAM,IAAI,MAAM,4BAA4B,qBAAqB;CACnE;;;;CAKA,aAAa,YACX,MAIgB;EAChB,QAAQ,KAAK,OAAb;GACE,KAAK,+BAA+B;IAClC,MAAM,EAAE,kBAAkB,MAAA,QAAA,QAAA,CAAA,CAAA,WAAA,QAAM,kBAAA,CAAA;IAChC,OAAO,cAAc,YAAY,IAAI;GACvC;GACA,SACE,MAAM,IAAI,MAAM,oBAAoB;EACxC;CACF;AACF"}
|
|
@@ -100,8 +100,9 @@ var ChatAgent = class ChatAgent extends require_agent.Agent {
|
|
|
100
100
|
*/
|
|
101
101
|
static fromLLMAndTools(llm, tools, args) {
|
|
102
102
|
ChatAgent.validateTools(tools);
|
|
103
|
+
const prompt = ChatAgent.createPrompt(tools, args);
|
|
103
104
|
const chain = new require_llm_chain.LLMChain({
|
|
104
|
-
prompt
|
|
105
|
+
prompt,
|
|
105
106
|
llm,
|
|
106
107
|
callbacks: args?.callbacks ?? args?.callbackManager
|
|
107
108
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Agent","ChatAgentOutputParser","PREFIX","SUFFIX","FORMAT_INSTRUCTIONS","SystemMessagePromptTemplate","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain"],"sources":["../../../src/agents/chat/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { ChatAgentOutputParser } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\n\nconst DEFAULT_HUMAN_MESSAGE_TEMPLATE = \"{input}\\n\\n{agent_scratchpad}\";\n\n/**\n * Interface for arguments used to create a chat prompt.\n */\nexport interface ChatCreatePromptArgs {\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 /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** Formattable string to use as the instructions template. */\n formatInstructions?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n}\n\n/**\n * Type for input data for creating a ChatAgent, extending AgentInput with\n * optional 'outputParser'.\n */\nexport type ChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatAgent extends Agent {\n static lc_name() {\n return \"ChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatAgentInput) {\n const outputParser =\n input?.outputParser ?? ChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all tools have descriptions. Throws an error if a tool\n * without a description is found.\n * @param tools Array of Tool instances to validate.\n * @returns void\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 * Returns a default output parser for the ChatAgent.\n * @param _fields Optional OutputParserArgs to customize the output parser.\n * @returns ChatAgentOutputParser instance\n */\n static getDefaultOutputParser(_fields?: OutputParserArgs) {\n return new ChatAgentOutputParser();\n }\n\n /**\n * Constructs the agent's scratchpad, which is a string representation of\n * the agent's previous steps.\n * @param steps Array of AgentStep instances representing the agent's previous steps.\n * @returns Promise resolving to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\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.humanMessageTemplate - String to use directly as the human message template\n * @param args.formatInstructions - Formattable string to use as the instructions template\n */\n static createPrompt(tools: ToolInterface[], args?: ChatCreatePromptArgs) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE,\n formatInstructions = FORMAT_INSTRUCTIONS,\n } = args ?? {};\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const template = [prefix, toolStrings, formatInstructions, suffix].join(\n \"\\n\\n\"\n );\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(template),\n HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a ChatAgent instance using a language model, tools, and\n * optional arguments.\n * @param llm BaseLanguageModelInterface instance to use in the agent.\n * @param tools Array of Tool instances to include in the agent.\n * @param args Optional arguments to customize the agent and prompt.\n * @returns ChatAgent instance\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatCreatePromptArgs & AgentArgs\n ) {\n ChatAgent.validateTools(tools);\n const prompt = ChatAgent.createPrompt(tools, args);\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n const outputParser =\n args?.outputParser ?? ChatAgent.getDefaultOutputParser();\n\n return new ChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;AAeA,MAAM,iCAAiC;;;;;AA4BvC,IAAa,YAAb,MAAa,kBAAkBA,cAAAA,MAAM;CACnC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAM;CAI7C,YAAY,OAAuB;EACjC,MAAM,eACJ,OAAO,gBAAgB,UAAU,uBAAuB;EAC1D,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;;;;;;;CAQA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;CAOA,OAAO,uBAAuB,SAA4B;EACxD,OAAO,IAAIC,qBAAAA,sBAAsB;CACnC;;;;;;;CAQA,MAAM,oBAAoB,OAAqC;EAC7D,MAAM,kBAAkB,MAAM,MAAM,oBAAoB,KAAK;EAC7D,IAAI,iBACF,OAAO,4GAA4G;EAErH,OAAO;CACT;;;;;;;;;;;CAYA,OAAO,aAAa,OAAwB,MAA6B;EACvE,MAAM,EACJ,SAASC,eAAAA,QACT,SAASC,eAAAA,QACT,uBAAuB,gCACvB,qBAAqBC,eAAAA,wBACnB,QAAQ,CAAC;EAIb,MAAM,WAAW;GAAC;GAHE,MACjB,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,aAAa,CAAC,CAClD,KAAK,IAC4B;GAAG;GAAoB;EAAM,CAAC,CAAC,KACjE,MACF;EACA,MAAM,WAAW,CACfC,wBAAAA,4BAA4B,aAAa,QAAQ,GACjDC,wBAAAA,2BAA2B,aAAa,oBAAoB,CAC9D;EACA,OAAOC,wBAAAA,mBAAmB,aAAa,QAAQ;CACjD;;;;;;;;;CAUA,OAAO,gBACL,KACA,OACA,MACA;EACA,UAAU,cAAc,KAAK;
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Agent","ChatAgentOutputParser","PREFIX","SUFFIX","FORMAT_INSTRUCTIONS","SystemMessagePromptTemplate","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain"],"sources":["../../../src/agents/chat/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { ChatAgentOutputParser } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\n\nconst DEFAULT_HUMAN_MESSAGE_TEMPLATE = \"{input}\\n\\n{agent_scratchpad}\";\n\n/**\n * Interface for arguments used to create a chat prompt.\n */\nexport interface ChatCreatePromptArgs {\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 /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** Formattable string to use as the instructions template. */\n formatInstructions?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n}\n\n/**\n * Type for input data for creating a ChatAgent, extending AgentInput with\n * optional 'outputParser'.\n */\nexport type ChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatAgent extends Agent {\n static lc_name() {\n return \"ChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatAgentInput) {\n const outputParser =\n input?.outputParser ?? ChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all tools have descriptions. Throws an error if a tool\n * without a description is found.\n * @param tools Array of Tool instances to validate.\n * @returns void\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 * Returns a default output parser for the ChatAgent.\n * @param _fields Optional OutputParserArgs to customize the output parser.\n * @returns ChatAgentOutputParser instance\n */\n static getDefaultOutputParser(_fields?: OutputParserArgs) {\n return new ChatAgentOutputParser();\n }\n\n /**\n * Constructs the agent's scratchpad, which is a string representation of\n * the agent's previous steps.\n * @param steps Array of AgentStep instances representing the agent's previous steps.\n * @returns Promise resolving to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\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.humanMessageTemplate - String to use directly as the human message template\n * @param args.formatInstructions - Formattable string to use as the instructions template\n */\n static createPrompt(tools: ToolInterface[], args?: ChatCreatePromptArgs) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE,\n formatInstructions = FORMAT_INSTRUCTIONS,\n } = args ?? {};\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const template = [prefix, toolStrings, formatInstructions, suffix].join(\n \"\\n\\n\"\n );\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(template),\n HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a ChatAgent instance using a language model, tools, and\n * optional arguments.\n * @param llm BaseLanguageModelInterface instance to use in the agent.\n * @param tools Array of Tool instances to include in the agent.\n * @param args Optional arguments to customize the agent and prompt.\n * @returns ChatAgent instance\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatCreatePromptArgs & AgentArgs\n ) {\n ChatAgent.validateTools(tools);\n const prompt = ChatAgent.createPrompt(tools, args);\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n const outputParser =\n args?.outputParser ?? ChatAgent.getDefaultOutputParser();\n\n return new ChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;AAeA,MAAM,iCAAiC;;;;;AA4BvC,IAAa,YAAb,MAAa,kBAAkBA,cAAAA,MAAM;CACnC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAM;CAI7C,YAAY,OAAuB;EACjC,MAAM,eACJ,OAAO,gBAAgB,UAAU,uBAAuB;EAC1D,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;;;;;;;CAQA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;CAOA,OAAO,uBAAuB,SAA4B;EACxD,OAAO,IAAIC,qBAAAA,sBAAsB;CACnC;;;;;;;CAQA,MAAM,oBAAoB,OAAqC;EAC7D,MAAM,kBAAkB,MAAM,MAAM,oBAAoB,KAAK;EAC7D,IAAI,iBACF,OAAO,4GAA4G;EAErH,OAAO;CACT;;;;;;;;;;;CAYA,OAAO,aAAa,OAAwB,MAA6B;EACvE,MAAM,EACJ,SAASC,eAAAA,QACT,SAASC,eAAAA,QACT,uBAAuB,gCACvB,qBAAqBC,eAAAA,wBACnB,QAAQ,CAAC;EAIb,MAAM,WAAW;GAAC;GAHE,MACjB,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,aAAa,CAAC,CAClD,KAAK,IAC4B;GAAG;GAAoB;EAAM,CAAC,CAAC,KACjE,MACF;EACA,MAAM,WAAW,CACfC,wBAAAA,4BAA4B,aAAa,QAAQ,GACjDC,wBAAAA,2BAA2B,aAAa,oBAAoB,CAC9D;EACA,OAAOC,wBAAAA,mBAAmB,aAAa,QAAQ;CACjD;;;;;;;;;CAUA,OAAO,gBACL,KACA,OACA,MACA;EACA,UAAU,cAAc,KAAK;EAC7B,MAAM,SAAS,UAAU,aAAa,OAAO,IAAI;EACjD,MAAM,QAAQ,IAAIC,kBAAAA,SAAS;GACzB;GACA;GACA,WAAW,MAAM,aAAa,MAAM;EACtC,CAAC;EACD,MAAM,eACJ,MAAM,gBAAgB,UAAU,uBAAuB;EAEzD,OAAO,IAAI,UAAU;GACnB,UAAU;GACV;GACA,cAAc,MAAM,KAAK,MAAM,EAAE,IAAI;EACvC,CAAC;CACH;AACF"}
|
|
@@ -100,8 +100,9 @@ var ChatAgent = class ChatAgent extends Agent {
|
|
|
100
100
|
*/
|
|
101
101
|
static fromLLMAndTools(llm, tools, args) {
|
|
102
102
|
ChatAgent.validateTools(tools);
|
|
103
|
+
const prompt = ChatAgent.createPrompt(tools, args);
|
|
103
104
|
const chain = new LLMChain({
|
|
104
|
-
prompt
|
|
105
|
+
prompt,
|
|
105
106
|
llm,
|
|
106
107
|
callbacks: args?.callbacks ?? args?.callbackManager
|
|
107
108
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/chat/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { ChatAgentOutputParser } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\n\nconst DEFAULT_HUMAN_MESSAGE_TEMPLATE = \"{input}\\n\\n{agent_scratchpad}\";\n\n/**\n * Interface for arguments used to create a chat prompt.\n */\nexport interface ChatCreatePromptArgs {\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 /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** Formattable string to use as the instructions template. */\n formatInstructions?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n}\n\n/**\n * Type for input data for creating a ChatAgent, extending AgentInput with\n * optional 'outputParser'.\n */\nexport type ChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatAgent extends Agent {\n static lc_name() {\n return \"ChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatAgentInput) {\n const outputParser =\n input?.outputParser ?? ChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all tools have descriptions. Throws an error if a tool\n * without a description is found.\n * @param tools Array of Tool instances to validate.\n * @returns void\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 * Returns a default output parser for the ChatAgent.\n * @param _fields Optional OutputParserArgs to customize the output parser.\n * @returns ChatAgentOutputParser instance\n */\n static getDefaultOutputParser(_fields?: OutputParserArgs) {\n return new ChatAgentOutputParser();\n }\n\n /**\n * Constructs the agent's scratchpad, which is a string representation of\n * the agent's previous steps.\n * @param steps Array of AgentStep instances representing the agent's previous steps.\n * @returns Promise resolving to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\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.humanMessageTemplate - String to use directly as the human message template\n * @param args.formatInstructions - Formattable string to use as the instructions template\n */\n static createPrompt(tools: ToolInterface[], args?: ChatCreatePromptArgs) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE,\n formatInstructions = FORMAT_INSTRUCTIONS,\n } = args ?? {};\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const template = [prefix, toolStrings, formatInstructions, suffix].join(\n \"\\n\\n\"\n );\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(template),\n HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a ChatAgent instance using a language model, tools, and\n * optional arguments.\n * @param llm BaseLanguageModelInterface instance to use in the agent.\n * @param tools Array of Tool instances to include in the agent.\n * @param args Optional arguments to customize the agent and prompt.\n * @returns ChatAgent instance\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatCreatePromptArgs & AgentArgs\n ) {\n ChatAgent.validateTools(tools);\n const prompt = ChatAgent.createPrompt(tools, args);\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n const outputParser =\n args?.outputParser ?? ChatAgent.getDefaultOutputParser();\n\n return new ChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;AAeA,MAAM,iCAAiC;;;;;AA4BvC,IAAa,YAAb,MAAa,kBAAkB,MAAM;CACnC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAM;CAI7C,YAAY,OAAuB;EACjC,MAAM,eACJ,OAAO,gBAAgB,UAAU,uBAAuB;EAC1D,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;;;;;;;CAQA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;CAOA,OAAO,uBAAuB,SAA4B;EACxD,OAAO,IAAI,sBAAsB;CACnC;;;;;;;CAQA,MAAM,oBAAoB,OAAqC;EAC7D,MAAM,kBAAkB,MAAM,MAAM,oBAAoB,KAAK;EAC7D,IAAI,iBACF,OAAO,4GAA4G;EAErH,OAAO;CACT;;;;;;;;;;;CAYA,OAAO,aAAa,OAAwB,MAA6B;EACvE,MAAM,EACJ,SAAS,QACT,SAAS,QACT,uBAAuB,gCACvB,qBAAqB,wBACnB,QAAQ,CAAC;EAIb,MAAM,WAAW;GAAC;GAHE,MACjB,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,aAAa,CAAC,CAClD,KAAK,IAC4B;GAAG;GAAoB;EAAM,CAAC,CAAC,KACjE,MACF;EACA,MAAM,WAAW,CACf,4BAA4B,aAAa,QAAQ,GACjD,2BAA2B,aAAa,oBAAoB,CAC9D;EACA,OAAO,mBAAmB,aAAa,QAAQ;CACjD;;;;;;;;;CAUA,OAAO,gBACL,KACA,OACA,MACA;EACA,UAAU,cAAc,KAAK;
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/chat/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { ChatAgentOutputParser } from \"./outputParser.js\";\nimport { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from \"./prompt.js\";\n\nconst DEFAULT_HUMAN_MESSAGE_TEMPLATE = \"{input}\\n\\n{agent_scratchpad}\";\n\n/**\n * Interface for arguments used to create a chat prompt.\n */\nexport interface ChatCreatePromptArgs {\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 /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** Formattable string to use as the instructions template. */\n formatInstructions?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n}\n\n/**\n * Type for input data for creating a ChatAgent, extending AgentInput with\n * optional 'outputParser'.\n */\nexport type ChatAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatAgent extends Agent {\n static lc_name() {\n return \"ChatAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatAgentInput) {\n const outputParser =\n input?.outputParser ?? ChatAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-zero-shot-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\n\n /**\n * Validates that all tools have descriptions. Throws an error if a tool\n * without a description is found.\n * @param tools Array of Tool instances to validate.\n * @returns void\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 * Returns a default output parser for the ChatAgent.\n * @param _fields Optional OutputParserArgs to customize the output parser.\n * @returns ChatAgentOutputParser instance\n */\n static getDefaultOutputParser(_fields?: OutputParserArgs) {\n return new ChatAgentOutputParser();\n }\n\n /**\n * Constructs the agent's scratchpad, which is a string representation of\n * the agent's previous steps.\n * @param steps Array of AgentStep instances representing the agent's previous steps.\n * @returns Promise resolving to a string representing the agent's scratchpad.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<string> {\n const agentScratchpad = await super.constructScratchPad(steps);\n if (agentScratchpad) {\n return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\\n${agentScratchpad}`;\n }\n return agentScratchpad;\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.humanMessageTemplate - String to use directly as the human message template\n * @param args.formatInstructions - Formattable string to use as the instructions template\n */\n static createPrompt(tools: ToolInterface[], args?: ChatCreatePromptArgs) {\n const {\n prefix = PREFIX,\n suffix = SUFFIX,\n humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE,\n formatInstructions = FORMAT_INSTRUCTIONS,\n } = args ?? {};\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const template = [prefix, toolStrings, formatInstructions, suffix].join(\n \"\\n\\n\"\n );\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(template),\n HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates a ChatAgent instance using a language model, tools, and\n * optional arguments.\n * @param llm BaseLanguageModelInterface instance to use in the agent.\n * @param tools Array of Tool instances to include in the agent.\n * @param args Optional arguments to customize the agent and prompt.\n * @returns ChatAgent instance\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatCreatePromptArgs & AgentArgs\n ) {\n ChatAgent.validateTools(tools);\n const prompt = ChatAgent.createPrompt(tools, args);\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n const outputParser =\n args?.outputParser ?? ChatAgent.getDefaultOutputParser();\n\n return new ChatAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;AAeA,MAAM,iCAAiC;;;;;AA4BvC,IAAa,YAAb,MAAa,kBAAkB,MAAM;CACnC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAM;CAI7C,YAAY,OAAuB;EACjC,MAAM,eACJ,OAAO,gBAAgB,UAAU,uBAAuB;EAC1D,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;;;;;;;CAQA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;CAOA,OAAO,uBAAuB,SAA4B;EACxD,OAAO,IAAI,sBAAsB;CACnC;;;;;;;CAQA,MAAM,oBAAoB,OAAqC;EAC7D,MAAM,kBAAkB,MAAM,MAAM,oBAAoB,KAAK;EAC7D,IAAI,iBACF,OAAO,4GAA4G;EAErH,OAAO;CACT;;;;;;;;;;;CAYA,OAAO,aAAa,OAAwB,MAA6B;EACvE,MAAM,EACJ,SAAS,QACT,SAAS,QACT,uBAAuB,gCACvB,qBAAqB,wBACnB,QAAQ,CAAC;EAIb,MAAM,WAAW;GAAC;GAHE,MACjB,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,aAAa,CAAC,CAClD,KAAK,IAC4B;GAAG;GAAoB;EAAM,CAAC,CAAC,KACjE,MACF;EACA,MAAM,WAAW,CACf,4BAA4B,aAAa,QAAQ,GACjD,2BAA2B,aAAa,oBAAoB,CAC9D;EACA,OAAO,mBAAmB,aAAa,QAAQ;CACjD;;;;;;;;;CAUA,OAAO,gBACL,KACA,OACA,MACA;EACA,UAAU,cAAc,KAAK;EAC7B,MAAM,SAAS,UAAU,aAAa,OAAO,IAAI;EACjD,MAAM,QAAQ,IAAI,SAAS;GACzB;GACA;GACA,WAAW,MAAM,aAAa,MAAM;EACtC,CAAC;EACD,MAAM,eACJ,MAAM,gBAAgB,UAAU,uBAAuB;EAEzD,OAAO,IAAI,UAAU;GACnB,UAAU;GACV;GACA,cAAc,MAAM,KAAK,MAAM,EAAE,IAAI;EACvC,CAAC;CACH;AACF"}
|
|
@@ -83,8 +83,9 @@ var ChatConversationalAgent = class ChatConversationalAgent extends require_agen
|
|
|
83
83
|
const humanMessage = args?.humanMessage ?? require_prompt.DEFAULT_SUFFIX;
|
|
84
84
|
const toolStrings = tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n");
|
|
85
85
|
const toolNames = tools.map((tool) => tool.name);
|
|
86
|
+
const formatInstructions = (args?.outputParser ?? ChatConversationalAgent.getDefaultOutputParser({ toolNames })).getFormatInstructions({ toolNames });
|
|
86
87
|
const renderedHumanMessage = (0, _langchain_core_prompts.renderTemplate)(humanMessage, "f-string", {
|
|
87
|
-
format_instructions:
|
|
88
|
+
format_instructions: formatInstructions,
|
|
88
89
|
tools: toolStrings
|
|
89
90
|
});
|
|
90
91
|
const messages = [
|
|
@@ -110,11 +111,12 @@ var ChatConversationalAgent = class ChatConversationalAgent extends require_agen
|
|
|
110
111
|
llm,
|
|
111
112
|
toolNames: tools.map((tool) => tool.name)
|
|
112
113
|
});
|
|
114
|
+
const prompt = ChatConversationalAgent.createPrompt(tools, {
|
|
115
|
+
...args,
|
|
116
|
+
outputParser
|
|
117
|
+
});
|
|
113
118
|
const chain = new require_llm_chain.LLMChain({
|
|
114
|
-
prompt
|
|
115
|
-
...args,
|
|
116
|
-
outputParser
|
|
117
|
-
}),
|
|
119
|
+
prompt,
|
|
118
120
|
llm,
|
|
119
121
|
callbacks: args?.callbacks ?? args?.callbackManager
|
|
120
122
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Agent","AIMessage","HumanMessage","TEMPLATE_TOOL_RESPONSE","ChatConversationalAgentOutputParserWithRetries","DEFAULT_PREFIX","PREFIX_END","DEFAULT_SUFFIX","SystemMessagePromptTemplate","MessagesPlaceholder","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain"],"sources":["../../../src/agents/chat_convo/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n MessagesPlaceholder,\n SystemMessagePromptTemplate,\n renderTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport {\n type BaseMessage,\n HumanMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser, AgentInput } from \"../types.js\";\nimport { ChatConversationalAgentOutputParserWithRetries } from \"./outputParser.js\";\nimport {\n PREFIX_END,\n DEFAULT_PREFIX,\n DEFAULT_SUFFIX,\n TEMPLATE_TOOL_RESPONSE,\n} from \"./prompt.js\";\n\n/**\n * Interface defining the structure of arguments used to create a prompt\n * for the ChatConversationalAgent class.\n */\nexport interface ChatConversationalCreatePromptArgs {\n /** String to put after the list of tools. */\n systemMessage?: string;\n /** String to put before the list of tools. */\n humanMessage?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** Output parser to use for formatting. */\n outputParser?: AgentActionOutputParser;\n}\n\n/**\n * Type that extends the AgentInput interface for the\n * ChatConversationalAgent class, making the outputParser property\n * optional.\n */\nexport type ChatConversationalAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatConversationalAgent extends Agent {\n static lc_name() {\n return \"ChatConversationalAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatConversationalAgentInput) {\n const outputParser =\n input.outputParser ?? ChatConversationalAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-conversational-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\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 * Constructs the agent scratchpad based on the agent steps. It returns an\n * array of base messages representing the thoughts of the agent.\n * @param steps The agent steps to construct the scratchpad from.\n * @returns An array of base messages representing the thoughts of the agent.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<BaseMessage[]> {\n const thoughts: BaseMessage[] = [];\n for (const step of steps) {\n thoughts.push(new AIMessage(step.action.log));\n thoughts.push(\n new HumanMessage(\n renderTemplate(TEMPLATE_TOOL_RESPONSE, \"f-string\", {\n observation: step.observation,\n })\n )\n );\n }\n return thoughts;\n }\n\n /**\n * Returns the default output parser for the ChatConversationalAgent\n * class. It takes optional fields as arguments to customize the output\n * parser.\n * @param fields Optional fields to customize the output parser.\n * @returns The default output parser for the ChatConversationalAgent class.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ): AgentActionOutputParser {\n if (fields?.llm) {\n return ChatConversationalAgentOutputParserWithRetries.fromLLM(\n fields.llm,\n {\n toolNames: fields.toolNames,\n }\n );\n }\n return new ChatConversationalAgentOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Create prompt in the style of the ChatConversationAgent.\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.systemMessage - String to put before the list of tools.\n * @param args.humanMessage - String to put after the list of tools.\n * @param args.outputParser - Output parser to use for formatting.\n */\n static createPrompt(\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs\n ) {\n const systemMessage = (args?.systemMessage ?? DEFAULT_PREFIX) + PREFIX_END;\n const humanMessage = args?.humanMessage ?? DEFAULT_SUFFIX;\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const toolNames = tools.map((tool) => tool.name);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({ toolNames });\n const formatInstructions = outputParser.getFormatInstructions({\n toolNames,\n });\n const renderedHumanMessage = renderTemplate(humanMessage, \"f-string\", {\n format_instructions: formatInstructions,\n tools: toolStrings,\n });\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(systemMessage),\n new MessagesPlaceholder(\"chat_history\"),\n HumanMessagePromptTemplate.fromTemplate(renderedHumanMessage),\n new MessagesPlaceholder(\"agent_scratchpad\"),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates an instance of the ChatConversationalAgent class from a\n * BaseLanguageModel and a set of tools. It takes optional arguments to\n * customize the agent.\n * @param llm The BaseLanguageModel to create the agent from.\n * @param tools The set of tools to create the agent from.\n * @param args Optional arguments to customize the agent.\n * @returns An instance of the ChatConversationalAgent class.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs & AgentArgs\n ) {\n ChatConversationalAgent.validateTools(tools);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const prompt = ChatConversationalAgent.createPrompt(tools, {\n ...args,\n outputParser,\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n return new ChatConversationalAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,IAAa,0BAAb,MAAa,gCAAgCA,cAAAA,MAAM;CACjD,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAY;CAInD,YAAY,OAAqC;EAC/C,MAAM,eACJ,MAAM,gBAAgB,wBAAwB,uBAAuB;EACvE,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;CAEA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;;CAQA,MAAM,oBAAoB,OAA4C;EACpE,MAAM,WAA0B,CAAC;EACjC,KAAK,MAAM,QAAQ,OAAO;GACxB,SAAS,KAAK,IAAIC,yBAAAA,UAAU,KAAK,OAAO,GAAG,CAAC;GAC5C,SAAS,KACP,IAAIC,yBAAAA,cAAAA,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Agent","AIMessage","HumanMessage","renderTemplate","TEMPLATE_TOOL_RESPONSE","ChatConversationalAgentOutputParserWithRetries","DEFAULT_PREFIX","PREFIX_END","DEFAULT_SUFFIX","SystemMessagePromptTemplate","MessagesPlaceholder","HumanMessagePromptTemplate","ChatPromptTemplate","LLMChain"],"sources":["../../../src/agents/chat_convo/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n MessagesPlaceholder,\n SystemMessagePromptTemplate,\n renderTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport {\n type BaseMessage,\n HumanMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser, AgentInput } from \"../types.js\";\nimport { ChatConversationalAgentOutputParserWithRetries } from \"./outputParser.js\";\nimport {\n PREFIX_END,\n DEFAULT_PREFIX,\n DEFAULT_SUFFIX,\n TEMPLATE_TOOL_RESPONSE,\n} from \"./prompt.js\";\n\n/**\n * Interface defining the structure of arguments used to create a prompt\n * for the ChatConversationalAgent class.\n */\nexport interface ChatConversationalCreatePromptArgs {\n /** String to put after the list of tools. */\n systemMessage?: string;\n /** String to put before the list of tools. */\n humanMessage?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** Output parser to use for formatting. */\n outputParser?: AgentActionOutputParser;\n}\n\n/**\n * Type that extends the AgentInput interface for the\n * ChatConversationalAgent class, making the outputParser property\n * optional.\n */\nexport type ChatConversationalAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatConversationalAgent extends Agent {\n static lc_name() {\n return \"ChatConversationalAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatConversationalAgentInput) {\n const outputParser =\n input.outputParser ?? ChatConversationalAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-conversational-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\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 * Constructs the agent scratchpad based on the agent steps. It returns an\n * array of base messages representing the thoughts of the agent.\n * @param steps The agent steps to construct the scratchpad from.\n * @returns An array of base messages representing the thoughts of the agent.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<BaseMessage[]> {\n const thoughts: BaseMessage[] = [];\n for (const step of steps) {\n thoughts.push(new AIMessage(step.action.log));\n thoughts.push(\n new HumanMessage(\n renderTemplate(TEMPLATE_TOOL_RESPONSE, \"f-string\", {\n observation: step.observation,\n })\n )\n );\n }\n return thoughts;\n }\n\n /**\n * Returns the default output parser for the ChatConversationalAgent\n * class. It takes optional fields as arguments to customize the output\n * parser.\n * @param fields Optional fields to customize the output parser.\n * @returns The default output parser for the ChatConversationalAgent class.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ): AgentActionOutputParser {\n if (fields?.llm) {\n return ChatConversationalAgentOutputParserWithRetries.fromLLM(\n fields.llm,\n {\n toolNames: fields.toolNames,\n }\n );\n }\n return new ChatConversationalAgentOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Create prompt in the style of the ChatConversationAgent.\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.systemMessage - String to put before the list of tools.\n * @param args.humanMessage - String to put after the list of tools.\n * @param args.outputParser - Output parser to use for formatting.\n */\n static createPrompt(\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs\n ) {\n const systemMessage = (args?.systemMessage ?? DEFAULT_PREFIX) + PREFIX_END;\n const humanMessage = args?.humanMessage ?? DEFAULT_SUFFIX;\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const toolNames = tools.map((tool) => tool.name);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({ toolNames });\n const formatInstructions = outputParser.getFormatInstructions({\n toolNames,\n });\n const renderedHumanMessage = renderTemplate(humanMessage, \"f-string\", {\n format_instructions: formatInstructions,\n tools: toolStrings,\n });\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(systemMessage),\n new MessagesPlaceholder(\"chat_history\"),\n HumanMessagePromptTemplate.fromTemplate(renderedHumanMessage),\n new MessagesPlaceholder(\"agent_scratchpad\"),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates an instance of the ChatConversationalAgent class from a\n * BaseLanguageModel and a set of tools. It takes optional arguments to\n * customize the agent.\n * @param llm The BaseLanguageModel to create the agent from.\n * @param tools The set of tools to create the agent from.\n * @param args Optional arguments to customize the agent.\n * @returns An instance of the ChatConversationalAgent class.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs & AgentArgs\n ) {\n ChatConversationalAgent.validateTools(tools);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const prompt = ChatConversationalAgent.createPrompt(tools, {\n ...args,\n outputParser,\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n return new ChatConversationalAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,IAAa,0BAAb,MAAa,gCAAgCA,cAAAA,MAAM;CACjD,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAY;CAInD,YAAY,OAAqC;EAC/C,MAAM,eACJ,MAAM,gBAAgB,wBAAwB,uBAAuB;EACvE,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;CAEA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;;CAQA,MAAM,oBAAoB,OAA4C;EACpE,MAAM,WAA0B,CAAC;EACjC,KAAK,MAAM,QAAQ,OAAO;GACxB,SAAS,KAAK,IAAIC,yBAAAA,UAAU,KAAK,OAAO,GAAG,CAAC;GAC5C,SAAS,KACP,IAAIC,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B,aAAa,OAAO;GACzD,GAAG;GACH;EACF,CAAC;EACD,MAAM,QAAQ,IAAIC,kBAAAA,SAAS;GACzB;GACA;GACA,WAAW,MAAM,aAAa,MAAM;EACtC,CAAC;EACD,OAAO,IAAI,wBAAwB;GACjC,UAAU;GACV;GACA,cAAc,MAAM,KAAK,MAAM,EAAE,IAAI;EACvC,CAAC;CACH;AACF"}
|
|
@@ -83,8 +83,9 @@ var ChatConversationalAgent = class ChatConversationalAgent extends Agent {
|
|
|
83
83
|
const humanMessage = args?.humanMessage ?? DEFAULT_SUFFIX;
|
|
84
84
|
const toolStrings = tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n");
|
|
85
85
|
const toolNames = tools.map((tool) => tool.name);
|
|
86
|
+
const formatInstructions = (args?.outputParser ?? ChatConversationalAgent.getDefaultOutputParser({ toolNames })).getFormatInstructions({ toolNames });
|
|
86
87
|
const renderedHumanMessage = renderTemplate(humanMessage, "f-string", {
|
|
87
|
-
format_instructions:
|
|
88
|
+
format_instructions: formatInstructions,
|
|
88
89
|
tools: toolStrings
|
|
89
90
|
});
|
|
90
91
|
const messages = [
|
|
@@ -110,11 +111,12 @@ var ChatConversationalAgent = class ChatConversationalAgent extends Agent {
|
|
|
110
111
|
llm,
|
|
111
112
|
toolNames: tools.map((tool) => tool.name)
|
|
112
113
|
});
|
|
114
|
+
const prompt = ChatConversationalAgent.createPrompt(tools, {
|
|
115
|
+
...args,
|
|
116
|
+
outputParser
|
|
117
|
+
});
|
|
113
118
|
const chain = new LLMChain({
|
|
114
|
-
prompt
|
|
115
|
-
...args,
|
|
116
|
-
outputParser
|
|
117
|
-
}),
|
|
119
|
+
prompt,
|
|
118
120
|
llm,
|
|
119
121
|
callbacks: args?.callbacks ?? args?.callbackManager
|
|
120
122
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/chat_convo/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n MessagesPlaceholder,\n SystemMessagePromptTemplate,\n renderTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport {\n type BaseMessage,\n HumanMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser, AgentInput } from \"../types.js\";\nimport { ChatConversationalAgentOutputParserWithRetries } from \"./outputParser.js\";\nimport {\n PREFIX_END,\n DEFAULT_PREFIX,\n DEFAULT_SUFFIX,\n TEMPLATE_TOOL_RESPONSE,\n} from \"./prompt.js\";\n\n/**\n * Interface defining the structure of arguments used to create a prompt\n * for the ChatConversationalAgent class.\n */\nexport interface ChatConversationalCreatePromptArgs {\n /** String to put after the list of tools. */\n systemMessage?: string;\n /** String to put before the list of tools. */\n humanMessage?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** Output parser to use for formatting. */\n outputParser?: AgentActionOutputParser;\n}\n\n/**\n * Type that extends the AgentInput interface for the\n * ChatConversationalAgent class, making the outputParser property\n * optional.\n */\nexport type ChatConversationalAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatConversationalAgent extends Agent {\n static lc_name() {\n return \"ChatConversationalAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatConversationalAgentInput) {\n const outputParser =\n input.outputParser ?? ChatConversationalAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-conversational-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\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 * Constructs the agent scratchpad based on the agent steps. It returns an\n * array of base messages representing the thoughts of the agent.\n * @param steps The agent steps to construct the scratchpad from.\n * @returns An array of base messages representing the thoughts of the agent.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<BaseMessage[]> {\n const thoughts: BaseMessage[] = [];\n for (const step of steps) {\n thoughts.push(new AIMessage(step.action.log));\n thoughts.push(\n new HumanMessage(\n renderTemplate(TEMPLATE_TOOL_RESPONSE, \"f-string\", {\n observation: step.observation,\n })\n )\n );\n }\n return thoughts;\n }\n\n /**\n * Returns the default output parser for the ChatConversationalAgent\n * class. It takes optional fields as arguments to customize the output\n * parser.\n * @param fields Optional fields to customize the output parser.\n * @returns The default output parser for the ChatConversationalAgent class.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ): AgentActionOutputParser {\n if (fields?.llm) {\n return ChatConversationalAgentOutputParserWithRetries.fromLLM(\n fields.llm,\n {\n toolNames: fields.toolNames,\n }\n );\n }\n return new ChatConversationalAgentOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Create prompt in the style of the ChatConversationAgent.\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.systemMessage - String to put before the list of tools.\n * @param args.humanMessage - String to put after the list of tools.\n * @param args.outputParser - Output parser to use for formatting.\n */\n static createPrompt(\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs\n ) {\n const systemMessage = (args?.systemMessage ?? DEFAULT_PREFIX) + PREFIX_END;\n const humanMessage = args?.humanMessage ?? DEFAULT_SUFFIX;\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const toolNames = tools.map((tool) => tool.name);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({ toolNames });\n const formatInstructions = outputParser.getFormatInstructions({\n toolNames,\n });\n const renderedHumanMessage = renderTemplate(humanMessage, \"f-string\", {\n format_instructions: formatInstructions,\n tools: toolStrings,\n });\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(systemMessage),\n new MessagesPlaceholder(\"chat_history\"),\n HumanMessagePromptTemplate.fromTemplate(renderedHumanMessage),\n new MessagesPlaceholder(\"agent_scratchpad\"),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates an instance of the ChatConversationalAgent class from a\n * BaseLanguageModel and a set of tools. It takes optional arguments to\n * customize the agent.\n * @param llm The BaseLanguageModel to create the agent from.\n * @param tools The set of tools to create the agent from.\n * @param args Optional arguments to customize the agent.\n * @returns An instance of the ChatConversationalAgent class.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs & AgentArgs\n ) {\n ChatConversationalAgent.validateTools(tools);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const prompt = ChatConversationalAgent.createPrompt(tools, {\n ...args,\n outputParser,\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n return new ChatConversationalAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,IAAa,0BAAb,MAAa,gCAAgC,MAAM;CACjD,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAY;CAInD,YAAY,OAAqC;EAC/C,MAAM,eACJ,MAAM,gBAAgB,wBAAwB,uBAAuB;EACvE,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;CACT;CAEA,QAAkB;EAChB,OAAO,CAAC,cAAc;CACxB;CAEA,OAAO,cAAc,OAAwB;EAC3C,MAAM,sBAAsB,MAAM,MAAM,SAAS,CAAC,KAAK,WAAW;EAClE,IAAI,qBAAqB;GACvB,MAAM,MACJ,cAAc,oBAAoB,KAAK;GAEzC,MAAM,IAAI,MAAM,GAAG;EACrB;CACF;;;;;;;CAQA,MAAM,oBAAoB,OAA4C;EACpE,MAAM,WAA0B,CAAC;EACjC,KAAK,MAAM,QAAQ,OAAO;GACxB,SAAS,KAAK,IAAI,UAAU,KAAK,OAAO,GAAG,CAAC;GAC5C,SAAS,KACP,IAAI,aACF,eAAe,wBAAwB,YAAY,EACjD,aAAa,KAAK,YACpB,CAAC,CACH,CACF;EACF;EACA,OAAO;CACT;;;;;;;;CASA,OAAO,uBACL,QAGyB;EACzB,IAAI,QAAQ,KACV,OAAO,+CAA+C,QACpD,OAAO,KACP,EACE,WAAW,OAAO,UACpB,CACF;EAEF,OAAO,IAAI,+CAA+C,EACxD,WAAW,QAAQ,UACrB,CAAC;CACH;;;;;;;;;;CAWA,OAAO,aACL,OACA,MACA;EACA,MAAM,iBAAiB,MAAM,iBAAiB,kBAAkB;EAChE,MAAM,eAAe,MAAM,gBAAgB;EAC3C,MAAM,cAAc,MACjB,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,aAAa,CAAC,CAClD,KAAK,IAAI;EACZ,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,IAAI;
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/chat_convo/index.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { ToolInterface } from \"@langchain/core/tools\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n MessagesPlaceholder,\n SystemMessagePromptTemplate,\n renderTemplate,\n} from \"@langchain/core/prompts\";\nimport type { AgentStep } from \"@langchain/core/agents\";\nimport {\n type BaseMessage,\n HumanMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser, AgentInput } from \"../types.js\";\nimport { ChatConversationalAgentOutputParserWithRetries } from \"./outputParser.js\";\nimport {\n PREFIX_END,\n DEFAULT_PREFIX,\n DEFAULT_SUFFIX,\n TEMPLATE_TOOL_RESPONSE,\n} from \"./prompt.js\";\n\n/**\n * Interface defining the structure of arguments used to create a prompt\n * for the ChatConversationalAgent class.\n */\nexport interface ChatConversationalCreatePromptArgs {\n /** String to put after the list of tools. */\n systemMessage?: string;\n /** String to put before the list of tools. */\n humanMessage?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** Output parser to use for formatting. */\n outputParser?: AgentActionOutputParser;\n}\n\n/**\n * Type that extends the AgentInput interface for the\n * ChatConversationalAgent class, making the outputParser property\n * optional.\n */\nexport type ChatConversationalAgentInput = Optional<AgentInput, \"outputParser\">;\n\n/**\n * Agent for the MRKL chain.\n * @augments Agent\n */\nexport class ChatConversationalAgent extends Agent {\n static lc_name() {\n return \"ChatConversationalAgent\";\n }\n\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n declare ToolType: ToolInterface;\n\n constructor(input: ChatConversationalAgentInput) {\n const outputParser =\n input.outputParser ?? ChatConversationalAgent.getDefaultOutputParser();\n super({ ...input, outputParser });\n }\n\n _agentType() {\n return \"chat-conversational-react-description\" as const;\n }\n\n observationPrefix() {\n return \"Observation: \";\n }\n\n llmPrefix() {\n return \"Thought:\";\n }\n\n _stop(): string[] {\n return [\"Observation:\"];\n }\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 * Constructs the agent scratchpad based on the agent steps. It returns an\n * array of base messages representing the thoughts of the agent.\n * @param steps The agent steps to construct the scratchpad from.\n * @returns An array of base messages representing the thoughts of the agent.\n */\n async constructScratchPad(steps: AgentStep[]): Promise<BaseMessage[]> {\n const thoughts: BaseMessage[] = [];\n for (const step of steps) {\n thoughts.push(new AIMessage(step.action.log));\n thoughts.push(\n new HumanMessage(\n renderTemplate(TEMPLATE_TOOL_RESPONSE, \"f-string\", {\n observation: step.observation,\n })\n )\n );\n }\n return thoughts;\n }\n\n /**\n * Returns the default output parser for the ChatConversationalAgent\n * class. It takes optional fields as arguments to customize the output\n * parser.\n * @param fields Optional fields to customize the output parser.\n * @returns The default output parser for the ChatConversationalAgent class.\n */\n static getDefaultOutputParser(\n fields?: OutputParserArgs & {\n toolNames: string[];\n }\n ): AgentActionOutputParser {\n if (fields?.llm) {\n return ChatConversationalAgentOutputParserWithRetries.fromLLM(\n fields.llm,\n {\n toolNames: fields.toolNames,\n }\n );\n }\n return new ChatConversationalAgentOutputParserWithRetries({\n toolNames: fields?.toolNames,\n });\n }\n\n /**\n * Create prompt in the style of the ChatConversationAgent.\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.systemMessage - String to put before the list of tools.\n * @param args.humanMessage - String to put after the list of tools.\n * @param args.outputParser - Output parser to use for formatting.\n */\n static createPrompt(\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs\n ) {\n const systemMessage = (args?.systemMessage ?? DEFAULT_PREFIX) + PREFIX_END;\n const humanMessage = args?.humanMessage ?? DEFAULT_SUFFIX;\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const toolNames = tools.map((tool) => tool.name);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({ toolNames });\n const formatInstructions = outputParser.getFormatInstructions({\n toolNames,\n });\n const renderedHumanMessage = renderTemplate(humanMessage, \"f-string\", {\n format_instructions: formatInstructions,\n tools: toolStrings,\n });\n const messages = [\n SystemMessagePromptTemplate.fromTemplate(systemMessage),\n new MessagesPlaceholder(\"chat_history\"),\n HumanMessagePromptTemplate.fromTemplate(renderedHumanMessage),\n new MessagesPlaceholder(\"agent_scratchpad\"),\n ];\n return ChatPromptTemplate.fromMessages(messages);\n }\n\n /**\n * Creates an instance of the ChatConversationalAgent class from a\n * BaseLanguageModel and a set of tools. It takes optional arguments to\n * customize the agent.\n * @param llm The BaseLanguageModel to create the agent from.\n * @param tools The set of tools to create the agent from.\n * @param args Optional arguments to customize the agent.\n * @returns An instance of the ChatConversationalAgent class.\n */\n static fromLLMAndTools(\n llm: BaseLanguageModelInterface,\n tools: ToolInterface[],\n args?: ChatConversationalCreatePromptArgs & AgentArgs\n ) {\n ChatConversationalAgent.validateTools(tools);\n const outputParser =\n args?.outputParser ??\n ChatConversationalAgent.getDefaultOutputParser({\n llm,\n toolNames: tools.map((tool) => tool.name),\n });\n const prompt = ChatConversationalAgent.createPrompt(tools, {\n ...args,\n outputParser,\n });\n const chain = new LLMChain({\n prompt,\n llm,\n callbacks: args?.callbacks ?? args?.callbackManager,\n });\n return new ChatConversationalAgent({\n llmChain: chain,\n outputParser,\n allowedTools: tools.map((t) => t.name),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,IAAa,0BAAb,MAAa,gCAAgC,MAAM;CACjD,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe;EAAC;EAAa;EAAU;CAAY;CAInD,YAAY,OAAqC;EAC/C,MAAM,eACJ,MAAM,gBAAgB,wBAAwB,uBAAuB;EACvE,MAAM;GAAE,GAAG;GAAO;EAAa,CAAC;CAClC;CAEA,aAAa;EACX,OAAO;CACT;CAEA,oBAAoB;EAClB,OAAO;CACT;CAEA,YAAY;EACV,OAAO;C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AC5C;EACA,OAAO,mBAAmB,aAAa,QAAQ;CACjD;;;;;;;;;;CAWA,OAAO,gBACL,KACA,OACA,MACA;EACA,wBAAwB,cAAc,KAAK;EAC3C,MAAM,eACJ,MAAM,gBACN,wBAAwB,uBAAuB;GAC7C;GACA,WAAW,MAAM,KAAK,SAAS,KAAK,IAAI;EAC1C,CAAC;EACH,MAAM,SAAS,wBAAwB,aAAa,OAAO;GACzD,GAAG;GACH;EACF,CAAC;EACD,MAAM,QAAQ,IAAI,SAAS;GACzB;GACA;GACA,WAAW,MAAM,aAAa,MAAM;EACtC,CAAC;EACD,OAAO,IAAI,wBAAwB;GACjC,UAAU;GACV;GACA,cAAc,MAAM,KAAK,MAAM,EAAE,IAAI;EACvC,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.cjs","names":["AgentActionOutputParser","OutputParserException","FORMAT_INSTRUCTIONS","OutputFixingParser"],"sources":["../../../src/agents/chat_convo/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport {\n FormatInstructionsOptions,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\nexport type ChatConversationalAgentOutputParserFormatInstructionsOptions =\n FormatInstructionsOptions & {\n toolNames: string[];\n raw?: boolean;\n };\n\n/**\n * Class that represents an output parser for the ChatConversationalAgent\n * class. It extends the AgentActionOutputParser class and provides\n * methods for parsing the output of the MRKL chain into agent actions.\n */\nexport class ChatConversationalAgentOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\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 into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n let jsonOutput = text.trim();\n if (jsonOutput.includes(\"```json\") || jsonOutput.includes(\"```\")) {\n const testString = jsonOutput.includes(\"```json\") ? \"```json\" : \"```\";\n const firstIndex = jsonOutput.indexOf(testString);\n const actionInputIndex = jsonOutput.indexOf(\"action_input\");\n if (actionInputIndex > firstIndex) {\n jsonOutput = jsonOutput\n .slice(firstIndex + testString.length)\n .trimStart();\n const lastIndex = jsonOutput.lastIndexOf(\"```\");\n if (lastIndex !== -1) {\n jsonOutput = jsonOutput.slice(0, lastIndex).trimEnd();\n }\n }\n }\n\n try {\n const response = JSON.parse(jsonOutput);\n\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 as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\nexport type ChatConversationalAgentOutputParserArgs = {\n baseParser?: ChatConversationalAgentOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n};\n\n/**\n * Class that represents an output parser with retries for the\n * ChatConversationalAgent class. It extends the AgentActionOutputParser\n * class and provides methods for parsing the output of the MRKL chain\n * into agent actions with retry functionality.\n */\nexport class ChatConversationalAgentOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n private baseParser: ChatConversationalAgentOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: ChatConversationalAgentOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new ChatConversationalAgentOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Returns the format instructions as a string.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(\n options: ChatConversationalAgentOutputParserFormatInstructionsOptions\n ): string {\n if (options.raw) {\n return FORMAT_INSTRUCTIONS;\n }\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: options.toolNames.join(\", \"),\n });\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Static method to create a new\n * ChatConversationalAgentOutputParserWithRetries from a BaseLanguageModelInterface\n * and options. If no base parser is provided in the options, a new\n * ChatConversationalAgentOutputParser is created. An OutputFixingParser\n * is also created from the BaseLanguageModelInterface and the base parser.\n * @param llm BaseLanguageModelInterface instance used to create the OutputFixingParser.\n * @param options Options for creating the ChatConversationalAgentOutputParserWithRetries instance.\n * @returns A new instance of ChatConversationalAgentOutputParserWithRetries.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<ChatConversationalAgentOutputParserArgs, \"outputFixingParser\">\n ): ChatConversationalAgentOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new ChatConversationalAgentOutputParser({\n toolNames: options.toolNames ?? [],\n });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new ChatConversationalAgentOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAa,sCAAb,cAAyDA,cAAAA,wBAAwB;CAC/E,eAAe;EAAC;EAAa;EAAU;CAAY;CAEnD;CAEA,YAAY,QAAiC;EAC3C,MAAM,GAAG,SAAS;EAClB,KAAK,YAAY,OAAO;CAC1B;;;;;;;CAQA,MAAM,MAAM,MAAkD;EAC5D,IAAI,aAAa,KAAK,KAAK;EAC3B,IAAI,WAAW,SAAS,SAAS,KAAK,WAAW,SAAS,KAAK,GAAG;GAChE,MAAM,aAAa,WAAW,SAAS,SAAS,IAAI,YAAY;GAChE,MAAM,aAAa,WAAW,QAAQ,UAAU;GAEhD,IADyB,WAAW,QAAQ,cACzB,IAAI,YAAY;IACjC,aAAa,WACV,MAAM,aAAa,WAAW,MAAM,CAAC,CACrC,UAAU;IACb,MAAM,YAAY,WAAW,YAAY,KAAK;IAC9C,IAAI,cAAc,IAChB,aAAa,WAAW,MAAM,GAAG,SAAS,CAAC,CAAC,QAAQ;GAExD;EACF;EAEA,IAAI;GAGF,MAAM,EAAE,QAAQ,iBAFC,KAAK,MAAM,UAEY;GAExC,IAAI,WAAW,gBACb,OAAO;IAAE,cAAc,EAAE,QAAQ,aAAa;IAAG,KAAK;GAAK;GAE7D,OAAO;IAAE,MAAM;IAAQ,WAAW;IAAc,KAAK;GAAK;EAC5D,SAAS,GAAG;GACV,MAAM,IAAIC,+BAAAA,sBACR,2BAA2B,KAAK,YAAY,GAC9C;EACF;CACF;;;;;;;CAQA,wBAAgC;EAC9B,QAAA,
|
|
1
|
+
{"version":3,"file":"outputParser.cjs","names":["AgentActionOutputParser","OutputParserException","renderTemplate","FORMAT_INSTRUCTIONS","OutputFixingParser"],"sources":["../../../src/agents/chat_convo/outputParser.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { AgentAction, AgentFinish } from \"@langchain/core/agents\";\nimport {\n FormatInstructionsOptions,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { renderTemplate } from \"@langchain/core/prompts\";\nimport { AgentActionOutputParser } from \"../types.js\";\nimport { FORMAT_INSTRUCTIONS } from \"./prompt.js\";\nimport { OutputFixingParser } from \"../../output_parsers/fix.js\";\n\nexport type ChatConversationalAgentOutputParserFormatInstructionsOptions =\n FormatInstructionsOptions & {\n toolNames: string[];\n raw?: boolean;\n };\n\n/**\n * Class that represents an output parser for the ChatConversationalAgent\n * class. It extends the AgentActionOutputParser class and provides\n * methods for parsing the output of the MRKL chain into agent actions.\n */\nexport class ChatConversationalAgentOutputParser extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\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 into an AgentAction or AgentFinish object. If an\n * output fixing parser is defined, uses it to parse the text.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n let jsonOutput = text.trim();\n if (jsonOutput.includes(\"```json\") || jsonOutput.includes(\"```\")) {\n const testString = jsonOutput.includes(\"```json\") ? \"```json\" : \"```\";\n const firstIndex = jsonOutput.indexOf(testString);\n const actionInputIndex = jsonOutput.indexOf(\"action_input\");\n if (actionInputIndex > firstIndex) {\n jsonOutput = jsonOutput\n .slice(firstIndex + testString.length)\n .trimStart();\n const lastIndex = jsonOutput.lastIndexOf(\"```\");\n if (lastIndex !== -1) {\n jsonOutput = jsonOutput.slice(0, lastIndex).trimEnd();\n }\n }\n }\n\n try {\n const response = JSON.parse(jsonOutput);\n\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 as a string. If the 'raw' option is\n * true, returns the raw FORMAT_INSTRUCTIONS.\n * @param options Options for getting the format instructions.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(): string {\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: this.toolNames.join(\", \"),\n });\n }\n}\n\nexport type ChatConversationalAgentOutputParserArgs = {\n baseParser?: ChatConversationalAgentOutputParser;\n outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n toolNames?: string[];\n};\n\n/**\n * Class that represents an output parser with retries for the\n * ChatConversationalAgent class. It extends the AgentActionOutputParser\n * class and provides methods for parsing the output of the MRKL chain\n * into agent actions with retry functionality.\n */\nexport class ChatConversationalAgentOutputParserWithRetries extends AgentActionOutputParser {\n lc_namespace = [\"langchain\", \"agents\", \"chat_convo\"];\n\n private baseParser: ChatConversationalAgentOutputParser;\n\n private outputFixingParser?: OutputFixingParser<AgentAction | AgentFinish>;\n\n private toolNames: string[] = [];\n\n constructor(fields: ChatConversationalAgentOutputParserArgs) {\n super(fields);\n this.toolNames = fields.toolNames ?? this.toolNames;\n this.baseParser =\n fields?.baseParser ??\n new ChatConversationalAgentOutputParser({ toolNames: this.toolNames });\n this.outputFixingParser = fields?.outputFixingParser;\n }\n\n /**\n * Returns the format instructions as a string.\n * @returns Format instructions as a string.\n */\n getFormatInstructions(\n options: ChatConversationalAgentOutputParserFormatInstructionsOptions\n ): string {\n if (options.raw) {\n return FORMAT_INSTRUCTIONS;\n }\n return renderTemplate(FORMAT_INSTRUCTIONS, \"f-string\", {\n tool_names: options.toolNames.join(\", \"),\n });\n }\n\n /**\n * Parses the given text into an AgentAction or AgentFinish object.\n * @param text Text to parse.\n * @returns Promise that resolves to an AgentAction or AgentFinish object.\n */\n async parse(text: string): Promise<AgentAction | AgentFinish> {\n if (this.outputFixingParser !== undefined) {\n return this.outputFixingParser.parse(text);\n }\n return this.baseParser.parse(text);\n }\n\n /**\n * Static method to create a new\n * ChatConversationalAgentOutputParserWithRetries from a BaseLanguageModelInterface\n * and options. If no base parser is provided in the options, a new\n * ChatConversationalAgentOutputParser is created. An OutputFixingParser\n * is also created from the BaseLanguageModelInterface and the base parser.\n * @param llm BaseLanguageModelInterface instance used to create the OutputFixingParser.\n * @param options Options for creating the ChatConversationalAgentOutputParserWithRetries instance.\n * @returns A new instance of ChatConversationalAgentOutputParserWithRetries.\n */\n static fromLLM(\n llm: BaseLanguageModelInterface,\n options: Omit<ChatConversationalAgentOutputParserArgs, \"outputFixingParser\">\n ): ChatConversationalAgentOutputParserWithRetries {\n const baseParser =\n options.baseParser ??\n new ChatConversationalAgentOutputParser({\n toolNames: options.toolNames ?? [],\n });\n const outputFixingParser = OutputFixingParser.fromLLM(llm, baseParser);\n return new ChatConversationalAgentOutputParserWithRetries({\n baseParser,\n outputFixingParser,\n toolNames: options.toolNames,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAa,sCAAb,cAAyDA,cAAAA,wBAAwB;CAC/E,eAAe;EAAC;EAAa;EAAU;CAAY;CAEnD;CAEA,YAAY,QAAiC;EAC3C,MAAM,GAAG,SAAS;EAClB,KAAK,YAAY,OAAO;CAC1B;;;;;;;CAQA,MAAM,MAAM,MAAkD;EAC5D,IAAI,aAAa,KAAK,KAAK;EAC3B,IAAI,WAAW,SAAS,SAAS,KAAK,WAAW,SAAS,KAAK,GAAG;GAChE,MAAM,aAAa,WAAW,SAAS,SAAS,IAAI,YAAY;GAChE,MAAM,aAAa,WAAW,QAAQ,UAAU;GAEhD,IADyB,WAAW,QAAQ,cACzB,IAAI,YAAY;IACjC,aAAa,WACV,MAAM,aAAa,WAAW,MAAM,CAAC,CACrC,UAAU;IACb,MAAM,YAAY,WAAW,YAAY,KAAK;IAC9C,IAAI,cAAc,IAChB,aAAa,WAAW,MAAM,GAAG,SAAS,CAAC,CAAC,QAAQ;GAExD;EACF;EAEA,IAAI;GAGF,MAAM,EAAE,QAAQ,iBAFC,KAAK,MAAM,UAEY;GAExC,IAAI,WAAW,gBACb,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CACH;AACF"}
|
package/dist/agents/executor.cjs
CHANGED
|
@@ -206,15 +206,16 @@ var AgentExecutor = class AgentExecutor extends require_base.BaseChain {
|
|
|
206
206
|
let agent;
|
|
207
207
|
let returnOnlyOutputs = true;
|
|
208
208
|
if (_langchain_core_runnables.Runnable.isRunnable(input.agent)) {
|
|
209
|
-
if (require_agent.AgentRunnableSequence.isAgentRunnableSequence(input.agent))
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
209
|
+
if (require_agent.AgentRunnableSequence.isAgentRunnableSequence(input.agent)) {
|
|
210
|
+
if (input.agent.singleAction) agent = new require_agent.RunnableSingleActionAgent({
|
|
211
|
+
runnable: input.agent,
|
|
212
|
+
streamRunnable: input.agent.streamRunnable
|
|
213
|
+
});
|
|
214
|
+
else agent = new require_agent.RunnableMultiActionAgent({
|
|
215
|
+
runnable: input.agent,
|
|
216
|
+
streamRunnable: input.agent.streamRunnable
|
|
217
|
+
});
|
|
218
|
+
} else agent = new require_agent.RunnableMultiActionAgent({ runnable: input.agent });
|
|
218
219
|
returnOnlyOutputs = false;
|
|
219
220
|
} else {
|
|
220
221
|
if (require_agent.isRunnableAgent(input.agent)) returnOnlyOutputs = false;
|
|
@@ -282,11 +283,12 @@ var AgentExecutor = class AgentExecutor extends require_base.BaseChain {
|
|
|
282
283
|
if (e instanceof _langchain_core_output_parsers.OutputParserException) {
|
|
283
284
|
let observation;
|
|
284
285
|
let text = e.message;
|
|
285
|
-
if (this.handleParsingErrors === true)
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
286
|
+
if (this.handleParsingErrors === true) {
|
|
287
|
+
if (e.sendToLLM) {
|
|
288
|
+
observation = e.observation;
|
|
289
|
+
text = e.llmOutput ?? "";
|
|
290
|
+
} else observation = "Invalid or incomplete response";
|
|
291
|
+
} else if (typeof this.handleParsingErrors === "string") observation = this.handleParsingErrors;
|
|
290
292
|
else if (typeof this.handleParsingErrors === "function") observation = this.handleParsingErrors(e);
|
|
291
293
|
else throw e;
|
|
292
294
|
output = {
|
|
@@ -343,11 +345,12 @@ var AgentExecutor = class AgentExecutor extends require_base.BaseChain {
|
|
|
343
345
|
if (e instanceof _langchain_core_output_parsers.OutputParserException) {
|
|
344
346
|
let observation;
|
|
345
347
|
let text = e.message;
|
|
346
|
-
if (this.handleParsingErrors === true)
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
348
|
+
if (this.handleParsingErrors === true) {
|
|
349
|
+
if (e.sendToLLM) {
|
|
350
|
+
observation = e.observation;
|
|
351
|
+
text = e.llmOutput ?? "";
|
|
352
|
+
} else observation = "Invalid or incomplete response";
|
|
353
|
+
} else if (typeof this.handleParsingErrors === "string") observation = this.handleParsingErrors;
|
|
351
354
|
else if (typeof this.handleParsingErrors === "function") observation = this.handleParsingErrors(e);
|
|
352
355
|
else throw e;
|
|
353
356
|
output = {
|