@langchain/classic 1.0.32 → 1.0.34
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 +18 -0
- package/dist/agents/chat/outputParser.d.cts +2 -2
- package/dist/agents/executor.cjs +6 -2
- package/dist/agents/executor.cjs.map +1 -1
- package/dist/agents/executor.js +6 -2
- package/dist/agents/executor.js.map +1 -1
- package/dist/agents/mrkl/outputParser.d.cts +1 -1
- package/dist/cache/file_system.cjs +2 -2
- package/dist/document_loaders/fs/json.cjs +1 -1
- package/dist/experimental/generative_agents/generative_agent.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent.js.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.js.map +1 -1
- package/dist/experimental/prompts/handlebars.cjs +1 -1
- package/dist/retrievers/parent_document.cjs +1 -1
- package/dist/storage/file_system.cjs +2 -2
- package/dist/stores/file/node.cjs +1 -1
- package/dist/tools/json.cjs +1 -1
- package/dist/tools/webbrowser.cjs +1 -1
- package/dist/util/openapi.cjs +1 -1
- package/dist/util/parse.cjs +1 -1
- package/package.json +30 -31
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @langchain/classic
|
|
2
2
|
|
|
3
|
+
## 1.0.34
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`3999fab`](https://github.com/langchain-ai/langchainjs/commit/3999fab55870c6eea22d6d90c08aa472f9b2fac3), [`fce9ab4`](https://github.com/langchain-ai/langchainjs/commit/fce9ab418901323618fdfaaa9fc350fa1c0d50e0)]:
|
|
8
|
+
- @langchain/openai@1.4.7
|
|
9
|
+
|
|
10
|
+
## 1.0.33
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- [#10872](https://github.com/langchain-ai/langchainjs/pull/10872) [`a640079`](https://github.com/langchain-ai/langchainjs/commit/a64007997a4940f51bba3c1c83dae89d1ccfb692) Thanks [@hntrl](https://github.com/hntrl)! - chore(deps): remove redundant @types/uuid declarations
|
|
15
|
+
|
|
16
|
+
Remove `@types/uuid` from package manifests that rely on `@langchain/core/utils/uuid` or do not require uuid type stubs directly, and refresh the lockfile entries accordingly.
|
|
17
|
+
|
|
18
|
+
- Updated dependencies [[`229a7ad`](https://github.com/langchain-ai/langchainjs/commit/229a7ad67b9a7ebd8df3ca451e0b8195bea0190e), [`36fb0ef`](https://github.com/langchain-ai/langchainjs/commit/36fb0ef1dc76c096dcfa0c777e10c9f9365a5240)]:
|
|
19
|
+
- @langchain/openai@1.4.6
|
|
20
|
+
|
|
3
21
|
## 1.0.32
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
|
@@ -50,12 +50,12 @@ declare class ChatAgentOutputParser extends AgentActionOutputParser {
|
|
|
50
50
|
* @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.
|
|
51
51
|
*/
|
|
52
52
|
parse(text: string): Promise<{
|
|
53
|
+
tool?: undefined;
|
|
54
|
+
toolInput?: undefined;
|
|
53
55
|
returnValues: {
|
|
54
56
|
output: string;
|
|
55
57
|
};
|
|
56
58
|
log: string;
|
|
57
|
-
tool?: undefined;
|
|
58
|
-
toolInput?: undefined;
|
|
59
59
|
} | {
|
|
60
60
|
returnValues?: undefined;
|
|
61
61
|
tool: any;
|
package/dist/agents/executor.cjs
CHANGED
|
@@ -31,7 +31,10 @@ var AgentExecutorIterator = class extends _langchain_core_load_serializable.Seri
|
|
|
31
31
|
/** Intended to be used as a setter method, needs to be async. */
|
|
32
32
|
async setFinalOutputs(value) {
|
|
33
33
|
this._finalOutputs = void 0;
|
|
34
|
-
if (value)
|
|
34
|
+
if (value) {
|
|
35
|
+
const preparedOutputs = await this.agentExecutor.prepOutputs(this.inputs, value, true);
|
|
36
|
+
this._finalOutputs = preparedOutputs;
|
|
37
|
+
}
|
|
35
38
|
}
|
|
36
39
|
runManager;
|
|
37
40
|
intermediateSteps = [];
|
|
@@ -83,7 +86,8 @@ var AgentExecutorIterator = class extends _langchain_core_load_serializable.Seri
|
|
|
83
86
|
*/
|
|
84
87
|
async onFirstStep() {
|
|
85
88
|
if (this.iterations === 0) {
|
|
86
|
-
|
|
89
|
+
const callbackManager = await _langchain_core_callbacks_manager.CallbackManager.configure(this.callbacks ?? this.config?.callbacks, this.agentExecutor.callbacks, this.tags ?? this.config?.tags, this.agentExecutor.tags, this.metadata ?? this.config?.metadata, this.agentExecutor.metadata, { verbose: this.agentExecutor.verbose });
|
|
90
|
+
this.runManager = await callbackManager?.handleChainStart(this.agentExecutor.toJSON(), this.inputs, this.config?.runId, void 0, this.tags ?? this.config?.tags, this.metadata ?? this.config?.metadata, this.runName ?? this.config?.runName);
|
|
87
91
|
if (this.config !== void 0) delete this.config.runId;
|
|
88
92
|
}
|
|
89
93
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.cjs","names":["Serializable","CallbackManager","Tool","BaseChain","Runnable","AgentRunnableSequence","RunnableSingleActionAgent","RunnableMultiActionAgent","isRunnableAgent","OutputParserException","ToolInputParsingException"],"sources":["../../src/agents/executor.ts"],"sourcesContent":["import {\n type StructuredToolInterface,\n type ToolInterface,\n ToolInputParsingException,\n Tool,\n} from \"@langchain/core/tools\";\nimport {\n Runnable,\n type RunnableConfig,\n patchConfig,\n} from \"@langchain/core/runnables\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManager,\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport { SerializedLLMChain } from \"../chains/serde.js\";\nimport { StoppingMethod } from \"./types.js\";\nimport {\n AgentRunnableSequence,\n BaseMultiActionAgent,\n BaseSingleActionAgent,\n RunnableMultiActionAgent,\n RunnableSingleActionAgent,\n isRunnableAgent,\n} from \"./agent.js\";\nimport { BaseChain, ChainInputs } from \"../chains/base.js\";\n\ninterface AgentExecutorIteratorInput {\n agentExecutor: AgentExecutor;\n inputs: Record<string, string>;\n config?: RunnableConfig;\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n /** @deprecated Use \"config\" */\n tags?: string[];\n /** @deprecated Use \"config\" */\n metadata?: Record<string, unknown>;\n runName?: string;\n runManager?: CallbackManagerForChainRun;\n}\n\nexport class AgentExecutorIterator\n extends Serializable\n implements AgentExecutorIteratorInput\n{\n lc_namespace = [\"langchain\", \"agents\", \"executor_iterator\"];\n\n agentExecutor: AgentExecutor;\n\n inputs: Record<string, string>;\n\n config?: RunnableConfig;\n\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n\n /** @deprecated Use \"config\" */\n tags: string[] | undefined;\n\n /** @deprecated Use \"config\" */\n metadata: Record<string, unknown> | undefined;\n\n /** @deprecated Use \"config\" */\n runName: string | undefined;\n\n private _finalOutputs: Record<string, unknown> | undefined;\n\n get finalOutputs(): Record<string, unknown> | undefined {\n return this._finalOutputs;\n }\n\n /** Intended to be used as a setter method, needs to be async. */\n async setFinalOutputs(value: Record<string, unknown> | undefined) {\n this._finalOutputs = undefined;\n if (value) {\n const preparedOutputs: Record<string, unknown> =\n await this.agentExecutor.prepOutputs(this.inputs, value, true);\n this._finalOutputs = preparedOutputs;\n }\n }\n\n runManager: CallbackManagerForChainRun | undefined;\n\n intermediateSteps: AgentStep[] = [];\n\n iterations = 0;\n\n get nameToToolMap(): Record<string, ToolInterface> {\n const toolMap = this.agentExecutor.tools.map((tool) => ({\n [tool.name]: tool,\n }));\n return Object.assign({}, ...toolMap);\n }\n\n constructor(fields: AgentExecutorIteratorInput) {\n super(fields);\n this.agentExecutor = fields.agentExecutor;\n this.inputs = fields.inputs;\n this.callbacks = fields.callbacks;\n this.tags = fields.tags;\n this.metadata = fields.metadata;\n this.runName = fields.runName;\n this.runManager = fields.runManager;\n this.config = fields.config;\n }\n\n /**\n * Reset the iterator to its initial state, clearing intermediate steps,\n * iterations, and the final output.\n */\n reset(): void {\n this.intermediateSteps = [];\n this.iterations = 0;\n this._finalOutputs = undefined;\n }\n\n updateIterations(): void {\n this.iterations += 1;\n }\n\n async *streamIterator() {\n this.reset();\n\n // Loop to handle iteration\n while (true) {\n try {\n if (this.iterations === 0) {\n await this.onFirstStep();\n }\n\n const result = await this._callNext();\n yield result;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (\n \"message\" in e &&\n e.message.startsWith(\"Final outputs already reached: \")\n ) {\n if (!this.finalOutputs) {\n throw e;\n }\n return this.finalOutputs;\n }\n if (this.runManager) {\n await this.runManager.handleChainError(e);\n }\n throw e;\n }\n }\n }\n\n /**\n * Perform any necessary setup for the first step\n * of the asynchronous iterator.\n */\n async onFirstStep(): Promise<void> {\n if (this.iterations === 0) {\n const callbackManager = await CallbackManager.configure(\n this.callbacks ?? this.config?.callbacks,\n this.agentExecutor.callbacks,\n this.tags ?? this.config?.tags,\n this.agentExecutor.tags,\n this.metadata ?? this.config?.metadata,\n this.agentExecutor.metadata,\n {\n verbose: this.agentExecutor.verbose,\n }\n );\n this.runManager = await callbackManager?.handleChainStart(\n this.agentExecutor.toJSON(),\n this.inputs,\n this.config?.runId,\n undefined,\n this.tags ?? this.config?.tags,\n this.metadata ?? this.config?.metadata,\n this.runName ?? this.config?.runName\n );\n if (this.config !== undefined) {\n delete this.config.runId;\n }\n }\n }\n\n /**\n * Execute the next step in the chain using the\n * AgentExecutor's _takeNextStep method.\n */\n async _executeNextStep(\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentFinish | AgentStep[]> {\n return this.agentExecutor._takeNextStep(\n this.nameToToolMap,\n this.inputs,\n this.intermediateSteps,\n runManager,\n this.config\n );\n }\n\n /**\n * Process the output of the next step,\n * handling AgentFinish and tool return cases.\n */\n async _processNextStepOutput(\n nextStepOutput: AgentFinish | AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<Record<string, string | AgentStep[]>> {\n if (\"returnValues\" in nextStepOutput) {\n const output = await this.agentExecutor._return(\n nextStepOutput as AgentFinish,\n this.intermediateSteps,\n runManager\n );\n if (this.runManager) {\n await this.runManager.handleChainEnd(output);\n }\n await this.setFinalOutputs(output);\n return output;\n }\n\n this.intermediateSteps = this.intermediateSteps.concat(\n nextStepOutput as AgentStep[]\n );\n\n let output: Record<string, string | AgentStep[]> = {};\n if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {\n const nextStep = nextStepOutput[0];\n const toolReturn = await this.agentExecutor._getToolReturn(nextStep);\n if (toolReturn) {\n output = await this.agentExecutor._return(\n toolReturn,\n this.intermediateSteps,\n runManager\n );\n await this.runManager?.handleChainEnd(output);\n await this.setFinalOutputs(output);\n }\n }\n output = { intermediateSteps: nextStepOutput as AgentStep[] };\n return output;\n }\n\n async _stop(): Promise<Record<string, unknown>> {\n const output = await this.agentExecutor.agent.returnStoppedResponse(\n this.agentExecutor.earlyStoppingMethod,\n this.intermediateSteps,\n this.inputs\n );\n const returnedOutput = await this.agentExecutor._return(\n output,\n this.intermediateSteps,\n this.runManager\n );\n await this.setFinalOutputs(returnedOutput);\n await this.runManager?.handleChainEnd(returnedOutput);\n return returnedOutput;\n }\n\n async _callNext(): Promise<Record<string, unknown>> {\n // final output already reached: stopiteration (final output)\n if (this.finalOutputs) {\n throw new Error(\n `Final outputs already reached: ${JSON.stringify(\n this.finalOutputs,\n null,\n 2\n )}`\n );\n }\n // timeout/max iterations: stopiteration (stopped response)\n if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {\n return this._stop();\n }\n const nextStepOutput = await this._executeNextStep(this.runManager);\n const output = await this._processNextStepOutput(\n nextStepOutput,\n this.runManager\n );\n this.updateIterations();\n return output;\n }\n}\n\ntype ExtractToolType<T> = T extends { ToolType: infer ToolInterface }\n ? ToolInterface\n : StructuredToolInterface;\n\n/**\n * Interface defining the structure of input data for creating an\n * AgentExecutor. It extends ChainInputs and includes additional\n * properties specific to agent execution.\n */\nexport interface AgentExecutorInput extends ChainInputs {\n agent:\n | BaseSingleActionAgent\n | BaseMultiActionAgent\n | Runnable<\n ChainValues & { steps?: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n tools: ExtractToolType<this[\"agent\"]>[];\n returnIntermediateSteps?: boolean;\n maxIterations?: number;\n earlyStoppingMethod?: StoppingMethod;\n handleParsingErrors?:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string);\n handleToolRuntimeErrors?: (e: Error) => string;\n}\n\n// TODO: Type properly with { intermediateSteps?: AgentStep[] };\nexport type AgentExecutorOutput = ChainValues;\n\n/**\n * Tool that just returns the query.\n * Used for exception tracking.\n */\nexport class ExceptionTool extends Tool {\n name = \"_Exception\";\n\n description = \"Exception tool\";\n\n async _call(query: string) {\n return query;\n }\n}\n\n/**\n * A chain managing an agent using tools.\n * @augments BaseChain\n * @example\n * ```typescript\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: async () => loadAgentFromLangchainHub(),\n * tools: [new SerpAPI(), new Calculator()],\n * returnIntermediateSteps: true,\n * });\n *\n * const result = await executor.invoke({\n * input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,\n * });\n *\n * ```\n */\nexport class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {\n static lc_name() {\n return \"AgentExecutor\";\n }\n\n get lc_namespace() {\n return [\"langchain\", \"agents\", \"executor\"];\n }\n\n agent: BaseSingleActionAgent | BaseMultiActionAgent;\n\n tools: this[\"agent\"][\"ToolType\"][];\n\n returnIntermediateSteps = false;\n\n maxIterations?: number = 15;\n\n earlyStoppingMethod: StoppingMethod = \"force\";\n\n // TODO: Update BaseChain implementation on breaking change to include this\n returnOnlyOutputs = true;\n\n /**\n * How to handle errors raised by the agent's output parser.\n Defaults to `False`, which raises the error.\n\n If `true`, the error will be sent back to the LLM as an observation.\n If a string, the string itself will be sent to the LLM as an observation.\n If a callable function, the function will be called with the exception\n as an argument, and the result of that function will be passed to the agent\n as an observation.\n */\n handleParsingErrors:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string) =\n false;\n\n handleToolRuntimeErrors?: (e: Error) => string;\n\n get inputKeys() {\n return this.agent.inputKeys;\n }\n\n get outputKeys() {\n return this.agent.returnValues;\n }\n\n constructor(input: AgentExecutorInput) {\n let agent: BaseSingleActionAgent | BaseMultiActionAgent;\n let returnOnlyOutputs = true;\n if (Runnable.isRunnable(input.agent)) {\n if (AgentRunnableSequence.isAgentRunnableSequence(input.agent)) {\n if (input.agent.singleAction) {\n agent = new RunnableSingleActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n } else {\n agent = new RunnableMultiActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n }\n } else {\n agent = new RunnableMultiActionAgent({ runnable: input.agent });\n }\n // TODO: Update BaseChain implementation on breaking change\n returnOnlyOutputs = false;\n } else {\n if (isRunnableAgent(input.agent)) {\n returnOnlyOutputs = false;\n }\n agent = input.agent;\n }\n\n super(input);\n this.agent = agent;\n this.tools = input.tools;\n this.handleParsingErrors =\n input.handleParsingErrors ?? this.handleParsingErrors;\n this.handleToolRuntimeErrors = input.handleToolRuntimeErrors;\n this.returnOnlyOutputs = returnOnlyOutputs;\n if (this.agent._agentActionType() === \"multi\") {\n for (const tool of this.tools) {\n if (tool.returnDirect) {\n throw new Error(\n `Tool with return direct ${tool.name} not supported for multi-action agent.`\n );\n }\n }\n }\n this.returnIntermediateSteps =\n input.returnIntermediateSteps ?? this.returnIntermediateSteps;\n this.maxIterations = input.maxIterations ?? this.maxIterations;\n this.earlyStoppingMethod =\n input.earlyStoppingMethod ?? this.earlyStoppingMethod;\n }\n\n /** Create from agent and a list of tools. */\n static fromAgentAndTools(fields: AgentExecutorInput): AgentExecutor {\n return new AgentExecutor(fields);\n }\n\n get shouldContinueGetter() {\n return this.shouldContinue.bind(this);\n }\n\n /**\n * Method that checks if the agent execution should continue based on the\n * number of iterations.\n * @param iterations The current number of iterations.\n * @returns A boolean indicating whether the agent execution should continue.\n */\n private shouldContinue(iterations: number): boolean {\n return this.maxIterations === undefined || iterations < this.maxIterations;\n }\n\n /** @ignore */\n async _call(\n inputs: ChainValues,\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentExecutorOutput> {\n const toolsByName = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const steps: AgentStep[] = [];\n let iterations = 0;\n\n const getOutput = async (\n finishStep: AgentFinish\n ): Promise<AgentExecutorOutput> => {\n const { returnValues } = finishStep;\n const additional = await this.agent.prepareForOutput(returnValues, steps);\n\n await runManager?.handleAgentEnd(finishStep);\n\n let response;\n\n if (this.returnIntermediateSteps) {\n response = { ...returnValues, intermediateSteps: steps, ...additional };\n } else {\n response = { ...returnValues, ...additional };\n }\n if (!this.returnOnlyOutputs) {\n response = { ...inputs, ...response };\n }\n return response;\n };\n\n while (this.shouldContinue(iterations)) {\n let output;\n try {\n output = await this.agent.plan(\n steps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n // Check if the agent has finished\n if (\"returnValues\" in output) {\n return getOutput(output);\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const newSteps = await Promise.all(\n actions.map(async (action) => {\n await runManager?.handleAgentAction(action);\n const tool =\n action.tool === \"_Exception\"\n ? new ExceptionTool()\n : toolsByName[action.tool?.toLowerCase()];\n let observation;\n try {\n observation = tool\n ? await tool.invoke(\n action.toolInput,\n patchConfig(config, { callbacks: runManager?.getChild() })\n )\n : `${action.tool} is not a valid tool, try another one.`;\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n return { action, observation: observation ?? \"\" };\n } else if (this.handleToolRuntimeErrors !== undefined) {\n observation = this.handleToolRuntimeErrors(e);\n }\n }\n\n return { action, observation: observation ?? \"\" };\n })\n );\n\n steps.push(...newSteps);\n\n const lastStep = steps[steps.length - 1];\n const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];\n\n if (lastTool?.returnDirect) {\n return getOutput({\n returnValues: { [this.agent.returnValues[0]]: lastStep.observation },\n log: \"\",\n });\n }\n\n iterations += 1;\n }\n\n const finish = await this.agent.returnStoppedResponse(\n this.earlyStoppingMethod,\n steps,\n inputs\n );\n\n return getOutput(finish);\n }\n\n async _takeNextStep(\n nameToolMap: Record<string, ToolInterface>,\n inputs: ChainValues,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentFinish | AgentStep[]> {\n let output;\n try {\n output = await this.agent.plan(\n intermediateSteps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n\n if (\"returnValues\" in output) {\n return output;\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const result: AgentStep[] = [];\n for (const agentAction of actions) {\n let observation = \"\";\n if (runManager) {\n await runManager?.handleAgentAction(agentAction);\n }\n if (agentAction.tool in nameToolMap) {\n const tool = nameToolMap[agentAction.tool];\n try {\n observation = await tool.call(\n agentAction.toolInput,\n runManager?.getChild()\n );\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n }\n }\n } else {\n observation = `${\n agentAction.tool\n } is not a valid tool, try another available tool: ${Object.keys(\n nameToolMap\n ).join(\", \")}`;\n }\n result.push({\n action: agentAction,\n observation,\n });\n }\n return result;\n }\n\n async _return(\n output: AgentFinish,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentExecutorOutput> {\n if (runManager) {\n await runManager.handleAgentEnd(output);\n }\n const finalOutput: Record<string, unknown> = output.returnValues;\n if (this.returnIntermediateSteps) {\n finalOutput.intermediateSteps = intermediateSteps;\n }\n return finalOutput;\n }\n\n async _getToolReturn(nextStepOutput: AgentStep): Promise<AgentFinish | null> {\n const { action, observation } = nextStepOutput;\n const nameToolMap = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const [returnValueKey = \"output\"] = this.agent.returnValues;\n // Invalid tools won't be in the map, so we return False.\n if (action.tool in nameToolMap) {\n if (nameToolMap[action.tool].returnDirect) {\n return {\n returnValues: { [returnValueKey]: observation },\n log: \"\",\n };\n }\n }\n return null;\n }\n\n _returnStoppedResponse(earlyStoppingMethod: StoppingMethod) {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: {\n output: \"Agent stopped due to iteration limit or time limit.\",\n },\n log: \"\",\n } as AgentFinish;\n }\n throw new Error(\n `Got unsupported early_stopping_method: ${earlyStoppingMethod}`\n );\n }\n\n async *_streamIterator(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n inputs: Record<string, any>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<ChainValues> {\n const agentExecutorIterator = new AgentExecutorIterator({\n inputs,\n agentExecutor: this,\n config: options,\n // TODO: Deprecate these other parameters\n metadata: options?.metadata,\n tags: options?.tags,\n callbacks: options?.callbacks,\n });\n const iterator = agentExecutorIterator.streamIterator();\n for await (const step of iterator) {\n if (!step) {\n continue;\n }\n yield step;\n }\n }\n\n _chainType() {\n return \"agent_executor\" as const;\n }\n\n serialize(): SerializedLLMChain {\n throw new Error(\"Cannot serialize an AgentExecutor\");\n }\n}\n"],"mappings":";;;;;;;;;AA8CA,IAAa,wBAAb,cACUA,kCAAAA,aAEV;CACE,eAAe;EAAC;EAAa;EAAU;EAAoB;CAE3D;CAEA;CAEA;;CAGA;;CAGA;;CAGA;;CAGA;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CAGT,uBAAuB,qBAAqC;AAC1D,MAAI,wBAAwB,QAC1B,QAAO;GACL,cAAc,EACZ,QAAQ,uDACT;GACD,KAAK;GACN;AAEH,QAAM,IAAI,MACR,0CAA0C,sBAC3C;;CAGH,OAAO,gBAEL,QACA,SAC6B;EAU7B,MAAM,WATwB,IAAI,sBAAsB;GACtD;GACA,eAAe;GACf,QAAQ;GAER,UAAU,SAAS;GACnB,MAAM,SAAS;GACf,WAAW,SAAS;GACrB,CAAC,CACqC,gBAAgB;AACvD,aAAW,MAAM,QAAQ,UAAU;AACjC,OAAI,CAAC,KACH;AAEF,SAAM;;;CAIV,aAAa;AACX,SAAO;;CAGT,YAAgC;AAC9B,QAAM,IAAI,MAAM,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"executor.cjs","names":["Serializable","CallbackManager","Tool","BaseChain","Runnable","AgentRunnableSequence","RunnableSingleActionAgent","RunnableMultiActionAgent","isRunnableAgent","OutputParserException","ToolInputParsingException"],"sources":["../../src/agents/executor.ts"],"sourcesContent":["import {\n type StructuredToolInterface,\n type ToolInterface,\n ToolInputParsingException,\n Tool,\n} from \"@langchain/core/tools\";\nimport {\n Runnable,\n type RunnableConfig,\n patchConfig,\n} from \"@langchain/core/runnables\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManager,\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport { SerializedLLMChain } from \"../chains/serde.js\";\nimport { StoppingMethod } from \"./types.js\";\nimport {\n AgentRunnableSequence,\n BaseMultiActionAgent,\n BaseSingleActionAgent,\n RunnableMultiActionAgent,\n RunnableSingleActionAgent,\n isRunnableAgent,\n} from \"./agent.js\";\nimport { BaseChain, ChainInputs } from \"../chains/base.js\";\n\ninterface AgentExecutorIteratorInput {\n agentExecutor: AgentExecutor;\n inputs: Record<string, string>;\n config?: RunnableConfig;\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n /** @deprecated Use \"config\" */\n tags?: string[];\n /** @deprecated Use \"config\" */\n metadata?: Record<string, unknown>;\n runName?: string;\n runManager?: CallbackManagerForChainRun;\n}\n\nexport class AgentExecutorIterator\n extends Serializable\n implements AgentExecutorIteratorInput\n{\n lc_namespace = [\"langchain\", \"agents\", \"executor_iterator\"];\n\n agentExecutor: AgentExecutor;\n\n inputs: Record<string, string>;\n\n config?: RunnableConfig;\n\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n\n /** @deprecated Use \"config\" */\n tags: string[] | undefined;\n\n /** @deprecated Use \"config\" */\n metadata: Record<string, unknown> | undefined;\n\n /** @deprecated Use \"config\" */\n runName: string | undefined;\n\n private _finalOutputs: Record<string, unknown> | undefined;\n\n get finalOutputs(): Record<string, unknown> | undefined {\n return this._finalOutputs;\n }\n\n /** Intended to be used as a setter method, needs to be async. */\n async setFinalOutputs(value: Record<string, unknown> | undefined) {\n this._finalOutputs = undefined;\n if (value) {\n const preparedOutputs: Record<string, unknown> =\n await this.agentExecutor.prepOutputs(this.inputs, value, true);\n this._finalOutputs = preparedOutputs;\n }\n }\n\n runManager: CallbackManagerForChainRun | undefined;\n\n intermediateSteps: AgentStep[] = [];\n\n iterations = 0;\n\n get nameToToolMap(): Record<string, ToolInterface> {\n const toolMap = this.agentExecutor.tools.map((tool) => ({\n [tool.name]: tool,\n }));\n return Object.assign({}, ...toolMap);\n }\n\n constructor(fields: AgentExecutorIteratorInput) {\n super(fields);\n this.agentExecutor = fields.agentExecutor;\n this.inputs = fields.inputs;\n this.callbacks = fields.callbacks;\n this.tags = fields.tags;\n this.metadata = fields.metadata;\n this.runName = fields.runName;\n this.runManager = fields.runManager;\n this.config = fields.config;\n }\n\n /**\n * Reset the iterator to its initial state, clearing intermediate steps,\n * iterations, and the final output.\n */\n reset(): void {\n this.intermediateSteps = [];\n this.iterations = 0;\n this._finalOutputs = undefined;\n }\n\n updateIterations(): void {\n this.iterations += 1;\n }\n\n async *streamIterator() {\n this.reset();\n\n // Loop to handle iteration\n while (true) {\n try {\n if (this.iterations === 0) {\n await this.onFirstStep();\n }\n\n const result = await this._callNext();\n yield result;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (\n \"message\" in e &&\n e.message.startsWith(\"Final outputs already reached: \")\n ) {\n if (!this.finalOutputs) {\n throw e;\n }\n return this.finalOutputs;\n }\n if (this.runManager) {\n await this.runManager.handleChainError(e);\n }\n throw e;\n }\n }\n }\n\n /**\n * Perform any necessary setup for the first step\n * of the asynchronous iterator.\n */\n async onFirstStep(): Promise<void> {\n if (this.iterations === 0) {\n const callbackManager = await CallbackManager.configure(\n this.callbacks ?? this.config?.callbacks,\n this.agentExecutor.callbacks,\n this.tags ?? this.config?.tags,\n this.agentExecutor.tags,\n this.metadata ?? this.config?.metadata,\n this.agentExecutor.metadata,\n {\n verbose: this.agentExecutor.verbose,\n }\n );\n this.runManager = await callbackManager?.handleChainStart(\n this.agentExecutor.toJSON(),\n this.inputs,\n this.config?.runId,\n undefined,\n this.tags ?? this.config?.tags,\n this.metadata ?? this.config?.metadata,\n this.runName ?? this.config?.runName\n );\n if (this.config !== undefined) {\n delete this.config.runId;\n }\n }\n }\n\n /**\n * Execute the next step in the chain using the\n * AgentExecutor's _takeNextStep method.\n */\n async _executeNextStep(\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentFinish | AgentStep[]> {\n return this.agentExecutor._takeNextStep(\n this.nameToToolMap,\n this.inputs,\n this.intermediateSteps,\n runManager,\n this.config\n );\n }\n\n /**\n * Process the output of the next step,\n * handling AgentFinish and tool return cases.\n */\n async _processNextStepOutput(\n nextStepOutput: AgentFinish | AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<Record<string, string | AgentStep[]>> {\n if (\"returnValues\" in nextStepOutput) {\n const output = await this.agentExecutor._return(\n nextStepOutput as AgentFinish,\n this.intermediateSteps,\n runManager\n );\n if (this.runManager) {\n await this.runManager.handleChainEnd(output);\n }\n await this.setFinalOutputs(output);\n return output;\n }\n\n this.intermediateSteps = this.intermediateSteps.concat(\n nextStepOutput as AgentStep[]\n );\n\n let output: Record<string, string | AgentStep[]> = {};\n if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {\n const nextStep = nextStepOutput[0];\n const toolReturn = await this.agentExecutor._getToolReturn(nextStep);\n if (toolReturn) {\n output = await this.agentExecutor._return(\n toolReturn,\n this.intermediateSteps,\n runManager\n );\n await this.runManager?.handleChainEnd(output);\n await this.setFinalOutputs(output);\n }\n }\n output = { intermediateSteps: nextStepOutput as AgentStep[] };\n return output;\n }\n\n async _stop(): Promise<Record<string, unknown>> {\n const output = await this.agentExecutor.agent.returnStoppedResponse(\n this.agentExecutor.earlyStoppingMethod,\n this.intermediateSteps,\n this.inputs\n );\n const returnedOutput = await this.agentExecutor._return(\n output,\n this.intermediateSteps,\n this.runManager\n );\n await this.setFinalOutputs(returnedOutput);\n await this.runManager?.handleChainEnd(returnedOutput);\n return returnedOutput;\n }\n\n async _callNext(): Promise<Record<string, unknown>> {\n // final output already reached: stopiteration (final output)\n if (this.finalOutputs) {\n throw new Error(\n `Final outputs already reached: ${JSON.stringify(\n this.finalOutputs,\n null,\n 2\n )}`\n );\n }\n // timeout/max iterations: stopiteration (stopped response)\n if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {\n return this._stop();\n }\n const nextStepOutput = await this._executeNextStep(this.runManager);\n const output = await this._processNextStepOutput(\n nextStepOutput,\n this.runManager\n );\n this.updateIterations();\n return output;\n }\n}\n\ntype ExtractToolType<T> = T extends { ToolType: infer ToolInterface }\n ? ToolInterface\n : StructuredToolInterface;\n\n/**\n * Interface defining the structure of input data for creating an\n * AgentExecutor. It extends ChainInputs and includes additional\n * properties specific to agent execution.\n */\nexport interface AgentExecutorInput extends ChainInputs {\n agent:\n | BaseSingleActionAgent\n | BaseMultiActionAgent\n | Runnable<\n ChainValues & { steps?: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n tools: ExtractToolType<this[\"agent\"]>[];\n returnIntermediateSteps?: boolean;\n maxIterations?: number;\n earlyStoppingMethod?: StoppingMethod;\n handleParsingErrors?:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string);\n handleToolRuntimeErrors?: (e: Error) => string;\n}\n\n// TODO: Type properly with { intermediateSteps?: AgentStep[] };\nexport type AgentExecutorOutput = ChainValues;\n\n/**\n * Tool that just returns the query.\n * Used for exception tracking.\n */\nexport class ExceptionTool extends Tool {\n name = \"_Exception\";\n\n description = \"Exception tool\";\n\n async _call(query: string) {\n return query;\n }\n}\n\n/**\n * A chain managing an agent using tools.\n * @augments BaseChain\n * @example\n * ```typescript\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: async () => loadAgentFromLangchainHub(),\n * tools: [new SerpAPI(), new Calculator()],\n * returnIntermediateSteps: true,\n * });\n *\n * const result = await executor.invoke({\n * input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,\n * });\n *\n * ```\n */\nexport class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {\n static lc_name() {\n return \"AgentExecutor\";\n }\n\n get lc_namespace() {\n return [\"langchain\", \"agents\", \"executor\"];\n }\n\n agent: BaseSingleActionAgent | BaseMultiActionAgent;\n\n tools: this[\"agent\"][\"ToolType\"][];\n\n returnIntermediateSteps = false;\n\n maxIterations?: number = 15;\n\n earlyStoppingMethod: StoppingMethod = \"force\";\n\n // TODO: Update BaseChain implementation on breaking change to include this\n returnOnlyOutputs = true;\n\n /**\n * How to handle errors raised by the agent's output parser.\n Defaults to `False`, which raises the error.\n\n If `true`, the error will be sent back to the LLM as an observation.\n If a string, the string itself will be sent to the LLM as an observation.\n If a callable function, the function will be called with the exception\n as an argument, and the result of that function will be passed to the agent\n as an observation.\n */\n handleParsingErrors:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string) =\n false;\n\n handleToolRuntimeErrors?: (e: Error) => string;\n\n get inputKeys() {\n return this.agent.inputKeys;\n }\n\n get outputKeys() {\n return this.agent.returnValues;\n }\n\n constructor(input: AgentExecutorInput) {\n let agent: BaseSingleActionAgent | BaseMultiActionAgent;\n let returnOnlyOutputs = true;\n if (Runnable.isRunnable(input.agent)) {\n if (AgentRunnableSequence.isAgentRunnableSequence(input.agent)) {\n if (input.agent.singleAction) {\n agent = new RunnableSingleActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n } else {\n agent = new RunnableMultiActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n }\n } else {\n agent = new RunnableMultiActionAgent({ runnable: input.agent });\n }\n // TODO: Update BaseChain implementation on breaking change\n returnOnlyOutputs = false;\n } else {\n if (isRunnableAgent(input.agent)) {\n returnOnlyOutputs = false;\n }\n agent = input.agent;\n }\n\n super(input);\n this.agent = agent;\n this.tools = input.tools;\n this.handleParsingErrors =\n input.handleParsingErrors ?? this.handleParsingErrors;\n this.handleToolRuntimeErrors = input.handleToolRuntimeErrors;\n this.returnOnlyOutputs = returnOnlyOutputs;\n if (this.agent._agentActionType() === \"multi\") {\n for (const tool of this.tools) {\n if (tool.returnDirect) {\n throw new Error(\n `Tool with return direct ${tool.name} not supported for multi-action agent.`\n );\n }\n }\n }\n this.returnIntermediateSteps =\n input.returnIntermediateSteps ?? this.returnIntermediateSteps;\n this.maxIterations = input.maxIterations ?? this.maxIterations;\n this.earlyStoppingMethod =\n input.earlyStoppingMethod ?? this.earlyStoppingMethod;\n }\n\n /** Create from agent and a list of tools. */\n static fromAgentAndTools(fields: AgentExecutorInput): AgentExecutor {\n return new AgentExecutor(fields);\n }\n\n get shouldContinueGetter() {\n return this.shouldContinue.bind(this);\n }\n\n /**\n * Method that checks if the agent execution should continue based on the\n * number of iterations.\n * @param iterations The current number of iterations.\n * @returns A boolean indicating whether the agent execution should continue.\n */\n private shouldContinue(iterations: number): boolean {\n return this.maxIterations === undefined || iterations < this.maxIterations;\n }\n\n /** @ignore */\n async _call(\n inputs: ChainValues,\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentExecutorOutput> {\n const toolsByName = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const steps: AgentStep[] = [];\n let iterations = 0;\n\n const getOutput = async (\n finishStep: AgentFinish\n ): Promise<AgentExecutorOutput> => {\n const { returnValues } = finishStep;\n const additional = await this.agent.prepareForOutput(returnValues, steps);\n\n await runManager?.handleAgentEnd(finishStep);\n\n let response;\n\n if (this.returnIntermediateSteps) {\n response = { ...returnValues, intermediateSteps: steps, ...additional };\n } else {\n response = { ...returnValues, ...additional };\n }\n if (!this.returnOnlyOutputs) {\n response = { ...inputs, ...response };\n }\n return response;\n };\n\n while (this.shouldContinue(iterations)) {\n let output;\n try {\n output = await this.agent.plan(\n steps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n // Check if the agent has finished\n if (\"returnValues\" in output) {\n return getOutput(output);\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const newSteps = await Promise.all(\n actions.map(async (action) => {\n await runManager?.handleAgentAction(action);\n const tool =\n action.tool === \"_Exception\"\n ? new ExceptionTool()\n : toolsByName[action.tool?.toLowerCase()];\n let observation;\n try {\n observation = tool\n ? await tool.invoke(\n action.toolInput,\n patchConfig(config, { callbacks: runManager?.getChild() })\n )\n : `${action.tool} is not a valid tool, try another one.`;\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n return { action, observation: observation ?? \"\" };\n } else if (this.handleToolRuntimeErrors !== undefined) {\n observation = this.handleToolRuntimeErrors(e);\n }\n }\n\n return { action, observation: observation ?? \"\" };\n })\n );\n\n steps.push(...newSteps);\n\n const lastStep = steps[steps.length - 1];\n const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];\n\n if (lastTool?.returnDirect) {\n return getOutput({\n returnValues: { [this.agent.returnValues[0]]: lastStep.observation },\n log: \"\",\n });\n }\n\n iterations += 1;\n }\n\n const finish = await this.agent.returnStoppedResponse(\n this.earlyStoppingMethod,\n steps,\n inputs\n );\n\n return getOutput(finish);\n }\n\n async _takeNextStep(\n nameToolMap: Record<string, ToolInterface>,\n inputs: ChainValues,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentFinish | AgentStep[]> {\n let output;\n try {\n output = await this.agent.plan(\n intermediateSteps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n\n if (\"returnValues\" in output) {\n return output;\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const result: AgentStep[] = [];\n for (const agentAction of actions) {\n let observation = \"\";\n if (runManager) {\n await runManager?.handleAgentAction(agentAction);\n }\n if (agentAction.tool in nameToolMap) {\n const tool = nameToolMap[agentAction.tool];\n try {\n observation = await tool.call(\n agentAction.toolInput,\n runManager?.getChild()\n );\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n }\n }\n } else {\n observation = `${\n agentAction.tool\n } is not a valid tool, try another available tool: ${Object.keys(\n nameToolMap\n ).join(\", \")}`;\n }\n result.push({\n action: agentAction,\n observation,\n });\n }\n return result;\n }\n\n async _return(\n output: AgentFinish,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentExecutorOutput> {\n if (runManager) {\n await runManager.handleAgentEnd(output);\n }\n const finalOutput: Record<string, unknown> = output.returnValues;\n if (this.returnIntermediateSteps) {\n finalOutput.intermediateSteps = intermediateSteps;\n }\n return finalOutput;\n }\n\n async _getToolReturn(nextStepOutput: AgentStep): Promise<AgentFinish | null> {\n const { action, observation } = nextStepOutput;\n const nameToolMap = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const [returnValueKey = \"output\"] = this.agent.returnValues;\n // Invalid tools won't be in the map, so we return False.\n if (action.tool in nameToolMap) {\n if (nameToolMap[action.tool].returnDirect) {\n return {\n returnValues: { [returnValueKey]: observation },\n log: \"\",\n };\n }\n }\n return null;\n }\n\n _returnStoppedResponse(earlyStoppingMethod: StoppingMethod) {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: {\n output: \"Agent stopped due to iteration limit or time limit.\",\n },\n log: \"\",\n } as AgentFinish;\n }\n throw new Error(\n `Got unsupported early_stopping_method: ${earlyStoppingMethod}`\n );\n }\n\n async *_streamIterator(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n inputs: Record<string, any>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<ChainValues> {\n const agentExecutorIterator = new AgentExecutorIterator({\n inputs,\n agentExecutor: this,\n config: options,\n // TODO: Deprecate these other parameters\n metadata: options?.metadata,\n tags: options?.tags,\n callbacks: options?.callbacks,\n });\n const iterator = agentExecutorIterator.streamIterator();\n for await (const step of iterator) {\n if (!step) {\n continue;\n }\n yield step;\n }\n }\n\n _chainType() {\n return \"agent_executor\" as const;\n }\n\n serialize(): SerializedLLMChain {\n throw new Error(\"Cannot serialize an AgentExecutor\");\n }\n}\n"],"mappings":";;;;;;;;;AA8CA,IAAa,wBAAb,cACUA,kCAAAA,aAEV;CACE,eAAe;EAAC;EAAa;EAAU;EAAoB;CAE3D;CAEA;CAEA;;CAGA;;CAGA;;CAGA;;CAGA;CAEA;CAEA,IAAI,eAAoD;AACtD,SAAO,KAAK;;;CAId,MAAM,gBAAgB,OAA4C;AAChE,OAAK,gBAAgB,KAAA;AACrB,MAAI,OAAO;GACT,MAAM,kBACJ,MAAM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,KAAK;GACN;AAEH,QAAM,IAAI,MACR,0CAA0C,sBAC3C;;CAGH,OAAO,gBAEL,QACA,SAC6B;EAU7B,MAAM,WATwB,IAAI,sBAAsB;GACtD;GACA,eAAe;GACf,QAAQ;GAER,UAAU,SAAS;GACnB,MAAM,SAAS;GACf,WAAW,SAAS;GACrB,CAAC,CACqC,gBAAgB;AACvD,aAAW,MAAM,QAAQ,UAAU;AACjC,OAAI,CAAC,KACH;AAEF,SAAM;;;CAIV,aAAa;AACX,SAAO;;CAGT,YAAgC;AAC9B,QAAM,IAAI,MAAM,oCAAoC"}
|
package/dist/agents/executor.js
CHANGED
|
@@ -30,7 +30,10 @@ var AgentExecutorIterator = class extends Serializable {
|
|
|
30
30
|
/** Intended to be used as a setter method, needs to be async. */
|
|
31
31
|
async setFinalOutputs(value) {
|
|
32
32
|
this._finalOutputs = void 0;
|
|
33
|
-
if (value)
|
|
33
|
+
if (value) {
|
|
34
|
+
const preparedOutputs = await this.agentExecutor.prepOutputs(this.inputs, value, true);
|
|
35
|
+
this._finalOutputs = preparedOutputs;
|
|
36
|
+
}
|
|
34
37
|
}
|
|
35
38
|
runManager;
|
|
36
39
|
intermediateSteps = [];
|
|
@@ -82,7 +85,8 @@ var AgentExecutorIterator = class extends Serializable {
|
|
|
82
85
|
*/
|
|
83
86
|
async onFirstStep() {
|
|
84
87
|
if (this.iterations === 0) {
|
|
85
|
-
|
|
88
|
+
const callbackManager = await CallbackManager.configure(this.callbacks ?? this.config?.callbacks, this.agentExecutor.callbacks, this.tags ?? this.config?.tags, this.agentExecutor.tags, this.metadata ?? this.config?.metadata, this.agentExecutor.metadata, { verbose: this.agentExecutor.verbose });
|
|
89
|
+
this.runManager = await callbackManager?.handleChainStart(this.agentExecutor.toJSON(), this.inputs, this.config?.runId, void 0, this.tags ?? this.config?.tags, this.metadata ?? this.config?.metadata, this.runName ?? this.config?.runName);
|
|
86
90
|
if (this.config !== void 0) delete this.config.runId;
|
|
87
91
|
}
|
|
88
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","names":[],"sources":["../../src/agents/executor.ts"],"sourcesContent":["import {\n type StructuredToolInterface,\n type ToolInterface,\n ToolInputParsingException,\n Tool,\n} from \"@langchain/core/tools\";\nimport {\n Runnable,\n type RunnableConfig,\n patchConfig,\n} from \"@langchain/core/runnables\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManager,\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport { SerializedLLMChain } from \"../chains/serde.js\";\nimport { StoppingMethod } from \"./types.js\";\nimport {\n AgentRunnableSequence,\n BaseMultiActionAgent,\n BaseSingleActionAgent,\n RunnableMultiActionAgent,\n RunnableSingleActionAgent,\n isRunnableAgent,\n} from \"./agent.js\";\nimport { BaseChain, ChainInputs } from \"../chains/base.js\";\n\ninterface AgentExecutorIteratorInput {\n agentExecutor: AgentExecutor;\n inputs: Record<string, string>;\n config?: RunnableConfig;\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n /** @deprecated Use \"config\" */\n tags?: string[];\n /** @deprecated Use \"config\" */\n metadata?: Record<string, unknown>;\n runName?: string;\n runManager?: CallbackManagerForChainRun;\n}\n\nexport class AgentExecutorIterator\n extends Serializable\n implements AgentExecutorIteratorInput\n{\n lc_namespace = [\"langchain\", \"agents\", \"executor_iterator\"];\n\n agentExecutor: AgentExecutor;\n\n inputs: Record<string, string>;\n\n config?: RunnableConfig;\n\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n\n /** @deprecated Use \"config\" */\n tags: string[] | undefined;\n\n /** @deprecated Use \"config\" */\n metadata: Record<string, unknown> | undefined;\n\n /** @deprecated Use \"config\" */\n runName: string | undefined;\n\n private _finalOutputs: Record<string, unknown> | undefined;\n\n get finalOutputs(): Record<string, unknown> | undefined {\n return this._finalOutputs;\n }\n\n /** Intended to be used as a setter method, needs to be async. */\n async setFinalOutputs(value: Record<string, unknown> | undefined) {\n this._finalOutputs = undefined;\n if (value) {\n const preparedOutputs: Record<string, unknown> =\n await this.agentExecutor.prepOutputs(this.inputs, value, true);\n this._finalOutputs = preparedOutputs;\n }\n }\n\n runManager: CallbackManagerForChainRun | undefined;\n\n intermediateSteps: AgentStep[] = [];\n\n iterations = 0;\n\n get nameToToolMap(): Record<string, ToolInterface> {\n const toolMap = this.agentExecutor.tools.map((tool) => ({\n [tool.name]: tool,\n }));\n return Object.assign({}, ...toolMap);\n }\n\n constructor(fields: AgentExecutorIteratorInput) {\n super(fields);\n this.agentExecutor = fields.agentExecutor;\n this.inputs = fields.inputs;\n this.callbacks = fields.callbacks;\n this.tags = fields.tags;\n this.metadata = fields.metadata;\n this.runName = fields.runName;\n this.runManager = fields.runManager;\n this.config = fields.config;\n }\n\n /**\n * Reset the iterator to its initial state, clearing intermediate steps,\n * iterations, and the final output.\n */\n reset(): void {\n this.intermediateSteps = [];\n this.iterations = 0;\n this._finalOutputs = undefined;\n }\n\n updateIterations(): void {\n this.iterations += 1;\n }\n\n async *streamIterator() {\n this.reset();\n\n // Loop to handle iteration\n while (true) {\n try {\n if (this.iterations === 0) {\n await this.onFirstStep();\n }\n\n const result = await this._callNext();\n yield result;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (\n \"message\" in e &&\n e.message.startsWith(\"Final outputs already reached: \")\n ) {\n if (!this.finalOutputs) {\n throw e;\n }\n return this.finalOutputs;\n }\n if (this.runManager) {\n await this.runManager.handleChainError(e);\n }\n throw e;\n }\n }\n }\n\n /**\n * Perform any necessary setup for the first step\n * of the asynchronous iterator.\n */\n async onFirstStep(): Promise<void> {\n if (this.iterations === 0) {\n const callbackManager = await CallbackManager.configure(\n this.callbacks ?? this.config?.callbacks,\n this.agentExecutor.callbacks,\n this.tags ?? this.config?.tags,\n this.agentExecutor.tags,\n this.metadata ?? this.config?.metadata,\n this.agentExecutor.metadata,\n {\n verbose: this.agentExecutor.verbose,\n }\n );\n this.runManager = await callbackManager?.handleChainStart(\n this.agentExecutor.toJSON(),\n this.inputs,\n this.config?.runId,\n undefined,\n this.tags ?? this.config?.tags,\n this.metadata ?? this.config?.metadata,\n this.runName ?? this.config?.runName\n );\n if (this.config !== undefined) {\n delete this.config.runId;\n }\n }\n }\n\n /**\n * Execute the next step in the chain using the\n * AgentExecutor's _takeNextStep method.\n */\n async _executeNextStep(\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentFinish | AgentStep[]> {\n return this.agentExecutor._takeNextStep(\n this.nameToToolMap,\n this.inputs,\n this.intermediateSteps,\n runManager,\n this.config\n );\n }\n\n /**\n * Process the output of the next step,\n * handling AgentFinish and tool return cases.\n */\n async _processNextStepOutput(\n nextStepOutput: AgentFinish | AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<Record<string, string | AgentStep[]>> {\n if (\"returnValues\" in nextStepOutput) {\n const output = await this.agentExecutor._return(\n nextStepOutput as AgentFinish,\n this.intermediateSteps,\n runManager\n );\n if (this.runManager) {\n await this.runManager.handleChainEnd(output);\n }\n await this.setFinalOutputs(output);\n return output;\n }\n\n this.intermediateSteps = this.intermediateSteps.concat(\n nextStepOutput as AgentStep[]\n );\n\n let output: Record<string, string | AgentStep[]> = {};\n if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {\n const nextStep = nextStepOutput[0];\n const toolReturn = await this.agentExecutor._getToolReturn(nextStep);\n if (toolReturn) {\n output = await this.agentExecutor._return(\n toolReturn,\n this.intermediateSteps,\n runManager\n );\n await this.runManager?.handleChainEnd(output);\n await this.setFinalOutputs(output);\n }\n }\n output = { intermediateSteps: nextStepOutput as AgentStep[] };\n return output;\n }\n\n async _stop(): Promise<Record<string, unknown>> {\n const output = await this.agentExecutor.agent.returnStoppedResponse(\n this.agentExecutor.earlyStoppingMethod,\n this.intermediateSteps,\n this.inputs\n );\n const returnedOutput = await this.agentExecutor._return(\n output,\n this.intermediateSteps,\n this.runManager\n );\n await this.setFinalOutputs(returnedOutput);\n await this.runManager?.handleChainEnd(returnedOutput);\n return returnedOutput;\n }\n\n async _callNext(): Promise<Record<string, unknown>> {\n // final output already reached: stopiteration (final output)\n if (this.finalOutputs) {\n throw new Error(\n `Final outputs already reached: ${JSON.stringify(\n this.finalOutputs,\n null,\n 2\n )}`\n );\n }\n // timeout/max iterations: stopiteration (stopped response)\n if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {\n return this._stop();\n }\n const nextStepOutput = await this._executeNextStep(this.runManager);\n const output = await this._processNextStepOutput(\n nextStepOutput,\n this.runManager\n );\n this.updateIterations();\n return output;\n }\n}\n\ntype ExtractToolType<T> = T extends { ToolType: infer ToolInterface }\n ? ToolInterface\n : StructuredToolInterface;\n\n/**\n * Interface defining the structure of input data for creating an\n * AgentExecutor. It extends ChainInputs and includes additional\n * properties specific to agent execution.\n */\nexport interface AgentExecutorInput extends ChainInputs {\n agent:\n | BaseSingleActionAgent\n | BaseMultiActionAgent\n | Runnable<\n ChainValues & { steps?: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n tools: ExtractToolType<this[\"agent\"]>[];\n returnIntermediateSteps?: boolean;\n maxIterations?: number;\n earlyStoppingMethod?: StoppingMethod;\n handleParsingErrors?:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string);\n handleToolRuntimeErrors?: (e: Error) => string;\n}\n\n// TODO: Type properly with { intermediateSteps?: AgentStep[] };\nexport type AgentExecutorOutput = ChainValues;\n\n/**\n * Tool that just returns the query.\n * Used for exception tracking.\n */\nexport class ExceptionTool extends Tool {\n name = \"_Exception\";\n\n description = \"Exception tool\";\n\n async _call(query: string) {\n return query;\n }\n}\n\n/**\n * A chain managing an agent using tools.\n * @augments BaseChain\n * @example\n * ```typescript\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: async () => loadAgentFromLangchainHub(),\n * tools: [new SerpAPI(), new Calculator()],\n * returnIntermediateSteps: true,\n * });\n *\n * const result = await executor.invoke({\n * input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,\n * });\n *\n * ```\n */\nexport class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {\n static lc_name() {\n return \"AgentExecutor\";\n }\n\n get lc_namespace() {\n return [\"langchain\", \"agents\", \"executor\"];\n }\n\n agent: BaseSingleActionAgent | BaseMultiActionAgent;\n\n tools: this[\"agent\"][\"ToolType\"][];\n\n returnIntermediateSteps = false;\n\n maxIterations?: number = 15;\n\n earlyStoppingMethod: StoppingMethod = \"force\";\n\n // TODO: Update BaseChain implementation on breaking change to include this\n returnOnlyOutputs = true;\n\n /**\n * How to handle errors raised by the agent's output parser.\n Defaults to `False`, which raises the error.\n\n If `true`, the error will be sent back to the LLM as an observation.\n If a string, the string itself will be sent to the LLM as an observation.\n If a callable function, the function will be called with the exception\n as an argument, and the result of that function will be passed to the agent\n as an observation.\n */\n handleParsingErrors:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string) =\n false;\n\n handleToolRuntimeErrors?: (e: Error) => string;\n\n get inputKeys() {\n return this.agent.inputKeys;\n }\n\n get outputKeys() {\n return this.agent.returnValues;\n }\n\n constructor(input: AgentExecutorInput) {\n let agent: BaseSingleActionAgent | BaseMultiActionAgent;\n let returnOnlyOutputs = true;\n if (Runnable.isRunnable(input.agent)) {\n if (AgentRunnableSequence.isAgentRunnableSequence(input.agent)) {\n if (input.agent.singleAction) {\n agent = new RunnableSingleActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n } else {\n agent = new RunnableMultiActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n }\n } else {\n agent = new RunnableMultiActionAgent({ runnable: input.agent });\n }\n // TODO: Update BaseChain implementation on breaking change\n returnOnlyOutputs = false;\n } else {\n if (isRunnableAgent(input.agent)) {\n returnOnlyOutputs = false;\n }\n agent = input.agent;\n }\n\n super(input);\n this.agent = agent;\n this.tools = input.tools;\n this.handleParsingErrors =\n input.handleParsingErrors ?? this.handleParsingErrors;\n this.handleToolRuntimeErrors = input.handleToolRuntimeErrors;\n this.returnOnlyOutputs = returnOnlyOutputs;\n if (this.agent._agentActionType() === \"multi\") {\n for (const tool of this.tools) {\n if (tool.returnDirect) {\n throw new Error(\n `Tool with return direct ${tool.name} not supported for multi-action agent.`\n );\n }\n }\n }\n this.returnIntermediateSteps =\n input.returnIntermediateSteps ?? this.returnIntermediateSteps;\n this.maxIterations = input.maxIterations ?? this.maxIterations;\n this.earlyStoppingMethod =\n input.earlyStoppingMethod ?? this.earlyStoppingMethod;\n }\n\n /** Create from agent and a list of tools. */\n static fromAgentAndTools(fields: AgentExecutorInput): AgentExecutor {\n return new AgentExecutor(fields);\n }\n\n get shouldContinueGetter() {\n return this.shouldContinue.bind(this);\n }\n\n /**\n * Method that checks if the agent execution should continue based on the\n * number of iterations.\n * @param iterations The current number of iterations.\n * @returns A boolean indicating whether the agent execution should continue.\n */\n private shouldContinue(iterations: number): boolean {\n return this.maxIterations === undefined || iterations < this.maxIterations;\n }\n\n /** @ignore */\n async _call(\n inputs: ChainValues,\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentExecutorOutput> {\n const toolsByName = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const steps: AgentStep[] = [];\n let iterations = 0;\n\n const getOutput = async (\n finishStep: AgentFinish\n ): Promise<AgentExecutorOutput> => {\n const { returnValues } = finishStep;\n const additional = await this.agent.prepareForOutput(returnValues, steps);\n\n await runManager?.handleAgentEnd(finishStep);\n\n let response;\n\n if (this.returnIntermediateSteps) {\n response = { ...returnValues, intermediateSteps: steps, ...additional };\n } else {\n response = { ...returnValues, ...additional };\n }\n if (!this.returnOnlyOutputs) {\n response = { ...inputs, ...response };\n }\n return response;\n };\n\n while (this.shouldContinue(iterations)) {\n let output;\n try {\n output = await this.agent.plan(\n steps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n // Check if the agent has finished\n if (\"returnValues\" in output) {\n return getOutput(output);\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const newSteps = await Promise.all(\n actions.map(async (action) => {\n await runManager?.handleAgentAction(action);\n const tool =\n action.tool === \"_Exception\"\n ? new ExceptionTool()\n : toolsByName[action.tool?.toLowerCase()];\n let observation;\n try {\n observation = tool\n ? await tool.invoke(\n action.toolInput,\n patchConfig(config, { callbacks: runManager?.getChild() })\n )\n : `${action.tool} is not a valid tool, try another one.`;\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n return { action, observation: observation ?? \"\" };\n } else if (this.handleToolRuntimeErrors !== undefined) {\n observation = this.handleToolRuntimeErrors(e);\n }\n }\n\n return { action, observation: observation ?? \"\" };\n })\n );\n\n steps.push(...newSteps);\n\n const lastStep = steps[steps.length - 1];\n const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];\n\n if (lastTool?.returnDirect) {\n return getOutput({\n returnValues: { [this.agent.returnValues[0]]: lastStep.observation },\n log: \"\",\n });\n }\n\n iterations += 1;\n }\n\n const finish = await this.agent.returnStoppedResponse(\n this.earlyStoppingMethod,\n steps,\n inputs\n );\n\n return getOutput(finish);\n }\n\n async _takeNextStep(\n nameToolMap: Record<string, ToolInterface>,\n inputs: ChainValues,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentFinish | AgentStep[]> {\n let output;\n try {\n output = await this.agent.plan(\n intermediateSteps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n\n if (\"returnValues\" in output) {\n return output;\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const result: AgentStep[] = [];\n for (const agentAction of actions) {\n let observation = \"\";\n if (runManager) {\n await runManager?.handleAgentAction(agentAction);\n }\n if (agentAction.tool in nameToolMap) {\n const tool = nameToolMap[agentAction.tool];\n try {\n observation = await tool.call(\n agentAction.toolInput,\n runManager?.getChild()\n );\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n }\n }\n } else {\n observation = `${\n agentAction.tool\n } is not a valid tool, try another available tool: ${Object.keys(\n nameToolMap\n ).join(\", \")}`;\n }\n result.push({\n action: agentAction,\n observation,\n });\n }\n return result;\n }\n\n async _return(\n output: AgentFinish,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentExecutorOutput> {\n if (runManager) {\n await runManager.handleAgentEnd(output);\n }\n const finalOutput: Record<string, unknown> = output.returnValues;\n if (this.returnIntermediateSteps) {\n finalOutput.intermediateSteps = intermediateSteps;\n }\n return finalOutput;\n }\n\n async _getToolReturn(nextStepOutput: AgentStep): Promise<AgentFinish | null> {\n const { action, observation } = nextStepOutput;\n const nameToolMap = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const [returnValueKey = \"output\"] = this.agent.returnValues;\n // Invalid tools won't be in the map, so we return False.\n if (action.tool in nameToolMap) {\n if (nameToolMap[action.tool].returnDirect) {\n return {\n returnValues: { [returnValueKey]: observation },\n log: \"\",\n };\n }\n }\n return null;\n }\n\n _returnStoppedResponse(earlyStoppingMethod: StoppingMethod) {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: {\n output: \"Agent stopped due to iteration limit or time limit.\",\n },\n log: \"\",\n } as AgentFinish;\n }\n throw new Error(\n `Got unsupported early_stopping_method: ${earlyStoppingMethod}`\n );\n }\n\n async *_streamIterator(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n inputs: Record<string, any>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<ChainValues> {\n const agentExecutorIterator = new AgentExecutorIterator({\n inputs,\n agentExecutor: this,\n config: options,\n // TODO: Deprecate these other parameters\n metadata: options?.metadata,\n tags: options?.tags,\n callbacks: options?.callbacks,\n });\n const iterator = agentExecutorIterator.streamIterator();\n for await (const step of iterator) {\n if (!step) {\n continue;\n }\n yield step;\n }\n }\n\n _chainType() {\n return \"agent_executor\" as const;\n }\n\n serialize(): SerializedLLMChain {\n throw new Error(\"Cannot serialize an AgentExecutor\");\n }\n}\n"],"mappings":";;;;;;;;AA8CA,IAAa,wBAAb,cACU,aAEV;CACE,eAAe;EAAC;EAAa;EAAU;EAAoB;CAE3D;CAEA;CAEA;;CAGA;;CAGA;;CAGA;;CAGA;CAEA;CAEA,IAAI,eAAoD;AACtD,SAAO,KAAK;;;CAId,MAAM,gBAAgB,OAA4C;AAChE,OAAK,gBAAgB,KAAA;AACrB,MAAI,MAGF,MAAK,gBADH,MAAM,KAAK,cAAc,YAAY,KAAK,QAAQ,OAAO,KAAK;;CAKpE;CAEA,oBAAiC,EAAE;CAEnC,aAAa;CAEb,IAAI,gBAA+C;EACjD,MAAM,UAAU,KAAK,cAAc,MAAM,KAAK,UAAU,GACrD,KAAK,OAAO,MACd,EAAE;AACH,SAAO,OAAO,OAAO,EAAE,EAAE,GAAG,QAAQ;;CAGtC,YAAY,QAAoC;AAC9C,QAAM,OAAO;AACb,OAAK,gBAAgB,OAAO;AAC5B,OAAK,SAAS,OAAO;AACrB,OAAK,YAAY,OAAO;AACxB,OAAK,OAAO,OAAO;AACnB,OAAK,WAAW,OAAO;AACvB,OAAK,UAAU,OAAO;AACtB,OAAK,aAAa,OAAO;AACzB,OAAK,SAAS,OAAO;;;;;;CAOvB,QAAc;AACZ,OAAK,oBAAoB,EAAE;AAC3B,OAAK,aAAa;AAClB,OAAK,gBAAgB,KAAA;;C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,MAAM,cAAuC,OAAO;AACpD,MAAI,KAAK,wBACP,aAAY,oBAAoB;AAElC,SAAO;;CAGT,MAAM,eAAe,gBAAwD;EAC3E,MAAM,EAAE,QAAQ,gBAAgB;EAChC,MAAM,cAAc,OAAO,YACzB,KAAK,MAAM,KAAK,MAAM,CAAC,EAAE,KAAK,aAAa,EAAE,EAAE,CAAC,CACjD;EACD,MAAM,CAAC,iBAAiB,YAAY,KAAK,MAAM;AAE/C,MAAI,OAAO,QAAQ;OACb,YAAY,OAAO,MAAM,aAC3B,QAAO;IACL,cAAc,GAAG,iBAAiB,aAAa;IAC/C,KAAK;IACN;;AAGL,SAAO;;CAGT,uBAAuB,qBAAqC;AAC1D,MAAI,wBAAwB,QAC1B,QAAO;GACL,cAAc,EACZ,QAAQ,uDACT;GACD,KAAK;GACN;AAEH,QAAM,IAAI,MACR,0CAA0C,sBAC3C;;CAGH,OAAO,gBAEL,QACA,SAC6B;EAU7B,MAAM,WATwB,IAAI,sBAAsB;GACtD;GACA,eAAe;GACf,QAAQ;GAER,UAAU,SAAS;GACnB,MAAM,SAAS;GACf,WAAW,SAAS;GACrB,CAAC,CACqC,gBAAgB;AACvD,aAAW,MAAM,QAAQ,UAAU;AACjC,OAAI,CAAC,KACH;AAEF,SAAM;;;CAIV,aAAa;AACX,SAAO;;CAGT,YAAgC;AAC9B,QAAM,IAAI,MAAM,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"executor.js","names":[],"sources":["../../src/agents/executor.ts"],"sourcesContent":["import {\n type StructuredToolInterface,\n type ToolInterface,\n ToolInputParsingException,\n Tool,\n} from \"@langchain/core/tools\";\nimport {\n Runnable,\n type RunnableConfig,\n patchConfig,\n} from \"@langchain/core/runnables\";\nimport { AgentAction, AgentFinish, AgentStep } from \"@langchain/core/agents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManager,\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { Serializable } from \"@langchain/core/load/serializable\";\nimport { SerializedLLMChain } from \"../chains/serde.js\";\nimport { StoppingMethod } from \"./types.js\";\nimport {\n AgentRunnableSequence,\n BaseMultiActionAgent,\n BaseSingleActionAgent,\n RunnableMultiActionAgent,\n RunnableSingleActionAgent,\n isRunnableAgent,\n} from \"./agent.js\";\nimport { BaseChain, ChainInputs } from \"../chains/base.js\";\n\ninterface AgentExecutorIteratorInput {\n agentExecutor: AgentExecutor;\n inputs: Record<string, string>;\n config?: RunnableConfig;\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n /** @deprecated Use \"config\" */\n tags?: string[];\n /** @deprecated Use \"config\" */\n metadata?: Record<string, unknown>;\n runName?: string;\n runManager?: CallbackManagerForChainRun;\n}\n\nexport class AgentExecutorIterator\n extends Serializable\n implements AgentExecutorIteratorInput\n{\n lc_namespace = [\"langchain\", \"agents\", \"executor_iterator\"];\n\n agentExecutor: AgentExecutor;\n\n inputs: Record<string, string>;\n\n config?: RunnableConfig;\n\n /** @deprecated Use \"config\" */\n callbacks?: Callbacks;\n\n /** @deprecated Use \"config\" */\n tags: string[] | undefined;\n\n /** @deprecated Use \"config\" */\n metadata: Record<string, unknown> | undefined;\n\n /** @deprecated Use \"config\" */\n runName: string | undefined;\n\n private _finalOutputs: Record<string, unknown> | undefined;\n\n get finalOutputs(): Record<string, unknown> | undefined {\n return this._finalOutputs;\n }\n\n /** Intended to be used as a setter method, needs to be async. */\n async setFinalOutputs(value: Record<string, unknown> | undefined) {\n this._finalOutputs = undefined;\n if (value) {\n const preparedOutputs: Record<string, unknown> =\n await this.agentExecutor.prepOutputs(this.inputs, value, true);\n this._finalOutputs = preparedOutputs;\n }\n }\n\n runManager: CallbackManagerForChainRun | undefined;\n\n intermediateSteps: AgentStep[] = [];\n\n iterations = 0;\n\n get nameToToolMap(): Record<string, ToolInterface> {\n const toolMap = this.agentExecutor.tools.map((tool) => ({\n [tool.name]: tool,\n }));\n return Object.assign({}, ...toolMap);\n }\n\n constructor(fields: AgentExecutorIteratorInput) {\n super(fields);\n this.agentExecutor = fields.agentExecutor;\n this.inputs = fields.inputs;\n this.callbacks = fields.callbacks;\n this.tags = fields.tags;\n this.metadata = fields.metadata;\n this.runName = fields.runName;\n this.runManager = fields.runManager;\n this.config = fields.config;\n }\n\n /**\n * Reset the iterator to its initial state, clearing intermediate steps,\n * iterations, and the final output.\n */\n reset(): void {\n this.intermediateSteps = [];\n this.iterations = 0;\n this._finalOutputs = undefined;\n }\n\n updateIterations(): void {\n this.iterations += 1;\n }\n\n async *streamIterator() {\n this.reset();\n\n // Loop to handle iteration\n while (true) {\n try {\n if (this.iterations === 0) {\n await this.onFirstStep();\n }\n\n const result = await this._callNext();\n yield result;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (\n \"message\" in e &&\n e.message.startsWith(\"Final outputs already reached: \")\n ) {\n if (!this.finalOutputs) {\n throw e;\n }\n return this.finalOutputs;\n }\n if (this.runManager) {\n await this.runManager.handleChainError(e);\n }\n throw e;\n }\n }\n }\n\n /**\n * Perform any necessary setup for the first step\n * of the asynchronous iterator.\n */\n async onFirstStep(): Promise<void> {\n if (this.iterations === 0) {\n const callbackManager = await CallbackManager.configure(\n this.callbacks ?? this.config?.callbacks,\n this.agentExecutor.callbacks,\n this.tags ?? this.config?.tags,\n this.agentExecutor.tags,\n this.metadata ?? this.config?.metadata,\n this.agentExecutor.metadata,\n {\n verbose: this.agentExecutor.verbose,\n }\n );\n this.runManager = await callbackManager?.handleChainStart(\n this.agentExecutor.toJSON(),\n this.inputs,\n this.config?.runId,\n undefined,\n this.tags ?? this.config?.tags,\n this.metadata ?? this.config?.metadata,\n this.runName ?? this.config?.runName\n );\n if (this.config !== undefined) {\n delete this.config.runId;\n }\n }\n }\n\n /**\n * Execute the next step in the chain using the\n * AgentExecutor's _takeNextStep method.\n */\n async _executeNextStep(\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentFinish | AgentStep[]> {\n return this.agentExecutor._takeNextStep(\n this.nameToToolMap,\n this.inputs,\n this.intermediateSteps,\n runManager,\n this.config\n );\n }\n\n /**\n * Process the output of the next step,\n * handling AgentFinish and tool return cases.\n */\n async _processNextStepOutput(\n nextStepOutput: AgentFinish | AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<Record<string, string | AgentStep[]>> {\n if (\"returnValues\" in nextStepOutput) {\n const output = await this.agentExecutor._return(\n nextStepOutput as AgentFinish,\n this.intermediateSteps,\n runManager\n );\n if (this.runManager) {\n await this.runManager.handleChainEnd(output);\n }\n await this.setFinalOutputs(output);\n return output;\n }\n\n this.intermediateSteps = this.intermediateSteps.concat(\n nextStepOutput as AgentStep[]\n );\n\n let output: Record<string, string | AgentStep[]> = {};\n if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {\n const nextStep = nextStepOutput[0];\n const toolReturn = await this.agentExecutor._getToolReturn(nextStep);\n if (toolReturn) {\n output = await this.agentExecutor._return(\n toolReturn,\n this.intermediateSteps,\n runManager\n );\n await this.runManager?.handleChainEnd(output);\n await this.setFinalOutputs(output);\n }\n }\n output = { intermediateSteps: nextStepOutput as AgentStep[] };\n return output;\n }\n\n async _stop(): Promise<Record<string, unknown>> {\n const output = await this.agentExecutor.agent.returnStoppedResponse(\n this.agentExecutor.earlyStoppingMethod,\n this.intermediateSteps,\n this.inputs\n );\n const returnedOutput = await this.agentExecutor._return(\n output,\n this.intermediateSteps,\n this.runManager\n );\n await this.setFinalOutputs(returnedOutput);\n await this.runManager?.handleChainEnd(returnedOutput);\n return returnedOutput;\n }\n\n async _callNext(): Promise<Record<string, unknown>> {\n // final output already reached: stopiteration (final output)\n if (this.finalOutputs) {\n throw new Error(\n `Final outputs already reached: ${JSON.stringify(\n this.finalOutputs,\n null,\n 2\n )}`\n );\n }\n // timeout/max iterations: stopiteration (stopped response)\n if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {\n return this._stop();\n }\n const nextStepOutput = await this._executeNextStep(this.runManager);\n const output = await this._processNextStepOutput(\n nextStepOutput,\n this.runManager\n );\n this.updateIterations();\n return output;\n }\n}\n\ntype ExtractToolType<T> = T extends { ToolType: infer ToolInterface }\n ? ToolInterface\n : StructuredToolInterface;\n\n/**\n * Interface defining the structure of input data for creating an\n * AgentExecutor. It extends ChainInputs and includes additional\n * properties specific to agent execution.\n */\nexport interface AgentExecutorInput extends ChainInputs {\n agent:\n | BaseSingleActionAgent\n | BaseMultiActionAgent\n | Runnable<\n ChainValues & { steps?: AgentStep[] },\n AgentAction[] | AgentAction | AgentFinish\n >;\n tools: ExtractToolType<this[\"agent\"]>[];\n returnIntermediateSteps?: boolean;\n maxIterations?: number;\n earlyStoppingMethod?: StoppingMethod;\n handleParsingErrors?:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string);\n handleToolRuntimeErrors?: (e: Error) => string;\n}\n\n// TODO: Type properly with { intermediateSteps?: AgentStep[] };\nexport type AgentExecutorOutput = ChainValues;\n\n/**\n * Tool that just returns the query.\n * Used for exception tracking.\n */\nexport class ExceptionTool extends Tool {\n name = \"_Exception\";\n\n description = \"Exception tool\";\n\n async _call(query: string) {\n return query;\n }\n}\n\n/**\n * A chain managing an agent using tools.\n * @augments BaseChain\n * @example\n * ```typescript\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: async () => loadAgentFromLangchainHub(),\n * tools: [new SerpAPI(), new Calculator()],\n * returnIntermediateSteps: true,\n * });\n *\n * const result = await executor.invoke({\n * input: `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`,\n * });\n *\n * ```\n */\nexport class AgentExecutor extends BaseChain<ChainValues, AgentExecutorOutput> {\n static lc_name() {\n return \"AgentExecutor\";\n }\n\n get lc_namespace() {\n return [\"langchain\", \"agents\", \"executor\"];\n }\n\n agent: BaseSingleActionAgent | BaseMultiActionAgent;\n\n tools: this[\"agent\"][\"ToolType\"][];\n\n returnIntermediateSteps = false;\n\n maxIterations?: number = 15;\n\n earlyStoppingMethod: StoppingMethod = \"force\";\n\n // TODO: Update BaseChain implementation on breaking change to include this\n returnOnlyOutputs = true;\n\n /**\n * How to handle errors raised by the agent's output parser.\n Defaults to `False`, which raises the error.\n\n If `true`, the error will be sent back to the LLM as an observation.\n If a string, the string itself will be sent to the LLM as an observation.\n If a callable function, the function will be called with the exception\n as an argument, and the result of that function will be passed to the agent\n as an observation.\n */\n handleParsingErrors:\n | boolean\n | string\n | ((e: OutputParserException | ToolInputParsingException) => string) =\n false;\n\n handleToolRuntimeErrors?: (e: Error) => string;\n\n get inputKeys() {\n return this.agent.inputKeys;\n }\n\n get outputKeys() {\n return this.agent.returnValues;\n }\n\n constructor(input: AgentExecutorInput) {\n let agent: BaseSingleActionAgent | BaseMultiActionAgent;\n let returnOnlyOutputs = true;\n if (Runnable.isRunnable(input.agent)) {\n if (AgentRunnableSequence.isAgentRunnableSequence(input.agent)) {\n if (input.agent.singleAction) {\n agent = new RunnableSingleActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n } else {\n agent = new RunnableMultiActionAgent({\n runnable: input.agent,\n streamRunnable: input.agent.streamRunnable,\n });\n }\n } else {\n agent = new RunnableMultiActionAgent({ runnable: input.agent });\n }\n // TODO: Update BaseChain implementation on breaking change\n returnOnlyOutputs = false;\n } else {\n if (isRunnableAgent(input.agent)) {\n returnOnlyOutputs = false;\n }\n agent = input.agent;\n }\n\n super(input);\n this.agent = agent;\n this.tools = input.tools;\n this.handleParsingErrors =\n input.handleParsingErrors ?? this.handleParsingErrors;\n this.handleToolRuntimeErrors = input.handleToolRuntimeErrors;\n this.returnOnlyOutputs = returnOnlyOutputs;\n if (this.agent._agentActionType() === \"multi\") {\n for (const tool of this.tools) {\n if (tool.returnDirect) {\n throw new Error(\n `Tool with return direct ${tool.name} not supported for multi-action agent.`\n );\n }\n }\n }\n this.returnIntermediateSteps =\n input.returnIntermediateSteps ?? this.returnIntermediateSteps;\n this.maxIterations = input.maxIterations ?? this.maxIterations;\n this.earlyStoppingMethod =\n input.earlyStoppingMethod ?? this.earlyStoppingMethod;\n }\n\n /** Create from agent and a list of tools. */\n static fromAgentAndTools(fields: AgentExecutorInput): AgentExecutor {\n return new AgentExecutor(fields);\n }\n\n get shouldContinueGetter() {\n return this.shouldContinue.bind(this);\n }\n\n /**\n * Method that checks if the agent execution should continue based on the\n * number of iterations.\n * @param iterations The current number of iterations.\n * @returns A boolean indicating whether the agent execution should continue.\n */\n private shouldContinue(iterations: number): boolean {\n return this.maxIterations === undefined || iterations < this.maxIterations;\n }\n\n /** @ignore */\n async _call(\n inputs: ChainValues,\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentExecutorOutput> {\n const toolsByName = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const steps: AgentStep[] = [];\n let iterations = 0;\n\n const getOutput = async (\n finishStep: AgentFinish\n ): Promise<AgentExecutorOutput> => {\n const { returnValues } = finishStep;\n const additional = await this.agent.prepareForOutput(returnValues, steps);\n\n await runManager?.handleAgentEnd(finishStep);\n\n let response;\n\n if (this.returnIntermediateSteps) {\n response = { ...returnValues, intermediateSteps: steps, ...additional };\n } else {\n response = { ...returnValues, ...additional };\n }\n if (!this.returnOnlyOutputs) {\n response = { ...inputs, ...response };\n }\n return response;\n };\n\n while (this.shouldContinue(iterations)) {\n let output;\n try {\n output = await this.agent.plan(\n steps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n // Check if the agent has finished\n if (\"returnValues\" in output) {\n return getOutput(output);\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const newSteps = await Promise.all(\n actions.map(async (action) => {\n await runManager?.handleAgentAction(action);\n const tool =\n action.tool === \"_Exception\"\n ? new ExceptionTool()\n : toolsByName[action.tool?.toLowerCase()];\n let observation;\n try {\n observation = tool\n ? await tool.invoke(\n action.toolInput,\n patchConfig(config, { callbacks: runManager?.getChild() })\n )\n : `${action.tool} is not a valid tool, try another one.`;\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n return { action, observation: observation ?? \"\" };\n } else if (this.handleToolRuntimeErrors !== undefined) {\n observation = this.handleToolRuntimeErrors(e);\n }\n }\n\n return { action, observation: observation ?? \"\" };\n })\n );\n\n steps.push(...newSteps);\n\n const lastStep = steps[steps.length - 1];\n const lastTool = toolsByName[lastStep.action.tool?.toLowerCase()];\n\n if (lastTool?.returnDirect) {\n return getOutput({\n returnValues: { [this.agent.returnValues[0]]: lastStep.observation },\n log: \"\",\n });\n }\n\n iterations += 1;\n }\n\n const finish = await this.agent.returnStoppedResponse(\n this.earlyStoppingMethod,\n steps,\n inputs\n );\n\n return getOutput(finish);\n }\n\n async _takeNextStep(\n nameToolMap: Record<string, ToolInterface>,\n inputs: ChainValues,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun,\n config?: RunnableConfig\n ): Promise<AgentFinish | AgentStep[]> {\n let output;\n try {\n output = await this.agent.plan(\n intermediateSteps,\n inputs,\n runManager?.getChild(),\n config\n );\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof OutputParserException) {\n let observation;\n let text = e.message;\n if (this.handleParsingErrors === true) {\n if (e.sendToLLM) {\n observation = e.observation;\n text = e.llmOutput ?? \"\";\n } else {\n observation = \"Invalid or incomplete response\";\n }\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n output = {\n tool: \"_Exception\",\n toolInput: observation,\n log: text,\n } as AgentAction;\n } else {\n throw e;\n }\n }\n\n if (\"returnValues\" in output) {\n return output;\n }\n\n let actions: AgentAction[];\n if (Array.isArray(output)) {\n actions = output as AgentAction[];\n } else {\n actions = [output as AgentAction];\n }\n\n const result: AgentStep[] = [];\n for (const agentAction of actions) {\n let observation = \"\";\n if (runManager) {\n await runManager?.handleAgentAction(agentAction);\n }\n if (agentAction.tool in nameToolMap) {\n const tool = nameToolMap[agentAction.tool];\n try {\n observation = await tool.call(\n agentAction.toolInput,\n runManager?.getChild()\n );\n if (typeof observation !== \"string\") {\n throw new Error(\n \"Received unsupported non-string response from tool call.\"\n );\n }\n } catch (e) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof ToolInputParsingException) {\n if (this.handleParsingErrors === true) {\n observation =\n \"Invalid or incomplete tool input. Please try again.\";\n } else if (typeof this.handleParsingErrors === \"string\") {\n observation = this.handleParsingErrors;\n } else if (typeof this.handleParsingErrors === \"function\") {\n observation = this.handleParsingErrors(e);\n } else {\n throw e;\n }\n observation = await new ExceptionTool().call(\n observation,\n runManager?.getChild()\n );\n }\n }\n } else {\n observation = `${\n agentAction.tool\n } is not a valid tool, try another available tool: ${Object.keys(\n nameToolMap\n ).join(\", \")}`;\n }\n result.push({\n action: agentAction,\n observation,\n });\n }\n return result;\n }\n\n async _return(\n output: AgentFinish,\n intermediateSteps: AgentStep[],\n runManager?: CallbackManagerForChainRun\n ): Promise<AgentExecutorOutput> {\n if (runManager) {\n await runManager.handleAgentEnd(output);\n }\n const finalOutput: Record<string, unknown> = output.returnValues;\n if (this.returnIntermediateSteps) {\n finalOutput.intermediateSteps = intermediateSteps;\n }\n return finalOutput;\n }\n\n async _getToolReturn(nextStepOutput: AgentStep): Promise<AgentFinish | null> {\n const { action, observation } = nextStepOutput;\n const nameToolMap = Object.fromEntries(\n this.tools.map((t) => [t.name.toLowerCase(), t])\n );\n const [returnValueKey = \"output\"] = this.agent.returnValues;\n // Invalid tools won't be in the map, so we return False.\n if (action.tool in nameToolMap) {\n if (nameToolMap[action.tool].returnDirect) {\n return {\n returnValues: { [returnValueKey]: observation },\n log: \"\",\n };\n }\n }\n return null;\n }\n\n _returnStoppedResponse(earlyStoppingMethod: StoppingMethod) {\n if (earlyStoppingMethod === \"force\") {\n return {\n returnValues: {\n output: \"Agent stopped due to iteration limit or time limit.\",\n },\n log: \"\",\n } as AgentFinish;\n }\n throw new Error(\n `Got unsupported early_stopping_method: ${earlyStoppingMethod}`\n );\n }\n\n async *_streamIterator(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n inputs: Record<string, any>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<ChainValues> {\n const agentExecutorIterator = new AgentExecutorIterator({\n inputs,\n agentExecutor: this,\n config: options,\n // TODO: Deprecate these other parameters\n metadata: options?.metadata,\n tags: options?.tags,\n callbacks: options?.callbacks,\n });\n const iterator = agentExecutorIterator.streamIterator();\n for await (const step of iterator) {\n if (!step) {\n continue;\n }\n yield step;\n }\n }\n\n _chainType() {\n return \"agent_executor\" as const;\n }\n\n serialize(): SerializedLLMChain {\n throw new Error(\"Cannot serialize an AgentExecutor\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L,cAAc,GAAG,iBAAiB,aAAa;IAC/C,KAAK;IACN;;AAGL,SAAO;;CAGT,uBAAuB,qBAAqC;AAC1D,MAAI,wBAAwB,QAC1B,QAAO;GACL,cAAc,EACZ,QAAQ,uDACT;GACD,KAAK;GACN;AAEH,QAAM,IAAI,MACR,0CAA0C,sBAC3C;;CAGH,OAAO,gBAEL,QACA,SAC6B;EAU7B,MAAM,WATwB,IAAI,sBAAsB;GACtD;GACA,eAAe;GACf,QAAQ;GAER,UAAU,SAAS;GACnB,MAAM,SAAS;GACf,WAAW,SAAS;GACrB,CAAC,CACqC,gBAAgB;AACvD,aAAW,MAAM,QAAQ,UAAU;AACjC,OAAI,CAAC,KACH;AAEF,SAAM;;;CAIV,aAAa;AACX,SAAO;;CAGT,YAAgC;AAC9B,QAAM,IAAI,MAAM,oCAAoC"}
|
|
@@ -24,10 +24,10 @@ declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {
|
|
|
24
24
|
tool?: undefined;
|
|
25
25
|
toolInput?: undefined;
|
|
26
26
|
} | {
|
|
27
|
+
returnValues?: undefined;
|
|
27
28
|
tool: string;
|
|
28
29
|
toolInput: string;
|
|
29
30
|
log: string;
|
|
30
|
-
returnValues?: undefined;
|
|
31
31
|
}>;
|
|
32
32
|
/**
|
|
33
33
|
* Returns the format instructions for parsing the output of an agent
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
node_path = require_runtime.__toESM(node_path);
|
|
4
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
5
5
|
let node_fs_promises = require("node:fs/promises");
|
|
6
|
-
node_fs_promises = require_runtime.__toESM(node_fs_promises);
|
|
6
|
+
node_fs_promises = require_runtime.__toESM(node_fs_promises, 1);
|
|
7
7
|
let _langchain_core_caches = require("@langchain/core/caches");
|
|
8
8
|
//#region src/cache/file_system.ts
|
|
9
9
|
var file_system_exports = /* @__PURE__ */ require_runtime.__exportAll({ LocalFileCache: () => LocalFileCache });
|
|
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
|
|
3
3
|
const require_document_loaders_fs_text = require("./text.cjs");
|
|
4
4
|
let jsonpointer = require("jsonpointer");
|
|
5
|
-
jsonpointer = require_runtime.__toESM(jsonpointer);
|
|
5
|
+
jsonpointer = require_runtime.__toESM(jsonpointer, 1);
|
|
6
6
|
//#region src/document_loaders/fs/json.ts
|
|
7
7
|
var json_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
8
8
|
JSONLinesLoader: () => JSONLinesLoader,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generative_agent.cjs","names":["BaseChain","LLMChain","PromptTemplate"],"sources":["../../../src/experimental/generative_agents/generative_agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { GenerativeAgentMemory } from \"./generative_agent_memory.js\";\nimport { BaseChain } from \"../../chains/base.js\";\n\n/**\n * Configuration for the GenerativeAgent class. Defines the character's\n * name, optional age, permanent traits, status, verbosity, and summary\n * refresh seconds.\n */\nexport type GenerativeAgentConfig = {\n name: string;\n age?: number;\n traits: string;\n status: string;\n verbose?: boolean;\n summaryRefreshSeconds?: number;\n // dailySummaries?: string[];\n};\n\n/**\n * Implementation of a generative agent that can learn and form new memories over\n * time. It extends the BaseChain class, which is a generic\n * sequence of calls to components, including other chains.\n * @example\n * ```typescript\n * const tommie: GenerativeAgent = new GenerativeAgent(\n * new OpenAI({ temperature: 0.9, maxTokens: 1500 }),\n * new GenerativeAgentMemory(\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * new TimeWeightedVectorStoreRetriever({\n * vectorStore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * }),\n * { reflectionThreshold: 8 },\n * ),\n * {\n * name: \"Tommie\",\n * age: 25,\n * traits: \"anxious, likes design, talkative\",\n * status: \"looking for a job\",\n * },\n * );\n *\n * await tommie.addMemory(\n * \"Tommie remembers his dog, Bruno, from when he was a kid\",\n * new Date(),\n * );\n * const summary = await tommie.getSummary({ forceRefresh: true });\n * const response = await tommie.generateDialogueResponse(\n * \"USER says Hello Tommie, how are you today?\",\n * );\n * ```\n */\nexport class GenerativeAgent extends BaseChain {\n static lc_name() {\n return \"GenerativeAgent\";\n }\n\n // a character with memory and innate characterisitics\n name: string; // the character's name\n\n age?: number; // the optional age of the character\n\n traits: string; // permanent traits to ascribe to the character\n\n status: string; // the traits of the character you wish not to change\n\n longTermMemory: GenerativeAgentMemory;\n\n llm: BaseLanguageModelInterface; // the underlying language model\n\n verbose: boolean; // false\n\n private summary: string; // stateful self-summary generated via reflection on the character's memory.\n\n private summaryRefreshSeconds = 3600;\n\n private lastRefreshed: Date; // the last time the character's summary was regenerated\n\n // TODO: Add support for daily summaries\n // private dailySummaries: string[] = []; // summary of the events in the plan that the agent took.\n\n _chainType(): string {\n return \"generative_agent_executor\";\n }\n\n get inputKeys(): string[] {\n return [\"observation\", \"suffix\", \"now\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\", \"continue_dialogue\"];\n }\n\n constructor(\n llm: BaseLanguageModelInterface,\n longTermMemory: GenerativeAgentMemory,\n config: GenerativeAgentConfig\n ) {\n super();\n this.llm = llm;\n this.longTermMemory = longTermMemory;\n this.name = config.name;\n this.age = config.age;\n this.traits = config.traits;\n this.status = config.status;\n this.verbose = config.verbose ?? this.verbose;\n this.summary = \"\";\n this.summaryRefreshSeconds =\n config.summaryRefreshSeconds ?? this.summaryRefreshSeconds;\n this.lastRefreshed = new Date();\n // this.dailySummaries = config.dailySummaries ?? this.dailySummaries;\n }\n\n // LLM methods\n /**\n * Parses a newline-separated string into a list of strings.\n * @param text The string to parse.\n * @returns An array of strings parsed from the input text.\n */\n parseList(text: string): string[] {\n // parse a newline-seperated string into a list of strings\n const lines: string[] = text.trim().split(\"\\n\");\n const result: string[] = lines.map((line: string) =>\n line.replace(/^\\s*\\d+\\.\\s*/, \"\").trim()\n );\n return result;\n }\n\n /**\n * Creates a new LLMChain with the given prompt and the agent's language\n * model, verbosity, output key, and memory.\n * @param prompt The prompt to use for the LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\", // new\n memory: this.longTermMemory,\n });\n return chain;\n }\n\n /**\n * Extracts the observed entity from the given observation.\n * @param observation The observation to extract the entity from.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted entity as a string.\n */\n async getEntityFromObservations(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the observed entity in the following observation? {observation}\" +\n \"\\nEntity=\"\n );\n\n const result = await this.chain(prompt).call(\n {\n observation,\n },\n runManager?.getChild(\"entity_extractor\")\n );\n\n return result.output;\n }\n\n /**\n * Extracts the action of the given entity from the given observation.\n * @param observation The observation to extract the action from.\n * @param entityName The name of the entity to extract the action for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted action as a string.\n */\n async getEntityAction(\n observation: string,\n entityName: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the {entity} doing in the following observation? {observation}\" +\n \"\\nThe {entity} is\"\n );\n\n const result = await this.chain(prompt).call(\n {\n entity: entityName,\n observation,\n },\n runManager?.getChild(\"entity_action_extractor\")\n );\n const trimmedResult = result.output.trim();\n return trimmedResult;\n }\n\n /**\n * Summarizes memories that are most relevant to an observation.\n * @param observation The observation to summarize related memories for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The summarized memories as a string.\n */\n async summarizeRelatedMemories(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n // summarize memories that are most relevant to an observation\n const prompt = PromptTemplate.fromTemplate(\n `\n{q1}?\nContext from memory:\n{relevant_memories}\nRelevant context:`\n );\n const entityName = await this.getEntityFromObservations(\n observation,\n runManager\n );\n const entityAction = await this.getEntityAction(\n observation,\n entityName,\n runManager\n );\n const q1 = `What is the relationship between ${this.name} and ${entityName}`;\n const q2 = `${entityName} is ${entityAction}`;\n const response = await this.chain(prompt).call(\n {\n q1,\n queries: [q1, q2],\n },\n runManager?.getChild(\"entity_relationships\")\n );\n\n return response.output.trim(); // added output\n }\n\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const { observation, suffix, now } = values;\n // react to a given observation or dialogue act\n const prompt = PromptTemplate.fromTemplate(\n `{agent_summary_description}` +\n `\\nIt is {current_time}.` +\n `\\n{agent_name}'s status: {agent_status}` +\n `\\nSummary of relevant context from {agent_name}'s memory:` +\n \"\\n{relevant_memories}\" +\n `\\nMost recent observations: {most_recent_memories}` +\n `\\nObservation: {observation}` +\n `\\n\\n${suffix}`\n );\n\n const agentSummaryDescription = await this.getSummary({}, runManager); // now = now in param\n const relevantMemoriesStr = await this.summarizeRelatedMemories(\n observation,\n runManager\n );\n const currentTime = (now || new Date()).toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n const chainInputs: ChainValues = {\n agent_summary_description: agentSummaryDescription,\n current_time: currentTime,\n agent_name: this.name,\n observation,\n agent_status: this.status,\n most_recent_memories: \"\",\n };\n\n chainInputs[this.longTermMemory.getRelevantMemoriesKey()] =\n relevantMemoriesStr;\n\n const consumedTokens = await this.llm.getNumTokens(\n await prompt.format({ ...chainInputs })\n );\n\n chainInputs[this.longTermMemory.getMostRecentMemoriesTokenKey()] =\n consumedTokens;\n const response = await this.chain(prompt).call(\n chainInputs,\n runManager?.getChild(\"reaction_from_summary\")\n );\n\n const rawOutput = response.output;\n let output = rawOutput;\n let continue_dialogue = false;\n\n if (rawOutput.includes(\"REACT:\")) {\n const reaction = this._cleanResponse(rawOutput.split(\"REACT:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and reacted by ${reaction}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${reaction}`;\n continue_dialogue = false;\n } else if (rawOutput.includes(\"SAY:\")) {\n const saidValue = this._cleanResponse(rawOutput.split(\"SAY:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and said ${saidValue}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${saidValue}`;\n continue_dialogue = true;\n } else if (rawOutput.includes(\"GOODBYE:\")) {\n const farewell = this._cleanResponse(\n rawOutput.split(\"GOODBYE:\").pop() ?? \"\"\n );\n await this.addMemory(\n `${this.name} observed ${observation} and said ${farewell}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${farewell}`;\n continue_dialogue = false;\n }\n\n return { output, continue_dialogue };\n }\n\n private _cleanResponse(text: string | undefined): string {\n if (text === undefined) {\n return \"\";\n }\n const regex = new RegExp(`^${this.name} `);\n return text.replace(regex, \"\").trim();\n }\n\n /**\n * Generates a reaction to the given observation.\n * @param observation The observation to generate a reaction for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateReaction(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate: string =\n `Should {agent_name} react to the observation, and if so,` +\n ` what would be an appropriate reaction? Respond in one line.` +\n ` If the action is to engage in dialogue, write:\\nSAY: \"what to say\"` +\n ` \\notherwise, write:\\nREACT: {agent_name}'s reaction (if anything).` +\n ` \\nEither do nothing, react, or say something but not both.\\n\\n`;\n\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n /**\n * Generates a dialogue response to the given observation.\n * @param observation The observation to generate a dialogue response for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateDialogueResponse(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate = `What would ${this.name} say? To end the conversation, write: GOODBYE: \"what to say\". Otherwise to continue the conversation, write: SAY: \"what to say next\"\\n\\n`;\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n // Agent stateful' summary methods\n // Each dialog or response prompt includes a header\n // summarizing the agent's self-description. This is\n // updated periodically through probing it's memories\n /**\n * Gets the agent's summary, which includes the agent's name, age, traits,\n * and a summary of the agent's core characteristics. The summary is\n * updated periodically through probing the agent's memories.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The agent's summary as a string.\n */\n async getSummary(\n config?: {\n now?: Date;\n forceRefresh?: boolean;\n },\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const { now = new Date(), forceRefresh = false } = config ?? {};\n\n const sinceRefresh = Math.floor(\n (now.getTime() - this.lastRefreshed.getTime()) / 1000\n );\n\n if (\n !this.summary ||\n sinceRefresh >= this.summaryRefreshSeconds ||\n forceRefresh\n ) {\n this.summary = await this.computeAgentSummary(runManager);\n this.lastRefreshed = now;\n }\n\n let age;\n if (this.age) {\n age = this.age;\n } else {\n age = \"N/A\";\n }\n\n return `Name: ${this.name} (age: ${age})\nInnate traits: ${this.traits}\n${this.summary}`;\n }\n\n /**\n * Computes the agent's summary by summarizing the agent's core\n * characteristics given the agent's relevant memories.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The computed summary as a string.\n */\n async computeAgentSummary(\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"How would you summarize {name}'s core characteristics given the following statements:\\n\" +\n \"----------\" +\n \"{relevant_memories}\" +\n \"----------\" +\n \"Do not embellish.\" +\n \"\\n\\nSummary: \"\n );\n // the agent seeks to think about their core characterisitics\n const result = await this.chain(prompt).call(\n {\n name: this.name,\n queries: [`${this.name}'s core characteristics`],\n },\n runManager?.getChild(\"compute_agent_summary\")\n );\n return result.output.trim();\n }\n\n /**\n * Returns a full header of the agent's status, summary, and current time.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @returns The full header as a string.\n */\n getFullHeader(\n config: {\n now?: Date;\n forceRefresh?: boolean;\n } = {}\n ): string {\n const { now = new Date(), forceRefresh = false } = config;\n // return a full header of the agent's status, summary, and current time.\n const summary = this.getSummary({ now, forceRefresh });\n const currentTimeString = now.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n return `${summary}\\nIt is ${currentTimeString}.\\n${this.name}'s status: ${this.status}`;\n }\n\n /**\n * Adds a memory to the agent's long-term memory.\n * @param memoryContent The content of the memory to add.\n * @param now Optional current date.\n * @param metadata Optional metadata for the memory.\n * @param callbacks Optional Callbacks instance.\n * @returns The result of adding the memory to the agent's long-term memory.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.longTermMemory.addMemory(\n memoryContent,\n now,\n metadata,\n callbacks\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,kBAAb,cAAqCA,aAAAA,UAAU;CAC7C,OAAO,UAAU;AACf,SAAO;;CAIT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,wBAAgC;CAEhC;CAKA,aAAqB;AACnB,SAAO;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GAAG,KAAK,cAAc,SAAS,IAAI,IAClD;AAED,MACE,CAAC,KAAK,WACN,gBAAgB,KAAK,yBACrB,cACA;AACA,QAAK,UAAU,MAAM,KAAK,oBAAoB,WAAW;AACzD,QAAK,gBAAgB;;EAGvB,IAAI;AACJ,MAAI,KAAK,IACP,OAAM,KAAK;MAEX,OAAM;AAGR,SAAO,SAAS,KAAK,KAAK,SAAS,IAAI;iBAC1B,KAAK,OAAO;EAC3B,KAAK;;;;;;;;CASL,MAAM,oBACJ,YACiB;EACjB,MAAM,SAASA,wBAAAA,eAAe,aAC5B,+JAMD;AASD,UAPe,MAAM,KAAK,MAAM,OAAO,CAAC,KACtC;GACE,MAAM,KAAK;GACX,SAAS,CAAC,GAAG,KAAK,KAAK,yBAAyB;GACjD,EACD,YAAY,SAAS,wBAAwB,CAC9C,EACa,OAAO,MAAM;;;;;;;CAQ7B,cACE,SAGI,EAAE,EACE;EACR,MAAM,EAAE,sBAAM,IAAI,MAAM,EAAE,eAAe,UAAU;AAWnD,SAAO,GATS,KAAK,WAAW;GAAE;GAAK;GAAc,CAAC,CASpC,UARQ,IAAI,eAAe,SAAS;GACpD,OAAO;GACP,KAAK;GACL,MAAM;GACN,MAAM;GACN,QAAQ;GACR,QAAQ;GACT,CAAC,CAC4C,KAAK,KAAK,KAAK,aAAa,KAAK;;;;;;;;;;CAWjF,MAAM,UACJ,eACA,KACA,UACA,WACA;AACA,SAAO,KAAK,eAAe,UACzB,eACA,KACA,UACA,UACD"}
|
|
1
|
+
{"version":3,"file":"generative_agent.cjs","names":["BaseChain","LLMChain","PromptTemplate"],"sources":["../../../src/experimental/generative_agents/generative_agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { GenerativeAgentMemory } from \"./generative_agent_memory.js\";\nimport { BaseChain } from \"../../chains/base.js\";\n\n/**\n * Configuration for the GenerativeAgent class. Defines the character's\n * name, optional age, permanent traits, status, verbosity, and summary\n * refresh seconds.\n */\nexport type GenerativeAgentConfig = {\n name: string;\n age?: number;\n traits: string;\n status: string;\n verbose?: boolean;\n summaryRefreshSeconds?: number;\n // dailySummaries?: string[];\n};\n\n/**\n * Implementation of a generative agent that can learn and form new memories over\n * time. It extends the BaseChain class, which is a generic\n * sequence of calls to components, including other chains.\n * @example\n * ```typescript\n * const tommie: GenerativeAgent = new GenerativeAgent(\n * new OpenAI({ temperature: 0.9, maxTokens: 1500 }),\n * new GenerativeAgentMemory(\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * new TimeWeightedVectorStoreRetriever({\n * vectorStore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * }),\n * { reflectionThreshold: 8 },\n * ),\n * {\n * name: \"Tommie\",\n * age: 25,\n * traits: \"anxious, likes design, talkative\",\n * status: \"looking for a job\",\n * },\n * );\n *\n * await tommie.addMemory(\n * \"Tommie remembers his dog, Bruno, from when he was a kid\",\n * new Date(),\n * );\n * const summary = await tommie.getSummary({ forceRefresh: true });\n * const response = await tommie.generateDialogueResponse(\n * \"USER says Hello Tommie, how are you today?\",\n * );\n * ```\n */\nexport class GenerativeAgent extends BaseChain {\n static lc_name() {\n return \"GenerativeAgent\";\n }\n\n // a character with memory and innate characterisitics\n name: string; // the character's name\n\n age?: number; // the optional age of the character\n\n traits: string; // permanent traits to ascribe to the character\n\n status: string; // the traits of the character you wish not to change\n\n longTermMemory: GenerativeAgentMemory;\n\n llm: BaseLanguageModelInterface; // the underlying language model\n\n verbose: boolean; // false\n\n private summary: string; // stateful self-summary generated via reflection on the character's memory.\n\n private summaryRefreshSeconds = 3600;\n\n private lastRefreshed: Date; // the last time the character's summary was regenerated\n\n // TODO: Add support for daily summaries\n // private dailySummaries: string[] = []; // summary of the events in the plan that the agent took.\n\n _chainType(): string {\n return \"generative_agent_executor\";\n }\n\n get inputKeys(): string[] {\n return [\"observation\", \"suffix\", \"now\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\", \"continue_dialogue\"];\n }\n\n constructor(\n llm: BaseLanguageModelInterface,\n longTermMemory: GenerativeAgentMemory,\n config: GenerativeAgentConfig\n ) {\n super();\n this.llm = llm;\n this.longTermMemory = longTermMemory;\n this.name = config.name;\n this.age = config.age;\n this.traits = config.traits;\n this.status = config.status;\n this.verbose = config.verbose ?? this.verbose;\n this.summary = \"\";\n this.summaryRefreshSeconds =\n config.summaryRefreshSeconds ?? this.summaryRefreshSeconds;\n this.lastRefreshed = new Date();\n // this.dailySummaries = config.dailySummaries ?? this.dailySummaries;\n }\n\n // LLM methods\n /**\n * Parses a newline-separated string into a list of strings.\n * @param text The string to parse.\n * @returns An array of strings parsed from the input text.\n */\n parseList(text: string): string[] {\n // parse a newline-separated string into a list of strings\n const lines: string[] = text.trim().split(\"\\n\");\n const result: string[] = lines.map((line: string) =>\n line.replace(/^\\s*\\d+\\.\\s*/, \"\").trim()\n );\n return result;\n }\n\n /**\n * Creates a new LLMChain with the given prompt and the agent's language\n * model, verbosity, output key, and memory.\n * @param prompt The prompt to use for the LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\", // new\n memory: this.longTermMemory,\n });\n return chain;\n }\n\n /**\n * Extracts the observed entity from the given observation.\n * @param observation The observation to extract the entity from.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted entity as a string.\n */\n async getEntityFromObservations(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the observed entity in the following observation? {observation}\" +\n \"\\nEntity=\"\n );\n\n const result = await this.chain(prompt).call(\n {\n observation,\n },\n runManager?.getChild(\"entity_extractor\")\n );\n\n return result.output;\n }\n\n /**\n * Extracts the action of the given entity from the given observation.\n * @param observation The observation to extract the action from.\n * @param entityName The name of the entity to extract the action for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted action as a string.\n */\n async getEntityAction(\n observation: string,\n entityName: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the {entity} doing in the following observation? {observation}\" +\n \"\\nThe {entity} is\"\n );\n\n const result = await this.chain(prompt).call(\n {\n entity: entityName,\n observation,\n },\n runManager?.getChild(\"entity_action_extractor\")\n );\n const trimmedResult = result.output.trim();\n return trimmedResult;\n }\n\n /**\n * Summarizes memories that are most relevant to an observation.\n * @param observation The observation to summarize related memories for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The summarized memories as a string.\n */\n async summarizeRelatedMemories(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n // summarize memories that are most relevant to an observation\n const prompt = PromptTemplate.fromTemplate(\n `\n{q1}?\nContext from memory:\n{relevant_memories}\nRelevant context:`\n );\n const entityName = await this.getEntityFromObservations(\n observation,\n runManager\n );\n const entityAction = await this.getEntityAction(\n observation,\n entityName,\n runManager\n );\n const q1 = `What is the relationship between ${this.name} and ${entityName}`;\n const q2 = `${entityName} is ${entityAction}`;\n const response = await this.chain(prompt).call(\n {\n q1,\n queries: [q1, q2],\n },\n runManager?.getChild(\"entity_relationships\")\n );\n\n return response.output.trim(); // added output\n }\n\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const { observation, suffix, now } = values;\n // react to a given observation or dialogue act\n const prompt = PromptTemplate.fromTemplate(\n `{agent_summary_description}` +\n `\\nIt is {current_time}.` +\n `\\n{agent_name}'s status: {agent_status}` +\n `\\nSummary of relevant context from {agent_name}'s memory:` +\n \"\\n{relevant_memories}\" +\n `\\nMost recent observations: {most_recent_memories}` +\n `\\nObservation: {observation}` +\n `\\n\\n${suffix}`\n );\n\n const agentSummaryDescription = await this.getSummary({}, runManager); // now = now in param\n const relevantMemoriesStr = await this.summarizeRelatedMemories(\n observation,\n runManager\n );\n const currentTime = (now || new Date()).toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n const chainInputs: ChainValues = {\n agent_summary_description: agentSummaryDescription,\n current_time: currentTime,\n agent_name: this.name,\n observation,\n agent_status: this.status,\n most_recent_memories: \"\",\n };\n\n chainInputs[this.longTermMemory.getRelevantMemoriesKey()] =\n relevantMemoriesStr;\n\n const consumedTokens = await this.llm.getNumTokens(\n await prompt.format({ ...chainInputs })\n );\n\n chainInputs[this.longTermMemory.getMostRecentMemoriesTokenKey()] =\n consumedTokens;\n const response = await this.chain(prompt).call(\n chainInputs,\n runManager?.getChild(\"reaction_from_summary\")\n );\n\n const rawOutput = response.output;\n let output = rawOutput;\n let continue_dialogue = false;\n\n if (rawOutput.includes(\"REACT:\")) {\n const reaction = this._cleanResponse(rawOutput.split(\"REACT:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and reacted by ${reaction}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${reaction}`;\n continue_dialogue = false;\n } else if (rawOutput.includes(\"SAY:\")) {\n const saidValue = this._cleanResponse(rawOutput.split(\"SAY:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and said ${saidValue}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${saidValue}`;\n continue_dialogue = true;\n } else if (rawOutput.includes(\"GOODBYE:\")) {\n const farewell = this._cleanResponse(\n rawOutput.split(\"GOODBYE:\").pop() ?? \"\"\n );\n await this.addMemory(\n `${this.name} observed ${observation} and said ${farewell}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${farewell}`;\n continue_dialogue = false;\n }\n\n return { output, continue_dialogue };\n }\n\n private _cleanResponse(text: string | undefined): string {\n if (text === undefined) {\n return \"\";\n }\n const regex = new RegExp(`^${this.name} `);\n return text.replace(regex, \"\").trim();\n }\n\n /**\n * Generates a reaction to the given observation.\n * @param observation The observation to generate a reaction for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateReaction(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate: string =\n `Should {agent_name} react to the observation, and if so,` +\n ` what would be an appropriate reaction? Respond in one line.` +\n ` If the action is to engage in dialogue, write:\\nSAY: \"what to say\"` +\n ` \\notherwise, write:\\nREACT: {agent_name}'s reaction (if anything).` +\n ` \\nEither do nothing, react, or say something but not both.\\n\\n`;\n\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n /**\n * Generates a dialogue response to the given observation.\n * @param observation The observation to generate a dialogue response for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateDialogueResponse(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate = `What would ${this.name} say? To end the conversation, write: GOODBYE: \"what to say\". Otherwise to continue the conversation, write: SAY: \"what to say next\"\\n\\n`;\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n // Agent stateful' summary methods\n // Each dialog or response prompt includes a header\n // summarizing the agent's self-description. This is\n // updated periodically through probing it's memories\n /**\n * Gets the agent's summary, which includes the agent's name, age, traits,\n * and a summary of the agent's core characteristics. The summary is\n * updated periodically through probing the agent's memories.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The agent's summary as a string.\n */\n async getSummary(\n config?: {\n now?: Date;\n forceRefresh?: boolean;\n },\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const { now = new Date(), forceRefresh = false } = config ?? {};\n\n const sinceRefresh = Math.floor(\n (now.getTime() - this.lastRefreshed.getTime()) / 1000\n );\n\n if (\n !this.summary ||\n sinceRefresh >= this.summaryRefreshSeconds ||\n forceRefresh\n ) {\n this.summary = await this.computeAgentSummary(runManager);\n this.lastRefreshed = now;\n }\n\n let age;\n if (this.age) {\n age = this.age;\n } else {\n age = \"N/A\";\n }\n\n return `Name: ${this.name} (age: ${age})\nInnate traits: ${this.traits}\n${this.summary}`;\n }\n\n /**\n * Computes the agent's summary by summarizing the agent's core\n * characteristics given the agent's relevant memories.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The computed summary as a string.\n */\n async computeAgentSummary(\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"How would you summarize {name}'s core characteristics given the following statements:\\n\" +\n \"----------\" +\n \"{relevant_memories}\" +\n \"----------\" +\n \"Do not embellish.\" +\n \"\\n\\nSummary: \"\n );\n // the agent seeks to think about their core characterisitics\n const result = await this.chain(prompt).call(\n {\n name: this.name,\n queries: [`${this.name}'s core characteristics`],\n },\n runManager?.getChild(\"compute_agent_summary\")\n );\n return result.output.trim();\n }\n\n /**\n * Returns a full header of the agent's status, summary, and current time.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @returns The full header as a string.\n */\n getFullHeader(\n config: {\n now?: Date;\n forceRefresh?: boolean;\n } = {}\n ): string {\n const { now = new Date(), forceRefresh = false } = config;\n // return a full header of the agent's status, summary, and current time.\n const summary = this.getSummary({ now, forceRefresh });\n const currentTimeString = now.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n return `${summary}\\nIt is ${currentTimeString}.\\n${this.name}'s status: ${this.status}`;\n }\n\n /**\n * Adds a memory to the agent's long-term memory.\n * @param memoryContent The content of the memory to add.\n * @param now Optional current date.\n * @param metadata Optional metadata for the memory.\n * @param callbacks Optional Callbacks instance.\n * @returns The result of adding the memory to the agent's long-term memory.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.longTermMemory.addMemory(\n memoryContent,\n now,\n metadata,\n callbacks\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,kBAAb,cAAqCA,aAAAA,UAAU;CAC7C,OAAO,UAAU;AACf,SAAO;;CAIT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,wBAAgC;CAEhC;CAKA,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAe;GAAU;GAAM;;CAGzC,IAAI,aAAuB;AACzB,SAAO,CAAC,UAAU,oBAAoB;;CAGxC,YACE,KACA,gBACA,QACA;AACA,SAAO;AACP,OAAK,MAAM;AACX,OAAK,iBAAiB;AACtB,OAAK,OAAO,OAAO;AACnB,OAAK,MAAM,OAAO;AAClB,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS,OAAO;AACrB,OAAK,UAAU,OAAO,WAAW,KAAK;AACtC,OAAK,UAAU;AACf,OAAK,wBACH,OAAO,yBAAyB,KAAK;AACvC,OAAK,gCAAgB,IAAI,MAAM;;;;;;;CAUjC,UAAU,MAAwB;AAMhC,SAJwB,KAAK,MAAM,CAAC,MAAM,KAAK,CAChB,KAAK,SAClC,KAAK,QAAQ,gBAAgB,GAAG,CAAC,MAAM,CACxC;;;;;;;;CAUH,MAAM,QAAkC;AAQtC,SAPc,IAAIC,kBAAAA,SAAS;GACzB,KAAK,KAAK;GACV;GACA,SAAS,KAAK;GACd,WAAW;GACX,QAAQ,KAAK;GACd,CAAC;;;;;;;;CAUJ,MAAM,0BACJ,aACA,YACiB;EACjB,MAAM,SAASC,wBAAAA,eAAe,aAC5B,mFAED;AASD,UAPe,MAAM,KAAK,MAAM,OAAO,CAAC,KACtC,EACE,aACD,EACD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;;;;CAWjF,MAAM,UACJ,eACA,KACA,UACA,WACA;AACA,SAAO,KAAK,eAAe,UACzB,eACA,KACA,UACA,UACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generative_agent.js","names":[],"sources":["../../../src/experimental/generative_agents/generative_agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { GenerativeAgentMemory } from \"./generative_agent_memory.js\";\nimport { BaseChain } from \"../../chains/base.js\";\n\n/**\n * Configuration for the GenerativeAgent class. Defines the character's\n * name, optional age, permanent traits, status, verbosity, and summary\n * refresh seconds.\n */\nexport type GenerativeAgentConfig = {\n name: string;\n age?: number;\n traits: string;\n status: string;\n verbose?: boolean;\n summaryRefreshSeconds?: number;\n // dailySummaries?: string[];\n};\n\n/**\n * Implementation of a generative agent that can learn and form new memories over\n * time. It extends the BaseChain class, which is a generic\n * sequence of calls to components, including other chains.\n * @example\n * ```typescript\n * const tommie: GenerativeAgent = new GenerativeAgent(\n * new OpenAI({ temperature: 0.9, maxTokens: 1500 }),\n * new GenerativeAgentMemory(\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * new TimeWeightedVectorStoreRetriever({\n * vectorStore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * }),\n * { reflectionThreshold: 8 },\n * ),\n * {\n * name: \"Tommie\",\n * age: 25,\n * traits: \"anxious, likes design, talkative\",\n * status: \"looking for a job\",\n * },\n * );\n *\n * await tommie.addMemory(\n * \"Tommie remembers his dog, Bruno, from when he was a kid\",\n * new Date(),\n * );\n * const summary = await tommie.getSummary({ forceRefresh: true });\n * const response = await tommie.generateDialogueResponse(\n * \"USER says Hello Tommie, how are you today?\",\n * );\n * ```\n */\nexport class GenerativeAgent extends BaseChain {\n static lc_name() {\n return \"GenerativeAgent\";\n }\n\n // a character with memory and innate characterisitics\n name: string; // the character's name\n\n age?: number; // the optional age of the character\n\n traits: string; // permanent traits to ascribe to the character\n\n status: string; // the traits of the character you wish not to change\n\n longTermMemory: GenerativeAgentMemory;\n\n llm: BaseLanguageModelInterface; // the underlying language model\n\n verbose: boolean; // false\n\n private summary: string; // stateful self-summary generated via reflection on the character's memory.\n\n private summaryRefreshSeconds = 3600;\n\n private lastRefreshed: Date; // the last time the character's summary was regenerated\n\n // TODO: Add support for daily summaries\n // private dailySummaries: string[] = []; // summary of the events in the plan that the agent took.\n\n _chainType(): string {\n return \"generative_agent_executor\";\n }\n\n get inputKeys(): string[] {\n return [\"observation\", \"suffix\", \"now\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\", \"continue_dialogue\"];\n }\n\n constructor(\n llm: BaseLanguageModelInterface,\n longTermMemory: GenerativeAgentMemory,\n config: GenerativeAgentConfig\n ) {\n super();\n this.llm = llm;\n this.longTermMemory = longTermMemory;\n this.name = config.name;\n this.age = config.age;\n this.traits = config.traits;\n this.status = config.status;\n this.verbose = config.verbose ?? this.verbose;\n this.summary = \"\";\n this.summaryRefreshSeconds =\n config.summaryRefreshSeconds ?? this.summaryRefreshSeconds;\n this.lastRefreshed = new Date();\n // this.dailySummaries = config.dailySummaries ?? this.dailySummaries;\n }\n\n // LLM methods\n /**\n * Parses a newline-separated string into a list of strings.\n * @param text The string to parse.\n * @returns An array of strings parsed from the input text.\n */\n parseList(text: string): string[] {\n // parse a newline-seperated string into a list of strings\n const lines: string[] = text.trim().split(\"\\n\");\n const result: string[] = lines.map((line: string) =>\n line.replace(/^\\s*\\d+\\.\\s*/, \"\").trim()\n );\n return result;\n }\n\n /**\n * Creates a new LLMChain with the given prompt and the agent's language\n * model, verbosity, output key, and memory.\n * @param prompt The prompt to use for the LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\", // new\n memory: this.longTermMemory,\n });\n return chain;\n }\n\n /**\n * Extracts the observed entity from the given observation.\n * @param observation The observation to extract the entity from.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted entity as a string.\n */\n async getEntityFromObservations(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the observed entity in the following observation? {observation}\" +\n \"\\nEntity=\"\n );\n\n const result = await this.chain(prompt).call(\n {\n observation,\n },\n runManager?.getChild(\"entity_extractor\")\n );\n\n return result.output;\n }\n\n /**\n * Extracts the action of the given entity from the given observation.\n * @param observation The observation to extract the action from.\n * @param entityName The name of the entity to extract the action for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted action as a string.\n */\n async getEntityAction(\n observation: string,\n entityName: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the {entity} doing in the following observation? {observation}\" +\n \"\\nThe {entity} is\"\n );\n\n const result = await this.chain(prompt).call(\n {\n entity: entityName,\n observation,\n },\n runManager?.getChild(\"entity_action_extractor\")\n );\n const trimmedResult = result.output.trim();\n return trimmedResult;\n }\n\n /**\n * Summarizes memories that are most relevant to an observation.\n * @param observation The observation to summarize related memories for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The summarized memories as a string.\n */\n async summarizeRelatedMemories(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n // summarize memories that are most relevant to an observation\n const prompt = PromptTemplate.fromTemplate(\n `\n{q1}?\nContext from memory:\n{relevant_memories}\nRelevant context:`\n );\n const entityName = await this.getEntityFromObservations(\n observation,\n runManager\n );\n const entityAction = await this.getEntityAction(\n observation,\n entityName,\n runManager\n );\n const q1 = `What is the relationship between ${this.name} and ${entityName}`;\n const q2 = `${entityName} is ${entityAction}`;\n const response = await this.chain(prompt).call(\n {\n q1,\n queries: [q1, q2],\n },\n runManager?.getChild(\"entity_relationships\")\n );\n\n return response.output.trim(); // added output\n }\n\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const { observation, suffix, now } = values;\n // react to a given observation or dialogue act\n const prompt = PromptTemplate.fromTemplate(\n `{agent_summary_description}` +\n `\\nIt is {current_time}.` +\n `\\n{agent_name}'s status: {agent_status}` +\n `\\nSummary of relevant context from {agent_name}'s memory:` +\n \"\\n{relevant_memories}\" +\n `\\nMost recent observations: {most_recent_memories}` +\n `\\nObservation: {observation}` +\n `\\n\\n${suffix}`\n );\n\n const agentSummaryDescription = await this.getSummary({}, runManager); // now = now in param\n const relevantMemoriesStr = await this.summarizeRelatedMemories(\n observation,\n runManager\n );\n const currentTime = (now || new Date()).toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n const chainInputs: ChainValues = {\n agent_summary_description: agentSummaryDescription,\n current_time: currentTime,\n agent_name: this.name,\n observation,\n agent_status: this.status,\n most_recent_memories: \"\",\n };\n\n chainInputs[this.longTermMemory.getRelevantMemoriesKey()] =\n relevantMemoriesStr;\n\n const consumedTokens = await this.llm.getNumTokens(\n await prompt.format({ ...chainInputs })\n );\n\n chainInputs[this.longTermMemory.getMostRecentMemoriesTokenKey()] =\n consumedTokens;\n const response = await this.chain(prompt).call(\n chainInputs,\n runManager?.getChild(\"reaction_from_summary\")\n );\n\n const rawOutput = response.output;\n let output = rawOutput;\n let continue_dialogue = false;\n\n if (rawOutput.includes(\"REACT:\")) {\n const reaction = this._cleanResponse(rawOutput.split(\"REACT:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and reacted by ${reaction}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${reaction}`;\n continue_dialogue = false;\n } else if (rawOutput.includes(\"SAY:\")) {\n const saidValue = this._cleanResponse(rawOutput.split(\"SAY:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and said ${saidValue}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${saidValue}`;\n continue_dialogue = true;\n } else if (rawOutput.includes(\"GOODBYE:\")) {\n const farewell = this._cleanResponse(\n rawOutput.split(\"GOODBYE:\").pop() ?? \"\"\n );\n await this.addMemory(\n `${this.name} observed ${observation} and said ${farewell}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${farewell}`;\n continue_dialogue = false;\n }\n\n return { output, continue_dialogue };\n }\n\n private _cleanResponse(text: string | undefined): string {\n if (text === undefined) {\n return \"\";\n }\n const regex = new RegExp(`^${this.name} `);\n return text.replace(regex, \"\").trim();\n }\n\n /**\n * Generates a reaction to the given observation.\n * @param observation The observation to generate a reaction for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateReaction(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate: string =\n `Should {agent_name} react to the observation, and if so,` +\n ` what would be an appropriate reaction? Respond in one line.` +\n ` If the action is to engage in dialogue, write:\\nSAY: \"what to say\"` +\n ` \\notherwise, write:\\nREACT: {agent_name}'s reaction (if anything).` +\n ` \\nEither do nothing, react, or say something but not both.\\n\\n`;\n\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n /**\n * Generates a dialogue response to the given observation.\n * @param observation The observation to generate a dialogue response for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateDialogueResponse(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate = `What would ${this.name} say? To end the conversation, write: GOODBYE: \"what to say\". Otherwise to continue the conversation, write: SAY: \"what to say next\"\\n\\n`;\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n // Agent stateful' summary methods\n // Each dialog or response prompt includes a header\n // summarizing the agent's self-description. This is\n // updated periodically through probing it's memories\n /**\n * Gets the agent's summary, which includes the agent's name, age, traits,\n * and a summary of the agent's core characteristics. The summary is\n * updated periodically through probing the agent's memories.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The agent's summary as a string.\n */\n async getSummary(\n config?: {\n now?: Date;\n forceRefresh?: boolean;\n },\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const { now = new Date(), forceRefresh = false } = config ?? {};\n\n const sinceRefresh = Math.floor(\n (now.getTime() - this.lastRefreshed.getTime()) / 1000\n );\n\n if (\n !this.summary ||\n sinceRefresh >= this.summaryRefreshSeconds ||\n forceRefresh\n ) {\n this.summary = await this.computeAgentSummary(runManager);\n this.lastRefreshed = now;\n }\n\n let age;\n if (this.age) {\n age = this.age;\n } else {\n age = \"N/A\";\n }\n\n return `Name: ${this.name} (age: ${age})\nInnate traits: ${this.traits}\n${this.summary}`;\n }\n\n /**\n * Computes the agent's summary by summarizing the agent's core\n * characteristics given the agent's relevant memories.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The computed summary as a string.\n */\n async computeAgentSummary(\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"How would you summarize {name}'s core characteristics given the following statements:\\n\" +\n \"----------\" +\n \"{relevant_memories}\" +\n \"----------\" +\n \"Do not embellish.\" +\n \"\\n\\nSummary: \"\n );\n // the agent seeks to think about their core characterisitics\n const result = await this.chain(prompt).call(\n {\n name: this.name,\n queries: [`${this.name}'s core characteristics`],\n },\n runManager?.getChild(\"compute_agent_summary\")\n );\n return result.output.trim();\n }\n\n /**\n * Returns a full header of the agent's status, summary, and current time.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @returns The full header as a string.\n */\n getFullHeader(\n config: {\n now?: Date;\n forceRefresh?: boolean;\n } = {}\n ): string {\n const { now = new Date(), forceRefresh = false } = config;\n // return a full header of the agent's status, summary, and current time.\n const summary = this.getSummary({ now, forceRefresh });\n const currentTimeString = now.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n return `${summary}\\nIt is ${currentTimeString}.\\n${this.name}'s status: ${this.status}`;\n }\n\n /**\n * Adds a memory to the agent's long-term memory.\n * @param memoryContent The content of the memory to add.\n * @param now Optional current date.\n * @param metadata Optional metadata for the memory.\n * @param callbacks Optional Callbacks instance.\n * @returns The result of adding the memory to the agent's long-term memory.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.longTermMemory.addMemory(\n memoryContent,\n now,\n metadata,\n callbacks\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,OAAO,UAAU;AACf,SAAO;;CAIT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,wBAAgC;CAEhC;CAKA,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAe;GAAU;GAAM;;CAGzC,IAAI,aAAuB;AACzB,SAAO,CAAC,UAAU,oBAAoB;;CAGxC,YACE,KACA,gBACA,QACA;AACA,SAAO;AACP,OAAK,MAAM;AACX,OAAK,iBAAiB;AACtB,OAAK,OAAO,OAAO;AACnB,OAAK,MAAM,OAAO;AAClB,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS,OAAO;AACrB,OAAK,UAAU,OAAO,WAAW,KAAK;AACtC,OAAK,UAAU;AACf,OAAK,wBACH,OAAO,yBAAyB,KAAK;AACvC,OAAK,gCAAgB,IAAI,MAAM;;;;;;;CAUjC,UAAU,MAAwB;AAMhC,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SAAS,wBAAwB,CAC9C,EACa,OAAO,MAAM;;;;;;;CAQ7B,cACE,SAGI,EAAE,EACE;EACR,MAAM,EAAE,sBAAM,IAAI,MAAM,EAAE,eAAe,UAAU;AAWnD,SAAO,GATS,KAAK,WAAW;GAAE;GAAK;GAAc,CAAC,CASpC,UARQ,IAAI,eAAe,SAAS;GACpD,OAAO;GACP,KAAK;GACL,MAAM;GACN,MAAM;GACN,QAAQ;GACR,QAAQ;GACT,CAAC,CAC4C,KAAK,KAAK,KAAK,aAAa,KAAK;;;;;;;;;;CAWjF,MAAM,UACJ,eACA,KACA,UACA,WACA;AACA,SAAO,KAAK,eAAe,UACzB,eACA,KACA,UACA,UACD"}
|
|
1
|
+
{"version":3,"file":"generative_agent.js","names":[],"sources":["../../../src/experimental/generative_agents/generative_agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\nimport { GenerativeAgentMemory } from \"./generative_agent_memory.js\";\nimport { BaseChain } from \"../../chains/base.js\";\n\n/**\n * Configuration for the GenerativeAgent class. Defines the character's\n * name, optional age, permanent traits, status, verbosity, and summary\n * refresh seconds.\n */\nexport type GenerativeAgentConfig = {\n name: string;\n age?: number;\n traits: string;\n status: string;\n verbose?: boolean;\n summaryRefreshSeconds?: number;\n // dailySummaries?: string[];\n};\n\n/**\n * Implementation of a generative agent that can learn and form new memories over\n * time. It extends the BaseChain class, which is a generic\n * sequence of calls to components, including other chains.\n * @example\n * ```typescript\n * const tommie: GenerativeAgent = new GenerativeAgent(\n * new OpenAI({ temperature: 0.9, maxTokens: 1500 }),\n * new GenerativeAgentMemory(\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * new TimeWeightedVectorStoreRetriever({\n * vectorStore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * }),\n * { reflectionThreshold: 8 },\n * ),\n * {\n * name: \"Tommie\",\n * age: 25,\n * traits: \"anxious, likes design, talkative\",\n * status: \"looking for a job\",\n * },\n * );\n *\n * await tommie.addMemory(\n * \"Tommie remembers his dog, Bruno, from when he was a kid\",\n * new Date(),\n * );\n * const summary = await tommie.getSummary({ forceRefresh: true });\n * const response = await tommie.generateDialogueResponse(\n * \"USER says Hello Tommie, how are you today?\",\n * );\n * ```\n */\nexport class GenerativeAgent extends BaseChain {\n static lc_name() {\n return \"GenerativeAgent\";\n }\n\n // a character with memory and innate characterisitics\n name: string; // the character's name\n\n age?: number; // the optional age of the character\n\n traits: string; // permanent traits to ascribe to the character\n\n status: string; // the traits of the character you wish not to change\n\n longTermMemory: GenerativeAgentMemory;\n\n llm: BaseLanguageModelInterface; // the underlying language model\n\n verbose: boolean; // false\n\n private summary: string; // stateful self-summary generated via reflection on the character's memory.\n\n private summaryRefreshSeconds = 3600;\n\n private lastRefreshed: Date; // the last time the character's summary was regenerated\n\n // TODO: Add support for daily summaries\n // private dailySummaries: string[] = []; // summary of the events in the plan that the agent took.\n\n _chainType(): string {\n return \"generative_agent_executor\";\n }\n\n get inputKeys(): string[] {\n return [\"observation\", \"suffix\", \"now\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\", \"continue_dialogue\"];\n }\n\n constructor(\n llm: BaseLanguageModelInterface,\n longTermMemory: GenerativeAgentMemory,\n config: GenerativeAgentConfig\n ) {\n super();\n this.llm = llm;\n this.longTermMemory = longTermMemory;\n this.name = config.name;\n this.age = config.age;\n this.traits = config.traits;\n this.status = config.status;\n this.verbose = config.verbose ?? this.verbose;\n this.summary = \"\";\n this.summaryRefreshSeconds =\n config.summaryRefreshSeconds ?? this.summaryRefreshSeconds;\n this.lastRefreshed = new Date();\n // this.dailySummaries = config.dailySummaries ?? this.dailySummaries;\n }\n\n // LLM methods\n /**\n * Parses a newline-separated string into a list of strings.\n * @param text The string to parse.\n * @returns An array of strings parsed from the input text.\n */\n parseList(text: string): string[] {\n // parse a newline-separated string into a list of strings\n const lines: string[] = text.trim().split(\"\\n\");\n const result: string[] = lines.map((line: string) =>\n line.replace(/^\\s*\\d+\\.\\s*/, \"\").trim()\n );\n return result;\n }\n\n /**\n * Creates a new LLMChain with the given prompt and the agent's language\n * model, verbosity, output key, and memory.\n * @param prompt The prompt to use for the LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\", // new\n memory: this.longTermMemory,\n });\n return chain;\n }\n\n /**\n * Extracts the observed entity from the given observation.\n * @param observation The observation to extract the entity from.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted entity as a string.\n */\n async getEntityFromObservations(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the observed entity in the following observation? {observation}\" +\n \"\\nEntity=\"\n );\n\n const result = await this.chain(prompt).call(\n {\n observation,\n },\n runManager?.getChild(\"entity_extractor\")\n );\n\n return result.output;\n }\n\n /**\n * Extracts the action of the given entity from the given observation.\n * @param observation The observation to extract the action from.\n * @param entityName The name of the entity to extract the action for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The extracted action as a string.\n */\n async getEntityAction(\n observation: string,\n entityName: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"What is the {entity} doing in the following observation? {observation}\" +\n \"\\nThe {entity} is\"\n );\n\n const result = await this.chain(prompt).call(\n {\n entity: entityName,\n observation,\n },\n runManager?.getChild(\"entity_action_extractor\")\n );\n const trimmedResult = result.output.trim();\n return trimmedResult;\n }\n\n /**\n * Summarizes memories that are most relevant to an observation.\n * @param observation The observation to summarize related memories for.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The summarized memories as a string.\n */\n async summarizeRelatedMemories(\n observation: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n // summarize memories that are most relevant to an observation\n const prompt = PromptTemplate.fromTemplate(\n `\n{q1}?\nContext from memory:\n{relevant_memories}\nRelevant context:`\n );\n const entityName = await this.getEntityFromObservations(\n observation,\n runManager\n );\n const entityAction = await this.getEntityAction(\n observation,\n entityName,\n runManager\n );\n const q1 = `What is the relationship between ${this.name} and ${entityName}`;\n const q2 = `${entityName} is ${entityAction}`;\n const response = await this.chain(prompt).call(\n {\n q1,\n queries: [q1, q2],\n },\n runManager?.getChild(\"entity_relationships\")\n );\n\n return response.output.trim(); // added output\n }\n\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const { observation, suffix, now } = values;\n // react to a given observation or dialogue act\n const prompt = PromptTemplate.fromTemplate(\n `{agent_summary_description}` +\n `\\nIt is {current_time}.` +\n `\\n{agent_name}'s status: {agent_status}` +\n `\\nSummary of relevant context from {agent_name}'s memory:` +\n \"\\n{relevant_memories}\" +\n `\\nMost recent observations: {most_recent_memories}` +\n `\\nObservation: {observation}` +\n `\\n\\n${suffix}`\n );\n\n const agentSummaryDescription = await this.getSummary({}, runManager); // now = now in param\n const relevantMemoriesStr = await this.summarizeRelatedMemories(\n observation,\n runManager\n );\n const currentTime = (now || new Date()).toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n const chainInputs: ChainValues = {\n agent_summary_description: agentSummaryDescription,\n current_time: currentTime,\n agent_name: this.name,\n observation,\n agent_status: this.status,\n most_recent_memories: \"\",\n };\n\n chainInputs[this.longTermMemory.getRelevantMemoriesKey()] =\n relevantMemoriesStr;\n\n const consumedTokens = await this.llm.getNumTokens(\n await prompt.format({ ...chainInputs })\n );\n\n chainInputs[this.longTermMemory.getMostRecentMemoriesTokenKey()] =\n consumedTokens;\n const response = await this.chain(prompt).call(\n chainInputs,\n runManager?.getChild(\"reaction_from_summary\")\n );\n\n const rawOutput = response.output;\n let output = rawOutput;\n let continue_dialogue = false;\n\n if (rawOutput.includes(\"REACT:\")) {\n const reaction = this._cleanResponse(rawOutput.split(\"REACT:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and reacted by ${reaction}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${reaction}`;\n continue_dialogue = false;\n } else if (rawOutput.includes(\"SAY:\")) {\n const saidValue = this._cleanResponse(rawOutput.split(\"SAY:\").pop());\n await this.addMemory(\n `${this.name} observed ${observation} and said ${saidValue}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${saidValue}`;\n continue_dialogue = true;\n } else if (rawOutput.includes(\"GOODBYE:\")) {\n const farewell = this._cleanResponse(\n rawOutput.split(\"GOODBYE:\").pop() ?? \"\"\n );\n await this.addMemory(\n `${this.name} observed ${observation} and said ${farewell}`,\n now,\n {},\n runManager?.getChild(\"memory\")\n );\n output = `${this.name} said ${farewell}`;\n continue_dialogue = false;\n }\n\n return { output, continue_dialogue };\n }\n\n private _cleanResponse(text: string | undefined): string {\n if (text === undefined) {\n return \"\";\n }\n const regex = new RegExp(`^${this.name} `);\n return text.replace(regex, \"\").trim();\n }\n\n /**\n * Generates a reaction to the given observation.\n * @param observation The observation to generate a reaction for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateReaction(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate: string =\n `Should {agent_name} react to the observation, and if so,` +\n ` what would be an appropriate reaction? Respond in one line.` +\n ` If the action is to engage in dialogue, write:\\nSAY: \"what to say\"` +\n ` \\notherwise, write:\\nREACT: {agent_name}'s reaction (if anything).` +\n ` \\nEither do nothing, react, or say something but not both.\\n\\n`;\n\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n /**\n * Generates a dialogue response to the given observation.\n * @param observation The observation to generate a dialogue response for.\n * @param now Optional current date.\n * @returns A boolean indicating whether to continue the dialogue and the output string.\n */\n async generateDialogueResponse(\n observation: string,\n now?: Date\n ): Promise<[boolean, string]> {\n const callToActionTemplate = `What would ${this.name} say? To end the conversation, write: GOODBYE: \"what to say\". Otherwise to continue the conversation, write: SAY: \"what to say next\"\\n\\n`;\n const { output, continue_dialogue } = await this.call({\n observation,\n suffix: callToActionTemplate,\n now,\n });\n return [continue_dialogue, output];\n }\n\n // Agent stateful' summary methods\n // Each dialog or response prompt includes a header\n // summarizing the agent's self-description. This is\n // updated periodically through probing it's memories\n /**\n * Gets the agent's summary, which includes the agent's name, age, traits,\n * and a summary of the agent's core characteristics. The summary is\n * updated periodically through probing the agent's memories.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The agent's summary as a string.\n */\n async getSummary(\n config?: {\n now?: Date;\n forceRefresh?: boolean;\n },\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const { now = new Date(), forceRefresh = false } = config ?? {};\n\n const sinceRefresh = Math.floor(\n (now.getTime() - this.lastRefreshed.getTime()) / 1000\n );\n\n if (\n !this.summary ||\n sinceRefresh >= this.summaryRefreshSeconds ||\n forceRefresh\n ) {\n this.summary = await this.computeAgentSummary(runManager);\n this.lastRefreshed = now;\n }\n\n let age;\n if (this.age) {\n age = this.age;\n } else {\n age = \"N/A\";\n }\n\n return `Name: ${this.name} (age: ${age})\nInnate traits: ${this.traits}\n${this.summary}`;\n }\n\n /**\n * Computes the agent's summary by summarizing the agent's core\n * characteristics given the agent's relevant memories.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns The computed summary as a string.\n */\n async computeAgentSummary(\n runManager?: CallbackManagerForChainRun\n ): Promise<string> {\n const prompt = PromptTemplate.fromTemplate(\n \"How would you summarize {name}'s core characteristics given the following statements:\\n\" +\n \"----------\" +\n \"{relevant_memories}\" +\n \"----------\" +\n \"Do not embellish.\" +\n \"\\n\\nSummary: \"\n );\n // the agent seeks to think about their core characterisitics\n const result = await this.chain(prompt).call(\n {\n name: this.name,\n queries: [`${this.name}'s core characteristics`],\n },\n runManager?.getChild(\"compute_agent_summary\")\n );\n return result.output.trim();\n }\n\n /**\n * Returns a full header of the agent's status, summary, and current time.\n * @param config Optional configuration object with current date and a boolean to force refresh.\n * @returns The full header as a string.\n */\n getFullHeader(\n config: {\n now?: Date;\n forceRefresh?: boolean;\n } = {}\n ): string {\n const { now = new Date(), forceRefresh = false } = config;\n // return a full header of the agent's status, summary, and current time.\n const summary = this.getSummary({ now, forceRefresh });\n const currentTimeString = now.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n return `${summary}\\nIt is ${currentTimeString}.\\n${this.name}'s status: ${this.status}`;\n }\n\n /**\n * Adds a memory to the agent's long-term memory.\n * @param memoryContent The content of the memory to add.\n * @param now Optional current date.\n * @param metadata Optional metadata for the memory.\n * @param callbacks Optional Callbacks instance.\n * @returns The result of adding the memory to the agent's long-term memory.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.longTermMemory.addMemory(\n memoryContent,\n now,\n metadata,\n callbacks\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,OAAO,UAAU;AACf,SAAO;;CAIT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,wBAAgC;CAEhC;CAKA,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAe;GAAU;GAAM;;CAGzC,IAAI,aAAuB;AACzB,SAAO,CAAC,UAAU,oBAAoB;;CAGxC,YACE,KACA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,MAAI,KAAK,IACP,OAAM,KAAK;MAEX,OAAM;AAGR,SAAO,SAAS,KAAK,KAAK,SAAS,IAAI;iBAC1B,KAAK,OAAO;EAC3B,KAAK;;;;;;;;CASL,MAAM,oBACJ,YACiB;EACjB,MAAM,SAAS,eAAe,aAC5B,+JAMD;AASD,UAPe,MAAM,KAAK,MAAM,OAAO,CAAC,KACtC;GACE,MAAM,KAAK;GACX,SAAS,CAAC,GAAG,KAAK,KAAK,yBAAyB;GACjD,EACD,YAAY,SAAS,wBAAwB,CAC9C,EACa,OAAO,MAAM;;;;;;;CAQ7B,cACE,SAGI,EAAE,EACE;EACR,MAAM,EAAE,sBAAM,IAAI,MAAM,EAAE,eAAe,UAAU;AAWnD,SAAO,GATS,KAAK,WAAW;GAAE;GAAK;GAAc,CAAC,CASpC,UARQ,IAAI,eAAe,SAAS;GACpD,OAAO;GACP,KAAK;GACL,MAAM;GACN,MAAM;GACN,QAAQ;GACR,QAAQ;GACT,CAAC,CAC4C,KAAK,KAAK,KAAK,aAAa,KAAK;;;;;;;;;;CAWjF,MAAM,UACJ,eACA,KACA,UACA,WACA;AACA,SAAO,KAAK,eAAe,UACzB,eACA,KACA,UACA,UACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generative_agent_memory.cjs","names":["BaseChain","LLMChain","Document","PromptTemplate","BaseMemory"],"sources":["../../../src/experimental/generative_agents/generative_agent_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseMemory, InputValues, OutputValues } from \"@langchain/core/memory\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { TimeWeightedVectorStoreRetriever } from \"../../retrievers/time_weighted.js\";\nimport { BaseChain } from \"../../chains/base.js\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nexport type GenerativeAgentMemoryConfig = {\n reflectionThreshold?: number;\n importanceWeight?: number;\n verbose?: boolean;\n maxTokensLimit?: number;\n};\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseChain` class and has methods for adding observations\n * or memories to the agent's memory, scoring the importance of a memory,\n * reflecting on recent events to add synthesized memories, and generating\n * insights on a topic of reflection based on pertinent memories.\n */\nclass GenerativeAgentMemoryChain extends BaseChain {\n static lc_name() {\n return \"GenerativeAgentMemoryChain\";\n }\n\n reflecting = false;\n\n reflectionThreshold?: number;\n\n importanceWeight = 0.15;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n llm: BaseLanguageModelInterface;\n\n verbose = false;\n\n private aggregateImportance = 0.0;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config: Omit<GenerativeAgentMemoryConfig, \"maxTokensLimit\">\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.reflectionThreshold = config.reflectionThreshold;\n this.importanceWeight = config.importanceWeight ?? this.importanceWeight;\n this.verbose = config.verbose ?? this.verbose;\n }\n\n _chainType(): string {\n return \"generative_agent_memory\";\n }\n\n get inputKeys(): string[] {\n return [\"memory_content\", \"now\", \"memory_metadata\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\"];\n }\n\n /**\n * Method that creates a new LLMChain with the given prompt.\n * @param prompt The PromptTemplate to use for the new LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\",\n });\n return chain;\n }\n\n async _call(values: ChainValues, runManager?: CallbackManagerForChainRun) {\n const { memory_content: memoryContent, now } = values;\n // add an observation or memory to the agent's memory\n const importanceScore = await this.scoreMemoryImportance(\n memoryContent,\n runManager\n );\n this.aggregateImportance += importanceScore;\n const document = new Document({\n pageContent: memoryContent,\n metadata: {\n importance: importanceScore,\n ...values.memory_metadata,\n },\n });\n await this.memoryRetriever.addDocuments([document]);\n // after an agent has processed a certain amount of memories (as measured by aggregate importance),\n // it is time to pause and reflect on recent events to add more synthesized memories to the agent's\n // memory stream.\n if (\n this.reflectionThreshold !== undefined &&\n this.aggregateImportance > this.reflectionThreshold &&\n !this.reflecting\n ) {\n console.log(\"Reflecting on current memories...\");\n this.reflecting = true;\n await this.pauseToReflect(now, runManager);\n this.aggregateImportance = 0.0;\n this.reflecting = false;\n }\n return { output: importanceScore };\n }\n\n /**\n * Method that pauses the agent to reflect on recent events and generate\n * new insights.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for the reflection.\n * @returns An array of new insights as strings.\n */\n async pauseToReflect(\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n if (this.verbose) {\n console.log(\"Pausing to reflect...\");\n }\n const newInsights: string[] = [];\n const topics = await this.getTopicsOfReflection(50, runManager);\n for (const topic of topics) {\n const insights = await this.getInsightsOnTopic(topic, now, runManager);\n for (const insight of insights) {\n // add memory\n await this.call(\n {\n memory_content: insight,\n now,\n memory_metadata: {\n source: \"reflection_insight\",\n },\n },\n runManager?.getChild(\"reflection_insight_memory\")\n );\n }\n newInsights.push(...insights);\n }\n return newInsights;\n }\n\n /**\n * Method that scores the importance of a given memory.\n * @param memoryContent The content of the memory to score.\n * @param runManager The CallbackManagerForChainRun to use for scoring.\n * @returns The importance score of the memory as a number.\n */\n async scoreMemoryImportance(\n memoryContent: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<number> {\n // score the absolute importance of a given memory\n const prompt = PromptTemplate.fromTemplate(\n \"On the scale of 1 to 10, where 1 is purely mundane\" +\n \" (e.g., brushing teeth, making bed) and 10 is\" +\n \" extremely poignant (e.g., a break up, college\" +\n \" acceptance), rate the likely poignancy of the\" +\n \" following piece of memory. Respond with a single integer.\" +\n \"\\nMemory: {memory_content}\" +\n \"\\nRating: \"\n );\n const score = await this.chain(prompt).run(\n memoryContent,\n runManager?.getChild(\"determine_importance\")\n );\n\n const strippedScore = score.trim();\n\n if (this.verbose) {\n console.log(\"Importance score:\", strippedScore);\n }\n const match = strippedScore.match(/^\\D*(\\d+)/);\n if (match) {\n const capturedNumber = parseFloat(match[1]);\n const result = (capturedNumber / 10) * this.importanceWeight;\n return result;\n } else {\n return 0.0;\n }\n }\n\n /**\n * Method that retrieves the topics of reflection based on the last K\n * memories.\n * @param lastK The number of most recent memories to consider for generating topics.\n * @param runManager The CallbackManagerForChainRun to use for retrieving topics.\n * @returns An array of topics of reflection as strings.\n */\n async getTopicsOfReflection(\n lastK: number,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n const prompt = PromptTemplate.fromTemplate(\n \"{observations}\\n\\n\" +\n \"Given only the information above, what are the 3 most salient\" +\n \" high-level questions we can answer about the subjects in\" +\n \" the statements? Provide each question on a new line.\\n\\n\"\n );\n\n const observations = this.memoryRetriever.getMemoryStream().slice(-lastK);\n const observationStr = observations\n .map((o: { pageContent: string }) => o.pageContent)\n .join(\"\\n\");\n const result = await this.chain(prompt).run(\n observationStr,\n runManager?.getChild(\"reflection_topics\")\n );\n return GenerativeAgentMemoryChain.parseList(result);\n }\n\n /**\n * Method that generates insights on a given topic of reflection based on\n * pertinent memories.\n * @param topic The topic of reflection.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for generating insights.\n * @returns An array of insights as strings.\n */\n async getInsightsOnTopic(\n topic: string,\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n // generate insights on a topic of reflection, based on pertinent memories\n const prompt = PromptTemplate.fromTemplate(\n \"Statements about {topic}\\n\" +\n \"{related_statements}\\n\\n\" +\n \"What 5 high-level insights can you infer from the above statements?\" +\n \" (example format: insight (because of 1, 5, 3))\"\n );\n\n const relatedMemories = await this.fetchMemories(topic, now, runManager);\n const relatedStatements: string = relatedMemories\n .map((memory, index) => `${index + 1}. ${memory.pageContent}`)\n .join(\"\\n\");\n const result = await this.chain(prompt).call(\n {\n topic,\n related_statements: relatedStatements,\n },\n runManager?.getChild(\"reflection_insights\")\n );\n return GenerativeAgentMemoryChain.parseList(result.output); // added output\n }\n\n /**\n * Method that parses a newline-separated string into a list of strings.\n * @param text The newline-separated string to parse.\n * @returns An array of strings.\n */\n static parseList(text: string): string[] {\n // parse a newine seperates string into a list of strings\n return text.split(\"\\n\").map((s) => s.trim());\n }\n\n // TODO: Mock \"now\" to simulate different times\n /**\n * Method that fetches memories related to a given observation.\n * @param observation The observation to fetch memories for.\n * @param _now The current date.\n * @param runManager The CallbackManagerForChainRun to use for fetching memories.\n * @returns An array of Document instances representing the fetched memories.\n */\n async fetchMemories(\n observation: string,\n _now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<Document[]> {\n return this.memoryRetriever.invoke(\n observation,\n runManager?.getChild(\"memory_retriever\")\n );\n }\n}\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseMemory` class and has methods for adding a memory,\n * formatting memories, getting memories until a token limit is reached,\n * loading memory variables, saving the context of a model run to memory,\n * and clearing memory contents.\n * @example\n * ```typescript\n * const createNewMemoryRetriever = async () => {\n * const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());\n * const retriever = new TimeWeightedVectorStoreRetriever({\n * vectorStore,\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * });\n * return retriever;\n * };\n * const tommiesMemory = new GenerativeAgentMemory(\n * llm,\n * await createNewMemoryRetriever(),\n * { reflectionThreshold: 8 },\n * );\n * const summary = await tommiesMemory.getSummary();\n * ```\n */\nexport class GenerativeAgentMemory extends BaseMemory {\n llm: BaseLanguageModelInterface;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n verbose: boolean;\n\n reflectionThreshold?: number;\n\n private maxTokensLimit = 1200;\n\n queriesKey = \"queries\";\n\n mostRecentMemoriesTokenKey = \"recent_memories_token\";\n\n addMemoryKey = \"addMemory\";\n\n relevantMemoriesKey = \"relevant_memories\";\n\n relevantMemoriesSimpleKey = \"relevant_memories_simple\";\n\n mostRecentMemoriesKey = \"most_recent_memories\";\n\n nowKey = \"now\";\n\n memoryChain: GenerativeAgentMemoryChain;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config?: GenerativeAgentMemoryConfig\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.verbose = config?.verbose ?? this.verbose;\n this.reflectionThreshold =\n config?.reflectionThreshold ?? this.reflectionThreshold;\n this.maxTokensLimit = config?.maxTokensLimit ?? this.maxTokensLimit;\n this.memoryChain = new GenerativeAgentMemoryChain(llm, memoryRetriever, {\n reflectionThreshold: config?.reflectionThreshold,\n importanceWeight: config?.importanceWeight,\n });\n }\n\n /**\n * Method that returns the key for relevant memories.\n * @returns The key for relevant memories as a string.\n */\n getRelevantMemoriesKey(): string {\n return this.relevantMemoriesKey;\n }\n\n /**\n * Method that returns the key for the most recent memories token.\n * @returns The key for the most recent memories token as a string.\n */\n getMostRecentMemoriesTokenKey(): string {\n return this.mostRecentMemoriesTokenKey;\n }\n\n /**\n * Method that returns the key for adding a memory.\n * @returns The key for adding a memory as a string.\n */\n getAddMemoryKey(): string {\n return this.addMemoryKey;\n }\n\n /**\n * Method that returns the key for the current time.\n * @returns The key for the current time as a string.\n */\n getCurrentTimeKey(): string {\n return this.nowKey;\n }\n\n get memoryKeys(): string[] {\n // Return an array of memory keys\n return [this.relevantMemoriesKey, this.mostRecentMemoriesKey];\n }\n\n /**\n * Method that adds a memory to the agent's memory.\n * @param memoryContent The content of the memory to add.\n * @param now The current date.\n * @param metadata The metadata for the memory.\n * @param callbacks The Callbacks to use for adding the memory.\n * @returns The result of the memory addition.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.memoryChain.call(\n { memory_content: memoryContent, now, memory_metadata: metadata },\n callbacks\n );\n }\n\n /**\n * Method that formats the given relevant memories in detail.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesDetail(relevantMemories: Document[]): string {\n if (!relevantMemories.length) {\n return \"No relevant information.\";\n }\n const contentStrings = new Set();\n const content = [];\n for (const memory of relevantMemories) {\n if (memory.pageContent in contentStrings) {\n continue;\n }\n contentStrings.add(memory.pageContent);\n const createdTime = memory.metadata.created_at.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n content.push(`${createdTime}: ${memory.pageContent.trim()}`);\n }\n const joinedContent = content.map((mem) => `${mem}`).join(\"\\n\");\n return joinedContent;\n }\n\n /**\n * Method that formats the given relevant memories in a simple manner.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesSimple(relevantMemories: Document[]): string {\n const joinedContent = relevantMemories\n .map((mem) => `${mem.pageContent}`)\n .join(\"; \");\n return joinedContent;\n }\n\n /**\n * Method that retrieves memories until a token limit is reached.\n * @param consumedTokens The number of tokens consumed so far.\n * @returns The memories as a string.\n */\n async getMemoriesUntilLimit(consumedTokens: number): Promise<string> {\n // reduce the number of tokens in the documents\n const result = [];\n for (const doc of this.memoryRetriever\n .getMemoryStream()\n .slice()\n .reverse()) {\n if (consumedTokens >= this.maxTokensLimit) {\n if (this.verbose) {\n console.log(\"Exceeding max tokens for LLM, filtering memories\");\n }\n break;\n }\n // oxlint-disable-next-line no-param-reassign\n consumedTokens += await this.llm.getNumTokens(doc.pageContent);\n if (consumedTokens < this.maxTokensLimit) {\n result.push(doc);\n }\n }\n return this.formatMemoriesSimple(result);\n }\n\n get memoryVariables(): string[] {\n // input keys this memory class will load dynamically\n return [];\n }\n\n /**\n * Method that loads memory variables based on the given inputs.\n * @param inputs The inputs to use for loading memory variables.\n * @returns An object containing the loaded memory variables.\n */\n async loadMemoryVariables(\n inputs: InputValues\n ): Promise<Record<string, string>> {\n const queries = inputs[this.queriesKey];\n const now = inputs[this.nowKey];\n if (queries !== undefined) {\n const relevantMemories = (\n await Promise.all(\n queries.map((query: string) =>\n this.memoryChain.fetchMemories(query, now)\n )\n )\n ).flat();\n return {\n [this.relevantMemoriesKey]: this.formatMemoriesDetail(relevantMemories),\n [this.relevantMemoriesSimpleKey]:\n this.formatMemoriesSimple(relevantMemories),\n };\n }\n const mostRecentMemoriesToken = inputs[this.mostRecentMemoriesTokenKey];\n if (mostRecentMemoriesToken !== undefined) {\n return {\n [this.mostRecentMemoriesKey]: await this.getMemoriesUntilLimit(\n mostRecentMemoriesToken\n ),\n };\n }\n return {};\n }\n\n /**\n * Method that saves the context of a model run to memory.\n * @param _inputs The inputs of the model run.\n * @param outputs The outputs of the model run.\n * @returns Nothing.\n */\n async saveContext(\n _inputs: InputValues,\n outputs: OutputValues\n ): Promise<void> {\n // save the context of this model run to memory\n const mem = outputs[this.addMemoryKey];\n const now = outputs[this.nowKey];\n if (mem) {\n await this.addMemory(mem, now, {});\n }\n }\n\n /**\n * Method that clears the memory contents.\n * @returns Nothing.\n */\n clear(): void {\n // TODO: clear memory contents\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA2BA,IAAM,6BAAN,MAAM,mCAAmCA,aAAAA,UAAU;CACjD,OAAO,UAAU;AACf,SAAO;;CAGT,aAAa;CAEb;CAEA,mBAAmB;CAEnB;CAEA;CAEA,UAAU;CAEV,sBAA8B;CAE9B,YACE,KACA,iBACA,QACA;AACA,SAAO;AACP,OAAK,MAAM;AACX,OAAK,kBAAkB;AACvB,OAAK,sBAAsB,OAAO;AAClC,OAAK,mBAAmB,OAAO,oBAAoB,KAAK;AACxD,OAAK,UAAU,OAAO,WAAW,KAAK;;CAGxC,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAkB;GAAO;GAAkB;;CAGrD,IAAI,aAAuB;AACzB,SAAO,CAAC,SAAS;;;;;;;CAQnB,MAAM,QAAkC;A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sC;AAIzD,SAHsB,iBACnB,KAAK,QAAQ,GAAG,IAAI,cAAc,CAClC,KAAK,KAAK;;;;;;;CASf,MAAM,sBAAsB,gBAAyC;EAEnE,MAAM,SAAS,EAAE;AACjB,OAAK,MAAM,OAAO,KAAK,gBACpB,iBAAiB,CACjB,OAAO,CACP,SAAS,EAAE;AACZ,OAAI,kBAAkB,KAAK,gBAAgB;AACzC,QAAI,KAAK,QACP,SAAQ,IAAI,mDAAmD;AAEjE;;AAGF,qBAAkB,MAAM,KAAK,IAAI,aAAa,IAAI,YAAY;AAC9D,OAAI,iBAAiB,KAAK,eACxB,QAAO,KAAK,IAAI;;AAGpB,SAAO,KAAK,qBAAqB,OAAO;;CAG1C,IAAI,kBAA4B;AAE9B,SAAO,EAAE;;;;;;;CAQX,MAAM,oBACJ,QACiC;EACjC,MAAM,UAAU,OAAO,KAAK;EAC5B,MAAM,MAAM,OAAO,KAAK;AACxB,MAAI,YAAY,KAAA,GAAW;GACzB,MAAM,oBACJ,MAAM,QAAQ,IACZ,QAAQ,KAAK,UACX,KAAK,YAAY,cAAc,OAAO,IAAI,CAC3C,CACF,EACD,MAAM;AACR,UAAO;KACJ,KAAK,sBAAsB,KAAK,qBAAqB,iBAAiB;KACtE,KAAK,4BACJ,KAAK,qBAAqB,iBAAiB;IAC9C;;EAEH,MAAM,0BAA0B,OAAO,KAAK;AAC5C,MAAI,4BAA4B,KAAA,EAC9B,QAAO,GACJ,KAAK,wBAAwB,MAAM,KAAK,sBACvC,wBACD,EACF;AAEH,SAAO,EAAE;;;;;;;;CASX,MAAM,YACJ,SACA,SACe;EAEf,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,MAAM,QAAQ,KAAK;AACzB,MAAI,IACF,OAAM,KAAK,UAAU,KAAK,KAAK,EAAE,CAAC;;;;;;CAQtC,QAAc"}
|
|
1
|
+
{"version":3,"file":"generative_agent_memory.cjs","names":["BaseChain","LLMChain","Document","PromptTemplate","BaseMemory"],"sources":["../../../src/experimental/generative_agents/generative_agent_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseMemory, InputValues, OutputValues } from \"@langchain/core/memory\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { TimeWeightedVectorStoreRetriever } from \"../../retrievers/time_weighted.js\";\nimport { BaseChain } from \"../../chains/base.js\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nexport type GenerativeAgentMemoryConfig = {\n reflectionThreshold?: number;\n importanceWeight?: number;\n verbose?: boolean;\n maxTokensLimit?: number;\n};\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseChain` class and has methods for adding observations\n * or memories to the agent's memory, scoring the importance of a memory,\n * reflecting on recent events to add synthesized memories, and generating\n * insights on a topic of reflection based on pertinent memories.\n */\nclass GenerativeAgentMemoryChain extends BaseChain {\n static lc_name() {\n return \"GenerativeAgentMemoryChain\";\n }\n\n reflecting = false;\n\n reflectionThreshold?: number;\n\n importanceWeight = 0.15;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n llm: BaseLanguageModelInterface;\n\n verbose = false;\n\n private aggregateImportance = 0.0;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config: Omit<GenerativeAgentMemoryConfig, \"maxTokensLimit\">\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.reflectionThreshold = config.reflectionThreshold;\n this.importanceWeight = config.importanceWeight ?? this.importanceWeight;\n this.verbose = config.verbose ?? this.verbose;\n }\n\n _chainType(): string {\n return \"generative_agent_memory\";\n }\n\n get inputKeys(): string[] {\n return [\"memory_content\", \"now\", \"memory_metadata\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\"];\n }\n\n /**\n * Method that creates a new LLMChain with the given prompt.\n * @param prompt The PromptTemplate to use for the new LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\",\n });\n return chain;\n }\n\n async _call(values: ChainValues, runManager?: CallbackManagerForChainRun) {\n const { memory_content: memoryContent, now } = values;\n // add an observation or memory to the agent's memory\n const importanceScore = await this.scoreMemoryImportance(\n memoryContent,\n runManager\n );\n this.aggregateImportance += importanceScore;\n const document = new Document({\n pageContent: memoryContent,\n metadata: {\n importance: importanceScore,\n ...values.memory_metadata,\n },\n });\n await this.memoryRetriever.addDocuments([document]);\n // after an agent has processed a certain amount of memories (as measured by aggregate importance),\n // it is time to pause and reflect on recent events to add more synthesized memories to the agent's\n // memory stream.\n if (\n this.reflectionThreshold !== undefined &&\n this.aggregateImportance > this.reflectionThreshold &&\n !this.reflecting\n ) {\n console.log(\"Reflecting on current memories...\");\n this.reflecting = true;\n await this.pauseToReflect(now, runManager);\n this.aggregateImportance = 0.0;\n this.reflecting = false;\n }\n return { output: importanceScore };\n }\n\n /**\n * Method that pauses the agent to reflect on recent events and generate\n * new insights.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for the reflection.\n * @returns An array of new insights as strings.\n */\n async pauseToReflect(\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n if (this.verbose) {\n console.log(\"Pausing to reflect...\");\n }\n const newInsights: string[] = [];\n const topics = await this.getTopicsOfReflection(50, runManager);\n for (const topic of topics) {\n const insights = await this.getInsightsOnTopic(topic, now, runManager);\n for (const insight of insights) {\n // add memory\n await this.call(\n {\n memory_content: insight,\n now,\n memory_metadata: {\n source: \"reflection_insight\",\n },\n },\n runManager?.getChild(\"reflection_insight_memory\")\n );\n }\n newInsights.push(...insights);\n }\n return newInsights;\n }\n\n /**\n * Method that scores the importance of a given memory.\n * @param memoryContent The content of the memory to score.\n * @param runManager The CallbackManagerForChainRun to use for scoring.\n * @returns The importance score of the memory as a number.\n */\n async scoreMemoryImportance(\n memoryContent: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<number> {\n // score the absolute importance of a given memory\n const prompt = PromptTemplate.fromTemplate(\n \"On the scale of 1 to 10, where 1 is purely mundane\" +\n \" (e.g., brushing teeth, making bed) and 10 is\" +\n \" extremely poignant (e.g., a break up, college\" +\n \" acceptance), rate the likely poignancy of the\" +\n \" following piece of memory. Respond with a single integer.\" +\n \"\\nMemory: {memory_content}\" +\n \"\\nRating: \"\n );\n const score = await this.chain(prompt).run(\n memoryContent,\n runManager?.getChild(\"determine_importance\")\n );\n\n const strippedScore = score.trim();\n\n if (this.verbose) {\n console.log(\"Importance score:\", strippedScore);\n }\n const match = strippedScore.match(/^\\D*(\\d+)/);\n if (match) {\n const capturedNumber = parseFloat(match[1]);\n const result = (capturedNumber / 10) * this.importanceWeight;\n return result;\n } else {\n return 0.0;\n }\n }\n\n /**\n * Method that retrieves the topics of reflection based on the last K\n * memories.\n * @param lastK The number of most recent memories to consider for generating topics.\n * @param runManager The CallbackManagerForChainRun to use for retrieving topics.\n * @returns An array of topics of reflection as strings.\n */\n async getTopicsOfReflection(\n lastK: number,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n const prompt = PromptTemplate.fromTemplate(\n \"{observations}\\n\\n\" +\n \"Given only the information above, what are the 3 most salient\" +\n \" high-level questions we can answer about the subjects in\" +\n \" the statements? Provide each question on a new line.\\n\\n\"\n );\n\n const observations = this.memoryRetriever.getMemoryStream().slice(-lastK);\n const observationStr = observations\n .map((o: { pageContent: string }) => o.pageContent)\n .join(\"\\n\");\n const result = await this.chain(prompt).run(\n observationStr,\n runManager?.getChild(\"reflection_topics\")\n );\n return GenerativeAgentMemoryChain.parseList(result);\n }\n\n /**\n * Method that generates insights on a given topic of reflection based on\n * pertinent memories.\n * @param topic The topic of reflection.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for generating insights.\n * @returns An array of insights as strings.\n */\n async getInsightsOnTopic(\n topic: string,\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n // generate insights on a topic of reflection, based on pertinent memories\n const prompt = PromptTemplate.fromTemplate(\n \"Statements about {topic}\\n\" +\n \"{related_statements}\\n\\n\" +\n \"What 5 high-level insights can you infer from the above statements?\" +\n \" (example format: insight (because of 1, 5, 3))\"\n );\n\n const relatedMemories = await this.fetchMemories(topic, now, runManager);\n const relatedStatements: string = relatedMemories\n .map((memory, index) => `${index + 1}. ${memory.pageContent}`)\n .join(\"\\n\");\n const result = await this.chain(prompt).call(\n {\n topic,\n related_statements: relatedStatements,\n },\n runManager?.getChild(\"reflection_insights\")\n );\n return GenerativeAgentMemoryChain.parseList(result.output); // added output\n }\n\n /**\n * Method that parses a newline-separated string into a list of strings.\n * @param text The newline-separated string to parse.\n * @returns An array of strings.\n */\n static parseList(text: string): string[] {\n // parse a newline-separated string into a list of strings\n return text.split(\"\\n\").map((s) => s.trim());\n }\n\n // TODO: Mock \"now\" to simulate different times\n /**\n * Method that fetches memories related to a given observation.\n * @param observation The observation to fetch memories for.\n * @param _now The current date.\n * @param runManager The CallbackManagerForChainRun to use for fetching memories.\n * @returns An array of Document instances representing the fetched memories.\n */\n async fetchMemories(\n observation: string,\n _now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<Document[]> {\n return this.memoryRetriever.invoke(\n observation,\n runManager?.getChild(\"memory_retriever\")\n );\n }\n}\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseMemory` class and has methods for adding a memory,\n * formatting memories, getting memories until a token limit is reached,\n * loading memory variables, saving the context of a model run to memory,\n * and clearing memory contents.\n * @example\n * ```typescript\n * const createNewMemoryRetriever = async () => {\n * const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());\n * const retriever = new TimeWeightedVectorStoreRetriever({\n * vectorStore,\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * });\n * return retriever;\n * };\n * const tommiesMemory = new GenerativeAgentMemory(\n * llm,\n * await createNewMemoryRetriever(),\n * { reflectionThreshold: 8 },\n * );\n * const summary = await tommiesMemory.getSummary();\n * ```\n */\nexport class GenerativeAgentMemory extends BaseMemory {\n llm: BaseLanguageModelInterface;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n verbose: boolean;\n\n reflectionThreshold?: number;\n\n private maxTokensLimit = 1200;\n\n queriesKey = \"queries\";\n\n mostRecentMemoriesTokenKey = \"recent_memories_token\";\n\n addMemoryKey = \"addMemory\";\n\n relevantMemoriesKey = \"relevant_memories\";\n\n relevantMemoriesSimpleKey = \"relevant_memories_simple\";\n\n mostRecentMemoriesKey = \"most_recent_memories\";\n\n nowKey = \"now\";\n\n memoryChain: GenerativeAgentMemoryChain;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config?: GenerativeAgentMemoryConfig\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.verbose = config?.verbose ?? this.verbose;\n this.reflectionThreshold =\n config?.reflectionThreshold ?? this.reflectionThreshold;\n this.maxTokensLimit = config?.maxTokensLimit ?? this.maxTokensLimit;\n this.memoryChain = new GenerativeAgentMemoryChain(llm, memoryRetriever, {\n reflectionThreshold: config?.reflectionThreshold,\n importanceWeight: config?.importanceWeight,\n });\n }\n\n /**\n * Method that returns the key for relevant memories.\n * @returns The key for relevant memories as a string.\n */\n getRelevantMemoriesKey(): string {\n return this.relevantMemoriesKey;\n }\n\n /**\n * Method that returns the key for the most recent memories token.\n * @returns The key for the most recent memories token as a string.\n */\n getMostRecentMemoriesTokenKey(): string {\n return this.mostRecentMemoriesTokenKey;\n }\n\n /**\n * Method that returns the key for adding a memory.\n * @returns The key for adding a memory as a string.\n */\n getAddMemoryKey(): string {\n return this.addMemoryKey;\n }\n\n /**\n * Method that returns the key for the current time.\n * @returns The key for the current time as a string.\n */\n getCurrentTimeKey(): string {\n return this.nowKey;\n }\n\n get memoryKeys(): string[] {\n // Return an array of memory keys\n return [this.relevantMemoriesKey, this.mostRecentMemoriesKey];\n }\n\n /**\n * Method that adds a memory to the agent's memory.\n * @param memoryContent The content of the memory to add.\n * @param now The current date.\n * @param metadata The metadata for the memory.\n * @param callbacks The Callbacks to use for adding the memory.\n * @returns The result of the memory addition.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.memoryChain.call(\n { memory_content: memoryContent, now, memory_metadata: metadata },\n callbacks\n );\n }\n\n /**\n * Method that formats the given relevant memories in detail.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesDetail(relevantMemories: Document[]): string {\n if (!relevantMemories.length) {\n return \"No relevant information.\";\n }\n const contentStrings = new Set();\n const content = [];\n for (const memory of relevantMemories) {\n if (memory.pageContent in contentStrings) {\n continue;\n }\n contentStrings.add(memory.pageContent);\n const createdTime = memory.metadata.created_at.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n content.push(`${createdTime}: ${memory.pageContent.trim()}`);\n }\n const joinedContent = content.map((mem) => `${mem}`).join(\"\\n\");\n return joinedContent;\n }\n\n /**\n * Method that formats the given relevant memories in a simple manner.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesSimple(relevantMemories: Document[]): string {\n const joinedContent = relevantMemories\n .map((mem) => `${mem.pageContent}`)\n .join(\"; \");\n return joinedContent;\n }\n\n /**\n * Method that retrieves memories until a token limit is reached.\n * @param consumedTokens The number of tokens consumed so far.\n * @returns The memories as a string.\n */\n async getMemoriesUntilLimit(consumedTokens: number): Promise<string> {\n // reduce the number of tokens in the documents\n const result = [];\n for (const doc of this.memoryRetriever\n .getMemoryStream()\n .slice()\n .reverse()) {\n if (consumedTokens >= this.maxTokensLimit) {\n if (this.verbose) {\n console.log(\"Exceeding max tokens for LLM, filtering memories\");\n }\n break;\n }\n // oxlint-disable-next-line no-param-reassign\n consumedTokens += await this.llm.getNumTokens(doc.pageContent);\n if (consumedTokens < this.maxTokensLimit) {\n result.push(doc);\n }\n }\n return this.formatMemoriesSimple(result);\n }\n\n get memoryVariables(): string[] {\n // input keys this memory class will load dynamically\n return [];\n }\n\n /**\n * Method that loads memory variables based on the given inputs.\n * @param inputs The inputs to use for loading memory variables.\n * @returns An object containing the loaded memory variables.\n */\n async loadMemoryVariables(\n inputs: InputValues\n ): Promise<Record<string, string>> {\n const queries = inputs[this.queriesKey];\n const now = inputs[this.nowKey];\n if (queries !== undefined) {\n const relevantMemories = (\n await Promise.all(\n queries.map((query: string) =>\n this.memoryChain.fetchMemories(query, now)\n )\n )\n ).flat();\n return {\n [this.relevantMemoriesKey]: this.formatMemoriesDetail(relevantMemories),\n [this.relevantMemoriesSimpleKey]:\n this.formatMemoriesSimple(relevantMemories),\n };\n }\n const mostRecentMemoriesToken = inputs[this.mostRecentMemoriesTokenKey];\n if (mostRecentMemoriesToken !== undefined) {\n return {\n [this.mostRecentMemoriesKey]: await this.getMemoriesUntilLimit(\n mostRecentMemoriesToken\n ),\n };\n }\n return {};\n }\n\n /**\n * Method that saves the context of a model run to memory.\n * @param _inputs The inputs of the model run.\n * @param outputs The outputs of the model run.\n * @returns Nothing.\n */\n async saveContext(\n _inputs: InputValues,\n outputs: OutputValues\n ): Promise<void> {\n // save the context of this model run to memory\n const mem = outputs[this.addMemoryKey];\n const now = outputs[this.nowKey];\n if (mem) {\n await this.addMemory(mem, now, {});\n }\n }\n\n /**\n * Method that clears the memory contents.\n * @returns Nothing.\n */\n clear(): void {\n // TODO: clear memory contents\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA2BA,IAAM,6BAAN,MAAM,mCAAmCA,aAAAA,UAAU;CACjD,OAAO,UAAU;AACf,SAAO;;CAGT,aAAa;CAEb;CAEA,mBAAmB;CAEnB;CAE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A4B,KAAA,EAC9B,QAAO,GACJ,KAAK,wBAAwB,MAAM,KAAK,sBACvC,wBACD,EACF;AAEH,SAAO,EAAE;;;;;;;;CASX,MAAM,YACJ,SACA,SACe;EAEf,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,MAAM,QAAQ,KAAK;AACzB,MAAI,IACF,OAAM,KAAK,UAAU,KAAK,KAAK,EAAE,CAAC;;;;;;CAQtC,QAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generative_agent_memory.js","names":[],"sources":["../../../src/experimental/generative_agents/generative_agent_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseMemory, InputValues, OutputValues } from \"@langchain/core/memory\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { TimeWeightedVectorStoreRetriever } from \"../../retrievers/time_weighted.js\";\nimport { BaseChain } from \"../../chains/base.js\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nexport type GenerativeAgentMemoryConfig = {\n reflectionThreshold?: number;\n importanceWeight?: number;\n verbose?: boolean;\n maxTokensLimit?: number;\n};\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseChain` class and has methods for adding observations\n * or memories to the agent's memory, scoring the importance of a memory,\n * reflecting on recent events to add synthesized memories, and generating\n * insights on a topic of reflection based on pertinent memories.\n */\nclass GenerativeAgentMemoryChain extends BaseChain {\n static lc_name() {\n return \"GenerativeAgentMemoryChain\";\n }\n\n reflecting = false;\n\n reflectionThreshold?: number;\n\n importanceWeight = 0.15;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n llm: BaseLanguageModelInterface;\n\n verbose = false;\n\n private aggregateImportance = 0.0;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config: Omit<GenerativeAgentMemoryConfig, \"maxTokensLimit\">\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.reflectionThreshold = config.reflectionThreshold;\n this.importanceWeight = config.importanceWeight ?? this.importanceWeight;\n this.verbose = config.verbose ?? this.verbose;\n }\n\n _chainType(): string {\n return \"generative_agent_memory\";\n }\n\n get inputKeys(): string[] {\n return [\"memory_content\", \"now\", \"memory_metadata\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\"];\n }\n\n /**\n * Method that creates a new LLMChain with the given prompt.\n * @param prompt The PromptTemplate to use for the new LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\",\n });\n return chain;\n }\n\n async _call(values: ChainValues, runManager?: CallbackManagerForChainRun) {\n const { memory_content: memoryContent, now } = values;\n // add an observation or memory to the agent's memory\n const importanceScore = await this.scoreMemoryImportance(\n memoryContent,\n runManager\n );\n this.aggregateImportance += importanceScore;\n const document = new Document({\n pageContent: memoryContent,\n metadata: {\n importance: importanceScore,\n ...values.memory_metadata,\n },\n });\n await this.memoryRetriever.addDocuments([document]);\n // after an agent has processed a certain amount of memories (as measured by aggregate importance),\n // it is time to pause and reflect on recent events to add more synthesized memories to the agent's\n // memory stream.\n if (\n this.reflectionThreshold !== undefined &&\n this.aggregateImportance > this.reflectionThreshold &&\n !this.reflecting\n ) {\n console.log(\"Reflecting on current memories...\");\n this.reflecting = true;\n await this.pauseToReflect(now, runManager);\n this.aggregateImportance = 0.0;\n this.reflecting = false;\n }\n return { output: importanceScore };\n }\n\n /**\n * Method that pauses the agent to reflect on recent events and generate\n * new insights.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for the reflection.\n * @returns An array of new insights as strings.\n */\n async pauseToReflect(\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n if (this.verbose) {\n console.log(\"Pausing to reflect...\");\n }\n const newInsights: string[] = [];\n const topics = await this.getTopicsOfReflection(50, runManager);\n for (const topic of topics) {\n const insights = await this.getInsightsOnTopic(topic, now, runManager);\n for (const insight of insights) {\n // add memory\n await this.call(\n {\n memory_content: insight,\n now,\n memory_metadata: {\n source: \"reflection_insight\",\n },\n },\n runManager?.getChild(\"reflection_insight_memory\")\n );\n }\n newInsights.push(...insights);\n }\n return newInsights;\n }\n\n /**\n * Method that scores the importance of a given memory.\n * @param memoryContent The content of the memory to score.\n * @param runManager The CallbackManagerForChainRun to use for scoring.\n * @returns The importance score of the memory as a number.\n */\n async scoreMemoryImportance(\n memoryContent: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<number> {\n // score the absolute importance of a given memory\n const prompt = PromptTemplate.fromTemplate(\n \"On the scale of 1 to 10, where 1 is purely mundane\" +\n \" (e.g., brushing teeth, making bed) and 10 is\" +\n \" extremely poignant (e.g., a break up, college\" +\n \" acceptance), rate the likely poignancy of the\" +\n \" following piece of memory. Respond with a single integer.\" +\n \"\\nMemory: {memory_content}\" +\n \"\\nRating: \"\n );\n const score = await this.chain(prompt).run(\n memoryContent,\n runManager?.getChild(\"determine_importance\")\n );\n\n const strippedScore = score.trim();\n\n if (this.verbose) {\n console.log(\"Importance score:\", strippedScore);\n }\n const match = strippedScore.match(/^\\D*(\\d+)/);\n if (match) {\n const capturedNumber = parseFloat(match[1]);\n const result = (capturedNumber / 10) * this.importanceWeight;\n return result;\n } else {\n return 0.0;\n }\n }\n\n /**\n * Method that retrieves the topics of reflection based on the last K\n * memories.\n * @param lastK The number of most recent memories to consider for generating topics.\n * @param runManager The CallbackManagerForChainRun to use for retrieving topics.\n * @returns An array of topics of reflection as strings.\n */\n async getTopicsOfReflection(\n lastK: number,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n const prompt = PromptTemplate.fromTemplate(\n \"{observations}\\n\\n\" +\n \"Given only the information above, what are the 3 most salient\" +\n \" high-level questions we can answer about the subjects in\" +\n \" the statements? Provide each question on a new line.\\n\\n\"\n );\n\n const observations = this.memoryRetriever.getMemoryStream().slice(-lastK);\n const observationStr = observations\n .map((o: { pageContent: string }) => o.pageContent)\n .join(\"\\n\");\n const result = await this.chain(prompt).run(\n observationStr,\n runManager?.getChild(\"reflection_topics\")\n );\n return GenerativeAgentMemoryChain.parseList(result);\n }\n\n /**\n * Method that generates insights on a given topic of reflection based on\n * pertinent memories.\n * @param topic The topic of reflection.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for generating insights.\n * @returns An array of insights as strings.\n */\n async getInsightsOnTopic(\n topic: string,\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n // generate insights on a topic of reflection, based on pertinent memories\n const prompt = PromptTemplate.fromTemplate(\n \"Statements about {topic}\\n\" +\n \"{related_statements}\\n\\n\" +\n \"What 5 high-level insights can you infer from the above statements?\" +\n \" (example format: insight (because of 1, 5, 3))\"\n );\n\n const relatedMemories = await this.fetchMemories(topic, now, runManager);\n const relatedStatements: string = relatedMemories\n .map((memory, index) => `${index + 1}. ${memory.pageContent}`)\n .join(\"\\n\");\n const result = await this.chain(prompt).call(\n {\n topic,\n related_statements: relatedStatements,\n },\n runManager?.getChild(\"reflection_insights\")\n );\n return GenerativeAgentMemoryChain.parseList(result.output); // added output\n }\n\n /**\n * Method that parses a newline-separated string into a list of strings.\n * @param text The newline-separated string to parse.\n * @returns An array of strings.\n */\n static parseList(text: string): string[] {\n // parse a newine seperates string into a list of strings\n return text.split(\"\\n\").map((s) => s.trim());\n }\n\n // TODO: Mock \"now\" to simulate different times\n /**\n * Method that fetches memories related to a given observation.\n * @param observation The observation to fetch memories for.\n * @param _now The current date.\n * @param runManager The CallbackManagerForChainRun to use for fetching memories.\n * @returns An array of Document instances representing the fetched memories.\n */\n async fetchMemories(\n observation: string,\n _now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<Document[]> {\n return this.memoryRetriever.invoke(\n observation,\n runManager?.getChild(\"memory_retriever\")\n );\n }\n}\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseMemory` class and has methods for adding a memory,\n * formatting memories, getting memories until a token limit is reached,\n * loading memory variables, saving the context of a model run to memory,\n * and clearing memory contents.\n * @example\n * ```typescript\n * const createNewMemoryRetriever = async () => {\n * const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());\n * const retriever = new TimeWeightedVectorStoreRetriever({\n * vectorStore,\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * });\n * return retriever;\n * };\n * const tommiesMemory = new GenerativeAgentMemory(\n * llm,\n * await createNewMemoryRetriever(),\n * { reflectionThreshold: 8 },\n * );\n * const summary = await tommiesMemory.getSummary();\n * ```\n */\nexport class GenerativeAgentMemory extends BaseMemory {\n llm: BaseLanguageModelInterface;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n verbose: boolean;\n\n reflectionThreshold?: number;\n\n private maxTokensLimit = 1200;\n\n queriesKey = \"queries\";\n\n mostRecentMemoriesTokenKey = \"recent_memories_token\";\n\n addMemoryKey = \"addMemory\";\n\n relevantMemoriesKey = \"relevant_memories\";\n\n relevantMemoriesSimpleKey = \"relevant_memories_simple\";\n\n mostRecentMemoriesKey = \"most_recent_memories\";\n\n nowKey = \"now\";\n\n memoryChain: GenerativeAgentMemoryChain;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config?: GenerativeAgentMemoryConfig\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.verbose = config?.verbose ?? this.verbose;\n this.reflectionThreshold =\n config?.reflectionThreshold ?? this.reflectionThreshold;\n this.maxTokensLimit = config?.maxTokensLimit ?? this.maxTokensLimit;\n this.memoryChain = new GenerativeAgentMemoryChain(llm, memoryRetriever, {\n reflectionThreshold: config?.reflectionThreshold,\n importanceWeight: config?.importanceWeight,\n });\n }\n\n /**\n * Method that returns the key for relevant memories.\n * @returns The key for relevant memories as a string.\n */\n getRelevantMemoriesKey(): string {\n return this.relevantMemoriesKey;\n }\n\n /**\n * Method that returns the key for the most recent memories token.\n * @returns The key for the most recent memories token as a string.\n */\n getMostRecentMemoriesTokenKey(): string {\n return this.mostRecentMemoriesTokenKey;\n }\n\n /**\n * Method that returns the key for adding a memory.\n * @returns The key for adding a memory as a string.\n */\n getAddMemoryKey(): string {\n return this.addMemoryKey;\n }\n\n /**\n * Method that returns the key for the current time.\n * @returns The key for the current time as a string.\n */\n getCurrentTimeKey(): string {\n return this.nowKey;\n }\n\n get memoryKeys(): string[] {\n // Return an array of memory keys\n return [this.relevantMemoriesKey, this.mostRecentMemoriesKey];\n }\n\n /**\n * Method that adds a memory to the agent's memory.\n * @param memoryContent The content of the memory to add.\n * @param now The current date.\n * @param metadata The metadata for the memory.\n * @param callbacks The Callbacks to use for adding the memory.\n * @returns The result of the memory addition.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.memoryChain.call(\n { memory_content: memoryContent, now, memory_metadata: metadata },\n callbacks\n );\n }\n\n /**\n * Method that formats the given relevant memories in detail.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesDetail(relevantMemories: Document[]): string {\n if (!relevantMemories.length) {\n return \"No relevant information.\";\n }\n const contentStrings = new Set();\n const content = [];\n for (const memory of relevantMemories) {\n if (memory.pageContent in contentStrings) {\n continue;\n }\n contentStrings.add(memory.pageContent);\n const createdTime = memory.metadata.created_at.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n content.push(`${createdTime}: ${memory.pageContent.trim()}`);\n }\n const joinedContent = content.map((mem) => `${mem}`).join(\"\\n\");\n return joinedContent;\n }\n\n /**\n * Method that formats the given relevant memories in a simple manner.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesSimple(relevantMemories: Document[]): string {\n const joinedContent = relevantMemories\n .map((mem) => `${mem.pageContent}`)\n .join(\"; \");\n return joinedContent;\n }\n\n /**\n * Method that retrieves memories until a token limit is reached.\n * @param consumedTokens The number of tokens consumed so far.\n * @returns The memories as a string.\n */\n async getMemoriesUntilLimit(consumedTokens: number): Promise<string> {\n // reduce the number of tokens in the documents\n const result = [];\n for (const doc of this.memoryRetriever\n .getMemoryStream()\n .slice()\n .reverse()) {\n if (consumedTokens >= this.maxTokensLimit) {\n if (this.verbose) {\n console.log(\"Exceeding max tokens for LLM, filtering memories\");\n }\n break;\n }\n // oxlint-disable-next-line no-param-reassign\n consumedTokens += await this.llm.getNumTokens(doc.pageContent);\n if (consumedTokens < this.maxTokensLimit) {\n result.push(doc);\n }\n }\n return this.formatMemoriesSimple(result);\n }\n\n get memoryVariables(): string[] {\n // input keys this memory class will load dynamically\n return [];\n }\n\n /**\n * Method that loads memory variables based on the given inputs.\n * @param inputs The inputs to use for loading memory variables.\n * @returns An object containing the loaded memory variables.\n */\n async loadMemoryVariables(\n inputs: InputValues\n ): Promise<Record<string, string>> {\n const queries = inputs[this.queriesKey];\n const now = inputs[this.nowKey];\n if (queries !== undefined) {\n const relevantMemories = (\n await Promise.all(\n queries.map((query: string) =>\n this.memoryChain.fetchMemories(query, now)\n )\n )\n ).flat();\n return {\n [this.relevantMemoriesKey]: this.formatMemoriesDetail(relevantMemories),\n [this.relevantMemoriesSimpleKey]:\n this.formatMemoriesSimple(relevantMemories),\n };\n }\n const mostRecentMemoriesToken = inputs[this.mostRecentMemoriesTokenKey];\n if (mostRecentMemoriesToken !== undefined) {\n return {\n [this.mostRecentMemoriesKey]: await this.getMemoriesUntilLimit(\n mostRecentMemoriesToken\n ),\n };\n }\n return {};\n }\n\n /**\n * Method that saves the context of a model run to memory.\n * @param _inputs The inputs of the model run.\n * @param outputs The outputs of the model run.\n * @returns Nothing.\n */\n async saveContext(\n _inputs: InputValues,\n outputs: OutputValues\n ): Promise<void> {\n // save the context of this model run to memory\n const mem = outputs[this.addMemoryKey];\n const now = outputs[this.nowKey];\n if (mem) {\n await this.addMemory(mem, now, {});\n }\n }\n\n /**\n * Method that clears the memory contents.\n * @returns Nothing.\n */\n clear(): void {\n // TODO: clear memory contents\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,IAAM,6BAAN,MAAM,mCAAmC,UAAU;CACjD,OAAO,UAAU;AACf,SAAO;;CAGT,aAAa;CAEb;CAEA,mBAAmB;CAEnB;CAEA;CAEA,UAAU;CAEV,sBAA8B;CAE9B,YACE,KACA,iBACA,QACA;AACA,SAAO;AACP,OAAK,MAAM;AACX,OAAK,kBAAkB;AACvB,OAAK,sBAAsB,OAAO;AAClC,OAAK,mBAAmB,OAAO,oBAAoB,KAAK;AACxD,OAAK,UAAU,OAAO,WAAW,KAAK;;CAGxC,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAkB;GAAO;GAAkB;;CAGrD,IAAI,aAAuB;AACzB,SAAO,CAAC,SAAS;;;;;;;CAQnB,MAAM,QAAkC;AAOtC,SANc,IAAI,SAAS;GACzB,KAAK,KAAK;GACV;GACA,SAAS,KAAK;GACd,WAAW;GACZ,CAAC;;CAIJ,MAAM,MAAM,QAAqB,YAAyC;EACxE,MAAM,EAAE,gBAAgB,eAAe,QAAQ;EAE/C,MAAM,kBAAkB,MAAM,KAAK,sBACjC,eACA,WACD;AACD,OAAK,uBAAuB;EAC5B,MAAM,WAAW,IAAI,SAAS;GAC5B,aAAa;GACb,UAAU;IACR,YAAY;IACZ,GAAG,OAAO;IACX;GACF,CAAC;AACF,QAAM,KAAK,gBAAgB,aAAa,CAAC,SAAS,CAAC;AAInD,MACE,KAAK,wBAAwB,KAAA,KAC7B,KAAK,sBAAsB,KAAK,uBAChC,CAAC,KAAK,YACN;AACA,WAAQ,IAAI,oCAAoC;AAChD,QAAK,aAAa;AAClB,SAAM,KAA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MAAI,YAAY,KAAA,GAAW;GACzB,MAAM,oBACJ,MAAM,QAAQ,IACZ,QAAQ,KAAK,UACX,KAAK,YAAY,cAAc,OAAO,IAAI,CAC3C,CACF,EACD,MAAM;AACR,UAAO;KACJ,KAAK,sBAAsB,KAAK,qBAAqB,iBAAiB;KACtE,KAAK,4BACJ,KAAK,qBAAqB,iBAAiB;IAC9C;;EAEH,MAAM,0BAA0B,OAAO,KAAK;AAC5C,MAAI,4BAA4B,KAAA,EAC9B,QAAO,GACJ,KAAK,wBAAwB,MAAM,KAAK,sBACvC,wBACD,EACF;AAEH,SAAO,EAAE;;;;;;;;CASX,MAAM,YACJ,SACA,SACe;EAEf,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,MAAM,QAAQ,KAAK;AACzB,MAAI,IACF,OAAM,KAAK,UAAU,KAAK,KAAK,EAAE,CAAC;;;;;;CAQtC,QAAc"}
|
|
1
|
+
{"version":3,"file":"generative_agent_memory.js","names":[],"sources":["../../../src/experimental/generative_agents/generative_agent_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseMemory, InputValues, OutputValues } from \"@langchain/core/memory\";\nimport {\n CallbackManagerForChainRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { TimeWeightedVectorStoreRetriever } from \"../../retrievers/time_weighted.js\";\nimport { BaseChain } from \"../../chains/base.js\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nexport type GenerativeAgentMemoryConfig = {\n reflectionThreshold?: number;\n importanceWeight?: number;\n verbose?: boolean;\n maxTokensLimit?: number;\n};\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseChain` class and has methods for adding observations\n * or memories to the agent's memory, scoring the importance of a memory,\n * reflecting on recent events to add synthesized memories, and generating\n * insights on a topic of reflection based on pertinent memories.\n */\nclass GenerativeAgentMemoryChain extends BaseChain {\n static lc_name() {\n return \"GenerativeAgentMemoryChain\";\n }\n\n reflecting = false;\n\n reflectionThreshold?: number;\n\n importanceWeight = 0.15;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n llm: BaseLanguageModelInterface;\n\n verbose = false;\n\n private aggregateImportance = 0.0;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config: Omit<GenerativeAgentMemoryConfig, \"maxTokensLimit\">\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.reflectionThreshold = config.reflectionThreshold;\n this.importanceWeight = config.importanceWeight ?? this.importanceWeight;\n this.verbose = config.verbose ?? this.verbose;\n }\n\n _chainType(): string {\n return \"generative_agent_memory\";\n }\n\n get inputKeys(): string[] {\n return [\"memory_content\", \"now\", \"memory_metadata\"];\n }\n\n get outputKeys(): string[] {\n return [\"output\"];\n }\n\n /**\n * Method that creates a new LLMChain with the given prompt.\n * @param prompt The PromptTemplate to use for the new LLMChain.\n * @returns A new LLMChain instance.\n */\n chain(prompt: PromptTemplate): LLMChain {\n const chain = new LLMChain({\n llm: this.llm,\n prompt,\n verbose: this.verbose,\n outputKey: \"output\",\n });\n return chain;\n }\n\n async _call(values: ChainValues, runManager?: CallbackManagerForChainRun) {\n const { memory_content: memoryContent, now } = values;\n // add an observation or memory to the agent's memory\n const importanceScore = await this.scoreMemoryImportance(\n memoryContent,\n runManager\n );\n this.aggregateImportance += importanceScore;\n const document = new Document({\n pageContent: memoryContent,\n metadata: {\n importance: importanceScore,\n ...values.memory_metadata,\n },\n });\n await this.memoryRetriever.addDocuments([document]);\n // after an agent has processed a certain amount of memories (as measured by aggregate importance),\n // it is time to pause and reflect on recent events to add more synthesized memories to the agent's\n // memory stream.\n if (\n this.reflectionThreshold !== undefined &&\n this.aggregateImportance > this.reflectionThreshold &&\n !this.reflecting\n ) {\n console.log(\"Reflecting on current memories...\");\n this.reflecting = true;\n await this.pauseToReflect(now, runManager);\n this.aggregateImportance = 0.0;\n this.reflecting = false;\n }\n return { output: importanceScore };\n }\n\n /**\n * Method that pauses the agent to reflect on recent events and generate\n * new insights.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for the reflection.\n * @returns An array of new insights as strings.\n */\n async pauseToReflect(\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n if (this.verbose) {\n console.log(\"Pausing to reflect...\");\n }\n const newInsights: string[] = [];\n const topics = await this.getTopicsOfReflection(50, runManager);\n for (const topic of topics) {\n const insights = await this.getInsightsOnTopic(topic, now, runManager);\n for (const insight of insights) {\n // add memory\n await this.call(\n {\n memory_content: insight,\n now,\n memory_metadata: {\n source: \"reflection_insight\",\n },\n },\n runManager?.getChild(\"reflection_insight_memory\")\n );\n }\n newInsights.push(...insights);\n }\n return newInsights;\n }\n\n /**\n * Method that scores the importance of a given memory.\n * @param memoryContent The content of the memory to score.\n * @param runManager The CallbackManagerForChainRun to use for scoring.\n * @returns The importance score of the memory as a number.\n */\n async scoreMemoryImportance(\n memoryContent: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<number> {\n // score the absolute importance of a given memory\n const prompt = PromptTemplate.fromTemplate(\n \"On the scale of 1 to 10, where 1 is purely mundane\" +\n \" (e.g., brushing teeth, making bed) and 10 is\" +\n \" extremely poignant (e.g., a break up, college\" +\n \" acceptance), rate the likely poignancy of the\" +\n \" following piece of memory. Respond with a single integer.\" +\n \"\\nMemory: {memory_content}\" +\n \"\\nRating: \"\n );\n const score = await this.chain(prompt).run(\n memoryContent,\n runManager?.getChild(\"determine_importance\")\n );\n\n const strippedScore = score.trim();\n\n if (this.verbose) {\n console.log(\"Importance score:\", strippedScore);\n }\n const match = strippedScore.match(/^\\D*(\\d+)/);\n if (match) {\n const capturedNumber = parseFloat(match[1]);\n const result = (capturedNumber / 10) * this.importanceWeight;\n return result;\n } else {\n return 0.0;\n }\n }\n\n /**\n * Method that retrieves the topics of reflection based on the last K\n * memories.\n * @param lastK The number of most recent memories to consider for generating topics.\n * @param runManager The CallbackManagerForChainRun to use for retrieving topics.\n * @returns An array of topics of reflection as strings.\n */\n async getTopicsOfReflection(\n lastK: number,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n const prompt = PromptTemplate.fromTemplate(\n \"{observations}\\n\\n\" +\n \"Given only the information above, what are the 3 most salient\" +\n \" high-level questions we can answer about the subjects in\" +\n \" the statements? Provide each question on a new line.\\n\\n\"\n );\n\n const observations = this.memoryRetriever.getMemoryStream().slice(-lastK);\n const observationStr = observations\n .map((o: { pageContent: string }) => o.pageContent)\n .join(\"\\n\");\n const result = await this.chain(prompt).run(\n observationStr,\n runManager?.getChild(\"reflection_topics\")\n );\n return GenerativeAgentMemoryChain.parseList(result);\n }\n\n /**\n * Method that generates insights on a given topic of reflection based on\n * pertinent memories.\n * @param topic The topic of reflection.\n * @param now The current date.\n * @param runManager The CallbackManagerForChainRun to use for generating insights.\n * @returns An array of insights as strings.\n */\n async getInsightsOnTopic(\n topic: string,\n now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<string[]> {\n // generate insights on a topic of reflection, based on pertinent memories\n const prompt = PromptTemplate.fromTemplate(\n \"Statements about {topic}\\n\" +\n \"{related_statements}\\n\\n\" +\n \"What 5 high-level insights can you infer from the above statements?\" +\n \" (example format: insight (because of 1, 5, 3))\"\n );\n\n const relatedMemories = await this.fetchMemories(topic, now, runManager);\n const relatedStatements: string = relatedMemories\n .map((memory, index) => `${index + 1}. ${memory.pageContent}`)\n .join(\"\\n\");\n const result = await this.chain(prompt).call(\n {\n topic,\n related_statements: relatedStatements,\n },\n runManager?.getChild(\"reflection_insights\")\n );\n return GenerativeAgentMemoryChain.parseList(result.output); // added output\n }\n\n /**\n * Method that parses a newline-separated string into a list of strings.\n * @param text The newline-separated string to parse.\n * @returns An array of strings.\n */\n static parseList(text: string): string[] {\n // parse a newline-separated string into a list of strings\n return text.split(\"\\n\").map((s) => s.trim());\n }\n\n // TODO: Mock \"now\" to simulate different times\n /**\n * Method that fetches memories related to a given observation.\n * @param observation The observation to fetch memories for.\n * @param _now The current date.\n * @param runManager The CallbackManagerForChainRun to use for fetching memories.\n * @returns An array of Document instances representing the fetched memories.\n */\n async fetchMemories(\n observation: string,\n _now?: Date,\n runManager?: CallbackManagerForChainRun\n ): Promise<Document[]> {\n return this.memoryRetriever.invoke(\n observation,\n runManager?.getChild(\"memory_retriever\")\n );\n }\n}\n\n/**\n * Class that manages the memory of a generative agent in LangChain. It\n * extends the `BaseMemory` class and has methods for adding a memory,\n * formatting memories, getting memories until a token limit is reached,\n * loading memory variables, saving the context of a model run to memory,\n * and clearing memory contents.\n * @example\n * ```typescript\n * const createNewMemoryRetriever = async () => {\n * const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());\n * const retriever = new TimeWeightedVectorStoreRetriever({\n * vectorStore,\n * otherScoreKeys: [\"importance\"],\n * k: 15,\n * });\n * return retriever;\n * };\n * const tommiesMemory = new GenerativeAgentMemory(\n * llm,\n * await createNewMemoryRetriever(),\n * { reflectionThreshold: 8 },\n * );\n * const summary = await tommiesMemory.getSummary();\n * ```\n */\nexport class GenerativeAgentMemory extends BaseMemory {\n llm: BaseLanguageModelInterface;\n\n memoryRetriever: TimeWeightedVectorStoreRetriever;\n\n verbose: boolean;\n\n reflectionThreshold?: number;\n\n private maxTokensLimit = 1200;\n\n queriesKey = \"queries\";\n\n mostRecentMemoriesTokenKey = \"recent_memories_token\";\n\n addMemoryKey = \"addMemory\";\n\n relevantMemoriesKey = \"relevant_memories\";\n\n relevantMemoriesSimpleKey = \"relevant_memories_simple\";\n\n mostRecentMemoriesKey = \"most_recent_memories\";\n\n nowKey = \"now\";\n\n memoryChain: GenerativeAgentMemoryChain;\n\n constructor(\n llm: BaseLanguageModelInterface,\n memoryRetriever: TimeWeightedVectorStoreRetriever,\n config?: GenerativeAgentMemoryConfig\n ) {\n super();\n this.llm = llm;\n this.memoryRetriever = memoryRetriever;\n this.verbose = config?.verbose ?? this.verbose;\n this.reflectionThreshold =\n config?.reflectionThreshold ?? this.reflectionThreshold;\n this.maxTokensLimit = config?.maxTokensLimit ?? this.maxTokensLimit;\n this.memoryChain = new GenerativeAgentMemoryChain(llm, memoryRetriever, {\n reflectionThreshold: config?.reflectionThreshold,\n importanceWeight: config?.importanceWeight,\n });\n }\n\n /**\n * Method that returns the key for relevant memories.\n * @returns The key for relevant memories as a string.\n */\n getRelevantMemoriesKey(): string {\n return this.relevantMemoriesKey;\n }\n\n /**\n * Method that returns the key for the most recent memories token.\n * @returns The key for the most recent memories token as a string.\n */\n getMostRecentMemoriesTokenKey(): string {\n return this.mostRecentMemoriesTokenKey;\n }\n\n /**\n * Method that returns the key for adding a memory.\n * @returns The key for adding a memory as a string.\n */\n getAddMemoryKey(): string {\n return this.addMemoryKey;\n }\n\n /**\n * Method that returns the key for the current time.\n * @returns The key for the current time as a string.\n */\n getCurrentTimeKey(): string {\n return this.nowKey;\n }\n\n get memoryKeys(): string[] {\n // Return an array of memory keys\n return [this.relevantMemoriesKey, this.mostRecentMemoriesKey];\n }\n\n /**\n * Method that adds a memory to the agent's memory.\n * @param memoryContent The content of the memory to add.\n * @param now The current date.\n * @param metadata The metadata for the memory.\n * @param callbacks The Callbacks to use for adding the memory.\n * @returns The result of the memory addition.\n */\n async addMemory(\n memoryContent: string,\n now?: Date,\n metadata?: Record<string, unknown>,\n callbacks?: Callbacks\n ) {\n return this.memoryChain.call(\n { memory_content: memoryContent, now, memory_metadata: metadata },\n callbacks\n );\n }\n\n /**\n * Method that formats the given relevant memories in detail.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesDetail(relevantMemories: Document[]): string {\n if (!relevantMemories.length) {\n return \"No relevant information.\";\n }\n const contentStrings = new Set();\n const content = [];\n for (const memory of relevantMemories) {\n if (memory.pageContent in contentStrings) {\n continue;\n }\n contentStrings.add(memory.pageContent);\n const createdTime = memory.metadata.created_at.toLocaleString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true,\n });\n content.push(`${createdTime}: ${memory.pageContent.trim()}`);\n }\n const joinedContent = content.map((mem) => `${mem}`).join(\"\\n\");\n return joinedContent;\n }\n\n /**\n * Method that formats the given relevant memories in a simple manner.\n * @param relevantMemories The relevant memories to format.\n * @returns The formatted memories as a string.\n */\n formatMemoriesSimple(relevantMemories: Document[]): string {\n const joinedContent = relevantMemories\n .map((mem) => `${mem.pageContent}`)\n .join(\"; \");\n return joinedContent;\n }\n\n /**\n * Method that retrieves memories until a token limit is reached.\n * @param consumedTokens The number of tokens consumed so far.\n * @returns The memories as a string.\n */\n async getMemoriesUntilLimit(consumedTokens: number): Promise<string> {\n // reduce the number of tokens in the documents\n const result = [];\n for (const doc of this.memoryRetriever\n .getMemoryStream()\n .slice()\n .reverse()) {\n if (consumedTokens >= this.maxTokensLimit) {\n if (this.verbose) {\n console.log(\"Exceeding max tokens for LLM, filtering memories\");\n }\n break;\n }\n // oxlint-disable-next-line no-param-reassign\n consumedTokens += await this.llm.getNumTokens(doc.pageContent);\n if (consumedTokens < this.maxTokensLimit) {\n result.push(doc);\n }\n }\n return this.formatMemoriesSimple(result);\n }\n\n get memoryVariables(): string[] {\n // input keys this memory class will load dynamically\n return [];\n }\n\n /**\n * Method that loads memory variables based on the given inputs.\n * @param inputs The inputs to use for loading memory variables.\n * @returns An object containing the loaded memory variables.\n */\n async loadMemoryVariables(\n inputs: InputValues\n ): Promise<Record<string, string>> {\n const queries = inputs[this.queriesKey];\n const now = inputs[this.nowKey];\n if (queries !== undefined) {\n const relevantMemories = (\n await Promise.all(\n queries.map((query: string) =>\n this.memoryChain.fetchMemories(query, now)\n )\n )\n ).flat();\n return {\n [this.relevantMemoriesKey]: this.formatMemoriesDetail(relevantMemories),\n [this.relevantMemoriesSimpleKey]:\n this.formatMemoriesSimple(relevantMemories),\n };\n }\n const mostRecentMemoriesToken = inputs[this.mostRecentMemoriesTokenKey];\n if (mostRecentMemoriesToken !== undefined) {\n return {\n [this.mostRecentMemoriesKey]: await this.getMemoriesUntilLimit(\n mostRecentMemoriesToken\n ),\n };\n }\n return {};\n }\n\n /**\n * Method that saves the context of a model run to memory.\n * @param _inputs The inputs of the model run.\n * @param outputs The outputs of the model run.\n * @returns Nothing.\n */\n async saveContext(\n _inputs: InputValues,\n outputs: OutputValues\n ): Promise<void> {\n // save the context of this model run to memory\n const mem = outputs[this.addMemoryKey];\n const now = outputs[this.nowKey];\n if (mem) {\n await this.addMemory(mem, now, {});\n }\n }\n\n /**\n * Method that clears the memory contents.\n * @returns Nothing.\n */\n clear(): void {\n // TODO: clear memory contents\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,IAAM,6BAAN,MAAM,mCAAmC,UAAU;CACjD,OAAO,UAAU;AACf,SAAO;;CAGT,aAAa;CAEb;CAEA,mBAAmB;CAEnB;CAEA;CAEA,UAAU;CAEV,sBAA8B;CAE9B,YACE,KACA,iBACA,QACA;AACA,SAAO;AACP,OAAK,MAAM;AACX,OAAK,kBAAkB;AACvB,OAAK,sBAAsB,OAAO;AAClC,OAAK,mBAAmB,OAAO,oBAAoB,KAAK;AACxD,OAAK,UAAU,OAAO,WAAW,KAAK;;CAGxC,aAAqB;AACnB,SAAO;;CAGT,IAAI,YAAsB;AACxB,SAAO;GAAC;GAAkB;GAAO;GAAkB;;CAGrD,IAAI,aAAuB;AACzB,SAAO,CAAC,SAAS;;;;;;;CAQnB,MAAM,QAAkC;AAOtC,SANc,IAAI,SAAS;GACzB,KAAK,KAAK;GACV;GACA,SAAS,KAAK;GACd,WAAW;GACZ,CAAC;;CAIJ,MAAM,MAAM,QAAqB,YAAyC;EACxE,MAAM,EAAE,gBAAgB,eAAe,QAAQ;EAE/C,MAAM,kBAAkB,MAAM,KAAK,sBACjC,eACA,WACD;AACD,OAAK,uBAAuB;EAC5B,MAAM,WAAW,IAAI,S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,MAAM,KAAK,IAAI,aAAa,IAAI,YAAY;AAC9D,OAAI,iBAAiB,KAAK,eACxB,QAAO,KAAK,IAAI;;AAGpB,SAAO,KAAK,qBAAqB,OAAO;;CAG1C,IAAI,kBAA4B;AAE9B,SAAO,EAAE;;;;;;;CAQX,MAAM,oBACJ,QACiC;EACjC,MAAM,UAAU,OAAO,KAAK;EAC5B,MAAM,MAAM,OAAO,KAAK;AACxB,MAAI,YAAY,KAAA,GAAW;GACzB,MAAM,oBACJ,MAAM,QAAQ,IACZ,QAAQ,KAAK,UACX,KAAK,YAAY,cAAc,OAAO,IAAI,CAC3C,CACF,EACD,MAAM;AACR,UAAO;KACJ,KAAK,sBAAsB,KAAK,qBAAqB,iBAAiB;KACtE,KAAK,4BACJ,KAAK,qBAAqB,iBAAiB;IAC9C;;EAEH,MAAM,0BAA0B,OAAO,KAAK;AAC5C,MAAI,4BAA4B,KAAA,EAC9B,QAAO,GACJ,KAAK,wBAAwB,MAAM,KAAK,sBACvC,wBACD,EACF;AAEH,SAAO,EAAE;;;;;;;;CASX,MAAM,YACJ,SACA,SACe;EAEf,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,MAAM,QAAQ,KAAK;AACzB,MAAI,IACF,OAAM,KAAK,UAAU,KAAK,KAAK,EAAE,CAAC;;;;;;CAQtC,QAAc"}
|
|
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
|
|
3
3
|
const require_experimental_prompts_custom_format = require("./custom_format.cjs");
|
|
4
4
|
let handlebars = require("handlebars");
|
|
5
|
-
handlebars = require_runtime.__toESM(handlebars);
|
|
5
|
+
handlebars = require_runtime.__toESM(handlebars, 1);
|
|
6
6
|
//#region src/experimental/prompts/handlebars.ts
|
|
7
7
|
var handlebars_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
8
8
|
HandlebarsPromptTemplate: () => HandlebarsPromptTemplate,
|
|
@@ -3,7 +3,7 @@ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
|
3
3
|
const require_retrievers_multi_vector = require("./multi_vector.cjs");
|
|
4
4
|
let _langchain_core_documents = require("@langchain/core/documents");
|
|
5
5
|
let _langchain_core_utils_uuid = require("@langchain/core/utils/uuid");
|
|
6
|
-
_langchain_core_utils_uuid = require_runtime.__toESM(_langchain_core_utils_uuid);
|
|
6
|
+
_langchain_core_utils_uuid = require_runtime.__toESM(_langchain_core_utils_uuid, 1);
|
|
7
7
|
//#region src/retrievers/parent_document.ts
|
|
8
8
|
var parent_document_exports = /* @__PURE__ */ require_runtime.__exportAll({ ParentDocumentRetriever: () => ParentDocumentRetriever });
|
|
9
9
|
/**
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
node_path = require_runtime.__toESM(node_path);
|
|
4
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
5
5
|
let node_fs_promises = require("node:fs/promises");
|
|
6
|
-
node_fs_promises = require_runtime.__toESM(node_fs_promises);
|
|
6
|
+
node_fs_promises = require_runtime.__toESM(node_fs_promises, 1);
|
|
7
7
|
let _langchain_core_stores = require("@langchain/core/stores");
|
|
8
8
|
//#region src/storage/file_system.ts
|
|
9
9
|
var file_system_exports = /* @__PURE__ */ require_runtime.__exportAll({ LocalFileStore: () => LocalFileStore });
|
|
@@ -3,7 +3,7 @@ const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
|
|
|
3
3
|
const require_base = require("./base.cjs");
|
|
4
4
|
let node_path = require("node:path");
|
|
5
5
|
let node_fs_promises = require("node:fs/promises");
|
|
6
|
-
node_fs_promises = require_runtime.__toESM(node_fs_promises);
|
|
6
|
+
node_fs_promises = require_runtime.__toESM(node_fs_promises, 1);
|
|
7
7
|
let node_fs = require("node:fs");
|
|
8
8
|
//#region src/stores/file/node.ts
|
|
9
9
|
var node_exports = /* @__PURE__ */ require_runtime.__exportAll({ NodeFileStore: () => NodeFileStore });
|
package/dist/tools/json.cjs
CHANGED
|
@@ -2,7 +2,7 @@ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
|
2
2
|
let _langchain_core_load_serializable = require("@langchain/core/load/serializable");
|
|
3
3
|
let _langchain_core_tools = require("@langchain/core/tools");
|
|
4
4
|
let jsonpointer = require("jsonpointer");
|
|
5
|
-
jsonpointer = require_runtime.__toESM(jsonpointer);
|
|
5
|
+
jsonpointer = require_runtime.__toESM(jsonpointer, 1);
|
|
6
6
|
//#region src/tools/json.ts
|
|
7
7
|
/**
|
|
8
8
|
* Represents a JSON object in the LangChain framework. Provides methods
|
|
@@ -8,7 +8,7 @@ let _langchain_core_output_parsers = require("@langchain/core/output_parsers");
|
|
|
8
8
|
let _langchain_textsplitters = require("@langchain/textsplitters");
|
|
9
9
|
let _langchain_core_documents = require("@langchain/core/documents");
|
|
10
10
|
let cheerio = require("cheerio");
|
|
11
|
-
cheerio = require_runtime.__toESM(cheerio);
|
|
11
|
+
cheerio = require_runtime.__toESM(cheerio, 1);
|
|
12
12
|
//#region src/tools/webbrowser.ts
|
|
13
13
|
var webbrowser_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
14
14
|
WebBrowser: () => WebBrowser,
|
package/dist/util/openapi.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
let js_yaml = require("js-yaml");
|
|
3
|
-
js_yaml = require_runtime.__toESM(js_yaml);
|
|
3
|
+
js_yaml = require_runtime.__toESM(js_yaml, 1);
|
|
4
4
|
//#region src/util/openapi.ts
|
|
5
5
|
var OpenAPISpec = class OpenAPISpec {
|
|
6
6
|
constructor(document) {
|
package/dist/util/parse.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
const require_extname = require("./extname.cjs");
|
|
3
3
|
let yaml = require("yaml");
|
|
4
|
-
yaml = require_runtime.__toESM(yaml);
|
|
4
|
+
yaml = require_runtime.__toESM(yaml, 1);
|
|
5
5
|
//#region src/util/parse.ts
|
|
6
6
|
const loadFileContents = (contents, format) => {
|
|
7
7
|
switch (format) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/classic",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.34",
|
|
4
4
|
"description": "Old abstractions from LangChain.js",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -99,21 +99,21 @@
|
|
|
99
99
|
"@azure/identity": "^4.12.0",
|
|
100
100
|
"@browserbasehq/stagehand": "^1.3.0",
|
|
101
101
|
"@clickhouse/client": "^0.2.5",
|
|
102
|
-
"@cloudflare/workers-types": "^4.
|
|
102
|
+
"@cloudflare/workers-types": "^4.20260508.1",
|
|
103
103
|
"@elastic/elasticsearch": "^8.4.0",
|
|
104
104
|
"@faker-js/faker": "^10.4.0",
|
|
105
105
|
"@getmetal/metal-sdk": "^7.7.1",
|
|
106
106
|
"@getzep/zep-cloud": "^1.0.12",
|
|
107
107
|
"@getzep/zep-js": "^2.0.2",
|
|
108
108
|
"@gomomento/sdk": "1.117.2",
|
|
109
|
-
"@google/generative-ai": "^0.
|
|
110
|
-
"@lancedb/lancedb": "^0.
|
|
109
|
+
"@google/generative-ai": "^0.24.1",
|
|
110
|
+
"@lancedb/lancedb": "^0.26.2",
|
|
111
111
|
"@langchain/langgraph": "1.0.0-alpha.5",
|
|
112
112
|
"@layerup/layerup-security": "^1.5.12",
|
|
113
113
|
"@opensearch-project/opensearch": "^2.2.0",
|
|
114
114
|
"@pinecone-database/pinecone": "^5.0.2",
|
|
115
115
|
"@planetscale/database": "^1.20.1",
|
|
116
|
-
"@prisma/client": "^
|
|
116
|
+
"@prisma/client": "^6.19.3",
|
|
117
117
|
"@qdrant/js-client-rest": "^1.17.0",
|
|
118
118
|
"@rockset/client": "^0.9.1",
|
|
119
119
|
"@supabase/supabase-js": "^2.53.0",
|
|
@@ -122,14 +122,13 @@
|
|
|
122
122
|
"@types/js-yaml": "^4",
|
|
123
123
|
"@types/jsdom": "^28.0.1",
|
|
124
124
|
"@types/pg": "^8.15.5",
|
|
125
|
-
"@types/uuid": "^9",
|
|
126
125
|
"@types/ws": "^8",
|
|
127
126
|
"@upstash/redis": "^1.37.0",
|
|
128
127
|
"@upstash/vector": "^1.2.2",
|
|
129
128
|
"@vercel/kv": "^3.0.0",
|
|
130
129
|
"@vitest/coverage-v8": "^3.2.4",
|
|
131
130
|
"@xata.io/client": "^0.30.1",
|
|
132
|
-
"@zilliz/milvus2-sdk-node": "^2.
|
|
131
|
+
"@zilliz/milvus2-sdk-node": "^2.6.14",
|
|
133
132
|
"axios": "^1.15.0",
|
|
134
133
|
"cheerio": "1.2.0",
|
|
135
134
|
"chromadb": "^1.5.3",
|
|
@@ -139,7 +138,7 @@
|
|
|
139
138
|
"dotenv": "^17.4.0",
|
|
140
139
|
"dpdm": "^3.14.0",
|
|
141
140
|
"duck-duck-scrape": "^2.2.5",
|
|
142
|
-
"exa-js": "^1.
|
|
141
|
+
"exa-js": "^1.10.3",
|
|
143
142
|
"firebase-admin": "^13.7.0",
|
|
144
143
|
"graphql": "^16.6.0",
|
|
145
144
|
"hdb": "^0.19.8",
|
|
@@ -148,9 +147,9 @@
|
|
|
148
147
|
"lorem-ipsum": "^2.0.8",
|
|
149
148
|
"lunary": "^0.8.8",
|
|
150
149
|
"mariadb": "^3.5.1",
|
|
151
|
-
"mem0ai": "^
|
|
150
|
+
"mem0ai": "^3.0.3",
|
|
152
151
|
"mongodb": "^6.17.0",
|
|
153
|
-
"openai": "^6.
|
|
152
|
+
"openai": "^6.37.0",
|
|
154
153
|
"peggy": "^5.1.0",
|
|
155
154
|
"pg": "^8.16.3",
|
|
156
155
|
"pickleparser": "^0.2.1",
|
|
@@ -165,35 +164,35 @@
|
|
|
165
164
|
"typesense": "^3.0.5",
|
|
166
165
|
"vitest": "^4.1.2",
|
|
167
166
|
"voy-search": "0.6.3",
|
|
168
|
-
"weaviate-client": "^3.
|
|
167
|
+
"weaviate-client": "^3.13.0",
|
|
169
168
|
"zod-to-json-schema": "^3.25.2",
|
|
170
|
-
"@langchain/anthropic": "1.
|
|
171
|
-
"@langchain/aws": "1.3.
|
|
172
|
-
"@langchain/cloudflare": "1.0.
|
|
173
|
-
"@langchain/core": "^1.1.
|
|
174
|
-
"@langchain/deepseek": "1.0.
|
|
175
|
-
"@langchain/fireworks": "0.1.
|
|
169
|
+
"@langchain/anthropic": "1.4.0",
|
|
170
|
+
"@langchain/aws": "1.3.9",
|
|
171
|
+
"@langchain/cloudflare": "1.0.6",
|
|
172
|
+
"@langchain/core": "^1.1.48",
|
|
173
|
+
"@langchain/deepseek": "1.0.27",
|
|
174
|
+
"@langchain/fireworks": "0.1.5",
|
|
176
175
|
"@langchain/google-cloud-sql-pg": "1.0.23",
|
|
177
|
-
"@langchain/google-common": "2.1.
|
|
178
|
-
"@langchain/google-genai": "2.1.
|
|
179
|
-
"@langchain/google-vertexai": "2.1.
|
|
180
|
-
"@langchain/google-vertexai-web": "2.1.
|
|
181
|
-
"@langchain/groq": "1.2.
|
|
182
|
-
"@langchain/mistralai": "1.0
|
|
183
|
-
"@langchain/mongodb": "1.
|
|
176
|
+
"@langchain/google-common": "2.1.31",
|
|
177
|
+
"@langchain/google-genai": "2.1.31",
|
|
178
|
+
"@langchain/google-vertexai": "2.1.31",
|
|
179
|
+
"@langchain/google-vertexai-web": "2.1.31",
|
|
180
|
+
"@langchain/groq": "1.2.1",
|
|
181
|
+
"@langchain/mistralai": "1.1.0",
|
|
182
|
+
"@langchain/mongodb": "1.2.1",
|
|
184
183
|
"@langchain/ollama": "1.2.7",
|
|
185
|
-
"@langchain/redis": "1.1.
|
|
184
|
+
"@langchain/redis": "1.1.3",
|
|
186
185
|
"@langchain/textsplitters": "1.0.1",
|
|
187
|
-
"@langchain/xai": "1.3.
|
|
186
|
+
"@langchain/xai": "1.3.19",
|
|
188
187
|
"@langchain/tsconfig": "0.0.1",
|
|
189
|
-
"langchain": "1.
|
|
190
|
-
"@langchain/together-ai": "0.1.
|
|
188
|
+
"langchain": "1.4.2",
|
|
189
|
+
"@langchain/together-ai": "0.1.5"
|
|
191
190
|
},
|
|
192
191
|
"peerDependencies": {
|
|
193
|
-
"@langchain/core": "^1.0.0",
|
|
194
192
|
"cheerio": "*",
|
|
195
193
|
"peggy": "^5.1.0",
|
|
196
|
-
"typeorm": "*"
|
|
194
|
+
"typeorm": "*",
|
|
195
|
+
"@langchain/core": "^1.1.48"
|
|
197
196
|
},
|
|
198
197
|
"peerDependenciesMeta": {
|
|
199
198
|
"cheerio": {
|
|
@@ -213,7 +212,7 @@
|
|
|
213
212
|
"openapi-types": "^12.1.3",
|
|
214
213
|
"yaml": "^2.8.3",
|
|
215
214
|
"zod": "^3.25.76 || ^4",
|
|
216
|
-
"@langchain/openai": "1.4.
|
|
215
|
+
"@langchain/openai": "1.4.7",
|
|
217
216
|
"@langchain/textsplitters": "1.0.1"
|
|
218
217
|
},
|
|
219
218
|
"optionalDependencies": {
|