langchain 0.0.93 → 0.0.95

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.
Files changed (43) hide show
  1. package/dist/agents/agent.cjs +3 -0
  2. package/dist/agents/agent.d.ts +1 -1
  3. package/dist/agents/agent.js +3 -0
  4. package/dist/agents/index.cjs +3 -1
  5. package/dist/agents/index.d.ts +1 -0
  6. package/dist/agents/index.js +1 -0
  7. package/dist/agents/initialize.cjs +18 -0
  8. package/dist/agents/initialize.d.ts +6 -2
  9. package/dist/agents/initialize.js +18 -0
  10. package/dist/agents/openai/index.cjs +119 -0
  11. package/dist/agents/openai/index.d.ts +26 -0
  12. package/dist/agents/openai/index.js +115 -0
  13. package/dist/agents/openai/prompt.cjs +5 -0
  14. package/dist/agents/openai/prompt.d.ts +2 -0
  15. package/dist/agents/openai/prompt.js +2 -0
  16. package/dist/agents/types.d.ts +1 -1
  17. package/dist/chains/base.cjs +3 -2
  18. package/dist/chains/base.js +3 -2
  19. package/dist/chains/combine_docs_chain.cjs +17 -10
  20. package/dist/chains/combine_docs_chain.d.ts +4 -2
  21. package/dist/chains/combine_docs_chain.js +17 -10
  22. package/dist/chains/serde.d.ts +1 -1
  23. package/dist/chat_models/openai.cjs +33 -10
  24. package/dist/chat_models/openai.d.ts +13 -3
  25. package/dist/chat_models/openai.js +33 -10
  26. package/dist/llms/openai-chat.d.ts +4 -0
  27. package/dist/load/import_constants.cjs +1 -0
  28. package/dist/load/import_constants.js +1 -0
  29. package/dist/schema/index.cjs +22 -2
  30. package/dist/schema/index.d.ts +9 -2
  31. package/dist/schema/index.js +20 -1
  32. package/dist/stores/message/utils.cjs +2 -1
  33. package/dist/stores/message/utils.js +2 -1
  34. package/dist/tools/convert_to_openai.cjs +12 -0
  35. package/dist/tools/convert_to_openai.d.ts +3 -0
  36. package/dist/tools/convert_to_openai.js +8 -0
  37. package/dist/vectorstores/typesense.cjs +216 -0
  38. package/dist/vectorstores/typesense.d.ts +124 -0
  39. package/dist/vectorstores/typesense.js +212 -0
  40. package/package.json +15 -2
  41. package/vectorstores/typesense.cjs +1 -0
  42. package/vectorstores/typesense.d.ts +1 -0
  43. package/vectorstores/typesense.js +1 -0
@@ -209,6 +209,9 @@ class Agent extends BaseSingleActionAgent {
209
209
  newInputs.stop = this._stop();
210
210
  }
211
211
  const output = await this.llmChain.predict(newInputs, callbackManager);
212
+ if (!this.outputParser) {
213
+ throw new Error("Output parser not set");
214
+ }
212
215
  return this.outputParser.parse(output, callbackManager);
213
216
  }
214
217
  /**
@@ -95,7 +95,7 @@ export interface AgentArgs {
95
95
  */
96
96
  export declare abstract class Agent extends BaseSingleActionAgent {
97
97
  llmChain: LLMChain;
98
- outputParser: AgentActionOutputParser;
98
+ outputParser: AgentActionOutputParser | undefined;
99
99
  private _allowedTools?;
100
100
  get allowedTools(): string[] | undefined;
101
101
  get inputKeys(): string[];
@@ -202,6 +202,9 @@ export class Agent extends BaseSingleActionAgent {
202
202
  newInputs.stop = this._stop();
203
203
  }
204
204
  const output = await this.llmChain.predict(newInputs, callbackManager);
205
+ if (!this.outputParser) {
206
+ throw new Error("Output parser not set");
207
+ }
205
208
  return this.outputParser.parse(output, callbackManager);
206
209
  }
207
210
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StructuredChatOutputParserWithRetries = exports.StructuredChatOutputParser = exports.StructuredChatAgent = exports.AgentActionOutputParser = exports.ZeroShotAgentOutputParser = exports.ZeroShotAgent = exports.initializeAgentExecutorWithOptions = exports.initializeAgentExecutor = exports.AgentExecutor = exports.ChatConversationalAgentOutputParserWithRetries = exports.ChatConversationalAgentOutputParser = exports.ChatConversationalAgent = exports.ChatAgentOutputParser = exports.ChatAgent = exports.Toolkit = exports.createVectorStoreRouterAgent = exports.createVectorStoreAgent = exports.createSqlAgent = exports.createOpenApiAgent = exports.createJsonAgent = exports.ZapierToolKit = exports.VectorStoreToolkit = exports.VectorStoreRouterToolkit = exports.SqlToolkit = exports.RequestsToolkit = exports.OpenApiToolkit = exports.JsonToolkit = exports.LLMSingleActionAgent = exports.BaseSingleActionAgent = exports.Agent = void 0;
3
+ exports.OpenAIAgent = exports.StructuredChatOutputParserWithRetries = exports.StructuredChatOutputParser = exports.StructuredChatAgent = exports.AgentActionOutputParser = exports.ZeroShotAgentOutputParser = exports.ZeroShotAgent = exports.initializeAgentExecutorWithOptions = exports.initializeAgentExecutor = exports.AgentExecutor = exports.ChatConversationalAgentOutputParserWithRetries = exports.ChatConversationalAgentOutputParser = exports.ChatConversationalAgent = exports.ChatAgentOutputParser = exports.ChatAgent = exports.Toolkit = exports.createVectorStoreRouterAgent = exports.createVectorStoreAgent = exports.createSqlAgent = exports.createOpenApiAgent = exports.createJsonAgent = exports.ZapierToolKit = exports.VectorStoreToolkit = exports.VectorStoreRouterToolkit = exports.SqlToolkit = exports.RequestsToolkit = exports.OpenApiToolkit = exports.JsonToolkit = exports.LLMSingleActionAgent = exports.BaseSingleActionAgent = exports.Agent = void 0;
4
4
  var agent_js_1 = require("./agent.cjs");
5
5
  Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_js_1.Agent; } });
6
6
  Object.defineProperty(exports, "BaseSingleActionAgent", { enumerable: true, get: function () { return agent_js_1.BaseSingleActionAgent; } });
@@ -45,3 +45,5 @@ Object.defineProperty(exports, "StructuredChatAgent", { enumerable: true, get: f
45
45
  var outputParser_js_4 = require("./structured_chat/outputParser.cjs");
46
46
  Object.defineProperty(exports, "StructuredChatOutputParser", { enumerable: true, get: function () { return outputParser_js_4.StructuredChatOutputParser; } });
47
47
  Object.defineProperty(exports, "StructuredChatOutputParserWithRetries", { enumerable: true, get: function () { return outputParser_js_4.StructuredChatOutputParserWithRetries; } });
48
+ var index_js_6 = require("./openai/index.cjs");
49
+ Object.defineProperty(exports, "OpenAIAgent", { enumerable: true, get: function () { return index_js_6.OpenAIAgent; } });
@@ -12,3 +12,4 @@ export { ZeroShotAgentOutputParser } from "./mrkl/outputParser.js";
12
12
  export { AgentActionOutputParser, AgentInput, SerializedAgent, SerializedAgentT, SerializedZeroShotAgent, StoppingMethod, } from "./types.js";
13
13
  export { StructuredChatAgent, StructuredChatAgentInput, StructuredChatCreatePromptArgs, } from "./structured_chat/index.js";
14
14
  export { StructuredChatOutputParser, StructuredChatOutputParserArgs, StructuredChatOutputParserWithRetries, } from "./structured_chat/outputParser.js";
15
+ export { OpenAIAgent, OpenAIAgentInput, OpenAIAgentCreatePromptArgs, } from "./openai/index.js";
@@ -12,3 +12,4 @@ export { ZeroShotAgentOutputParser } from "./mrkl/outputParser.js";
12
12
  export { AgentActionOutputParser, } from "./types.js";
13
13
  export { StructuredChatAgent, } from "./structured_chat/index.js";
14
14
  export { StructuredChatOutputParser, StructuredChatOutputParserWithRetries, } from "./structured_chat/outputParser.js";
15
+ export { OpenAIAgent, } from "./openai/index.js";
@@ -7,6 +7,7 @@ const index_js_2 = require("./chat_convo/index.cjs");
7
7
  const index_js_3 = require("./structured_chat/index.cjs");
8
8
  const executor_js_1 = require("./executor.cjs");
9
9
  const index_js_4 = require("./mrkl/index.cjs");
10
+ const index_js_5 = require("./openai/index.cjs");
10
11
  /**
11
12
  * @deprecated use initializeAgentExecutorWithOptions instead
12
13
  */
@@ -78,6 +79,7 @@ async function initializeAgentExecutorWithOptions(tools, llm, options = {
78
79
  returnMessages: true,
79
80
  memoryKey: "chat_history",
80
81
  inputKey: "input",
82
+ outputKey: "output",
81
83
  }),
82
84
  ...rest,
83
85
  });
@@ -93,6 +95,22 @@ async function initializeAgentExecutorWithOptions(tools, llm, options = {
93
95
  });
94
96
  return executor;
95
97
  }
98
+ case "openai-functions": {
99
+ const { agentArgs, memory, ...rest } = options;
100
+ const executor = executor_js_1.AgentExecutor.fromAgentAndTools({
101
+ agent: index_js_5.OpenAIAgent.fromLLMAndTools(llm, tools, agentArgs),
102
+ tools,
103
+ memory: memory ??
104
+ new buffer_memory_js_1.BufferMemory({
105
+ returnMessages: true,
106
+ memoryKey: "chat_history",
107
+ inputKey: "input",
108
+ outputKey: "output",
109
+ }),
110
+ ...rest,
111
+ });
112
+ return executor;
113
+ }
96
114
  default: {
97
115
  throw new Error("Unknown agent type");
98
116
  }
@@ -6,6 +6,7 @@ import { ChatConversationalAgent } from "./chat_convo/index.js";
6
6
  import { StructuredChatAgent } from "./structured_chat/index.js";
7
7
  import { AgentExecutor, AgentExecutorInput } from "./executor.js";
8
8
  import { ZeroShotAgent } from "./mrkl/index.js";
9
+ import { OpenAIAgent } from "./openai/index.js";
9
10
  type AgentType = "zero-shot-react-description" | "chat-zero-shot-react-description" | "chat-conversational-react-description";
10
11
  /**
11
12
  * @deprecated use initializeAgentExecutorWithOptions instead
@@ -29,10 +30,13 @@ export type InitializeAgentExecutorOptions = ({
29
30
  /**
30
31
  * @interface
31
32
  */
32
- export type InitializeAgentExecutorOptionsStructured = {
33
+ export type InitializeAgentExecutorOptionsStructured = ({
33
34
  agentType: "structured-chat-zero-shot-react-description";
34
35
  agentArgs?: Parameters<typeof StructuredChatAgent.fromLLMAndTools>[2];
35
- } & Omit<AgentExecutorInput, "agent" | "tools">;
36
+ } & Omit<AgentExecutorInput, "agent" | "tools">) | ({
37
+ agentType: "openai-functions";
38
+ agentArgs?: Parameters<typeof OpenAIAgent.fromLLMAndTools>[2];
39
+ } & Omit<AgentExecutorInput, "agent" | "tools">);
36
40
  /**
37
41
  * Initialize an agent executor with options
38
42
  * @param tools Array of tools to use in the agent
@@ -4,6 +4,7 @@ import { ChatConversationalAgent } from "./chat_convo/index.js";
4
4
  import { StructuredChatAgent } from "./structured_chat/index.js";
5
5
  import { AgentExecutor } from "./executor.js";
6
6
  import { ZeroShotAgent } from "./mrkl/index.js";
7
+ import { OpenAIAgent } from "./openai/index.js";
7
8
  /**
8
9
  * @deprecated use initializeAgentExecutorWithOptions instead
9
10
  */
@@ -74,6 +75,7 @@ export async function initializeAgentExecutorWithOptions(tools, llm, options = {
74
75
  returnMessages: true,
75
76
  memoryKey: "chat_history",
76
77
  inputKey: "input",
78
+ outputKey: "output",
77
79
  }),
78
80
  ...rest,
79
81
  });
@@ -89,6 +91,22 @@ export async function initializeAgentExecutorWithOptions(tools, llm, options = {
89
91
  });
90
92
  return executor;
91
93
  }
94
+ case "openai-functions": {
95
+ const { agentArgs, memory, ...rest } = options;
96
+ const executor = AgentExecutor.fromAgentAndTools({
97
+ agent: OpenAIAgent.fromLLMAndTools(llm, tools, agentArgs),
98
+ tools,
99
+ memory: memory ??
100
+ new BufferMemory({
101
+ returnMessages: true,
102
+ memoryKey: "chat_history",
103
+ inputKey: "input",
104
+ outputKey: "output",
105
+ }),
106
+ ...rest,
107
+ });
108
+ return executor;
109
+ }
92
110
  default: {
93
111
  throw new Error("Unknown agent type");
94
112
  }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpenAIAgent = void 0;
4
+ const index_js_1 = require("../../schema/index.cjs");
5
+ const agent_js_1 = require("../agent.cjs");
6
+ const prompt_js_1 = require("./prompt.cjs");
7
+ const chat_js_1 = require("../../prompts/chat.cjs");
8
+ const llm_chain_js_1 = require("../../chains/llm_chain.cjs");
9
+ function parseOutput(message) {
10
+ if (message.additional_kwargs.function_call) {
11
+ // eslint-disable-next-line prefer-destructuring
12
+ const function_call = message.additional_kwargs.function_call;
13
+ return {
14
+ tool: function_call.name,
15
+ toolInput: function_call.arguments
16
+ ? JSON.parse(function_call.arguments)
17
+ : {},
18
+ log: message.text,
19
+ };
20
+ }
21
+ else {
22
+ return { returnValues: { output: message.text }, log: message.text };
23
+ }
24
+ }
25
+ class OpenAIAgent extends agent_js_1.Agent {
26
+ _agentType() {
27
+ return "openai-functions";
28
+ }
29
+ observationPrefix() {
30
+ return "Observation: ";
31
+ }
32
+ llmPrefix() {
33
+ return "Thought:";
34
+ }
35
+ _stop() {
36
+ return ["Observation:"];
37
+ }
38
+ constructor(input) {
39
+ super({ ...input, outputParser: undefined });
40
+ Object.defineProperty(this, "lc_namespace", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: ["langchain", "agents", "openai"]
45
+ });
46
+ Object.defineProperty(this, "tools", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: void 0
51
+ });
52
+ this.tools = input.tools;
53
+ }
54
+ static createPrompt(_tools, fields) {
55
+ const { prefix = prompt_js_1.PREFIX } = fields || {};
56
+ return chat_js_1.ChatPromptTemplate.fromPromptMessages([
57
+ chat_js_1.SystemMessagePromptTemplate.fromTemplate(prefix),
58
+ new chat_js_1.MessagesPlaceholder("chat_history"),
59
+ chat_js_1.HumanMessagePromptTemplate.fromTemplate("{input}"),
60
+ new chat_js_1.MessagesPlaceholder("agent_scratchpad"),
61
+ ]);
62
+ }
63
+ static fromLLMAndTools(llm, tools, args) {
64
+ OpenAIAgent.validateTools(tools);
65
+ if (llm._modelType() !== "base_chat_model" || llm._llmType() !== "openai") {
66
+ throw new Error("OpenAIAgent requires an OpenAI chat model");
67
+ }
68
+ const prompt = OpenAIAgent.createPrompt(tools, args);
69
+ const chain = new llm_chain_js_1.LLMChain({
70
+ prompt,
71
+ llm,
72
+ callbacks: args?.callbacks,
73
+ });
74
+ return new OpenAIAgent({
75
+ llmChain: chain,
76
+ allowedTools: tools.map((t) => t.name),
77
+ tools,
78
+ });
79
+ }
80
+ async constructScratchPad(steps) {
81
+ return steps.flatMap(({ action, observation }) => [
82
+ new index_js_1.AIChatMessage("", {
83
+ function_call: {
84
+ name: action.tool,
85
+ arguments: JSON.stringify(action.toolInput),
86
+ },
87
+ }),
88
+ new index_js_1.FunctionChatMessage(observation, action.tool),
89
+ ]);
90
+ }
91
+ async plan(steps, inputs, callbackManager) {
92
+ // Add scratchpad and stop to inputs
93
+ const thoughts = await this.constructScratchPad(steps);
94
+ const newInputs = {
95
+ ...inputs,
96
+ agent_scratchpad: thoughts,
97
+ };
98
+ if (this._stop().length !== 0) {
99
+ newInputs.stop = this._stop();
100
+ }
101
+ // Split inputs between prompt and llm
102
+ const llm = this.llmChain.llm;
103
+ const valuesForPrompt = { ...newInputs };
104
+ const valuesForLLM = {
105
+ tools: this.tools,
106
+ };
107
+ for (const key of this.llmChain.llm.callKeys) {
108
+ if (key in inputs) {
109
+ valuesForLLM[key] = inputs[key];
110
+ delete valuesForPrompt[key];
111
+ }
112
+ }
113
+ const promptValue = await this.llmChain.prompt.formatPromptValue(valuesForPrompt);
114
+ const message = await llm.predictMessages(promptValue.toChatMessages(), valuesForLLM, callbackManager);
115
+ console.log("message", message);
116
+ return parseOutput(message);
117
+ }
118
+ }
119
+ exports.OpenAIAgent = OpenAIAgent;
@@ -0,0 +1,26 @@
1
+ import { CallbackManager } from "../../callbacks/manager.js";
2
+ import { BasePromptTemplate } from "../../prompts/base.js";
3
+ import { AgentAction, AgentFinish, AgentStep, BaseChatMessage, ChainValues } from "../../schema/index.js";
4
+ import { StructuredTool } from "../../tools/base.js";
5
+ import { Agent, AgentArgs } from "../agent.js";
6
+ import { AgentInput } from "../types.js";
7
+ import { BaseLanguageModel } from "../../base_language/index.js";
8
+ export interface OpenAIAgentInput extends AgentInput {
9
+ tools: StructuredTool[];
10
+ }
11
+ export interface OpenAIAgentCreatePromptArgs {
12
+ prefix?: string;
13
+ }
14
+ export declare class OpenAIAgent extends Agent {
15
+ lc_namespace: string[];
16
+ _agentType(): "openai-functions";
17
+ observationPrefix(): string;
18
+ llmPrefix(): string;
19
+ _stop(): string[];
20
+ tools: StructuredTool[];
21
+ constructor(input: Omit<OpenAIAgentInput, "outputParser">);
22
+ static createPrompt(_tools: StructuredTool[], fields?: OpenAIAgentCreatePromptArgs): BasePromptTemplate;
23
+ static fromLLMAndTools(llm: BaseLanguageModel, tools: StructuredTool[], args?: OpenAIAgentCreatePromptArgs & Pick<AgentArgs, "callbacks">): OpenAIAgent;
24
+ constructScratchPad(steps: AgentStep[]): Promise<string | BaseChatMessage[]>;
25
+ plan(steps: Array<AgentStep>, inputs: ChainValues, callbackManager?: CallbackManager): Promise<AgentAction | AgentFinish>;
26
+ }
@@ -0,0 +1,115 @@
1
+ import { AIChatMessage, FunctionChatMessage, } from "../../schema/index.js";
2
+ import { Agent } from "../agent.js";
3
+ import { PREFIX } from "./prompt.js";
4
+ import { ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, } from "../../prompts/chat.js";
5
+ import { LLMChain } from "../../chains/llm_chain.js";
6
+ function parseOutput(message) {
7
+ if (message.additional_kwargs.function_call) {
8
+ // eslint-disable-next-line prefer-destructuring
9
+ const function_call = message.additional_kwargs.function_call;
10
+ return {
11
+ tool: function_call.name,
12
+ toolInput: function_call.arguments
13
+ ? JSON.parse(function_call.arguments)
14
+ : {},
15
+ log: message.text,
16
+ };
17
+ }
18
+ else {
19
+ return { returnValues: { output: message.text }, log: message.text };
20
+ }
21
+ }
22
+ export class OpenAIAgent extends Agent {
23
+ _agentType() {
24
+ return "openai-functions";
25
+ }
26
+ observationPrefix() {
27
+ return "Observation: ";
28
+ }
29
+ llmPrefix() {
30
+ return "Thought:";
31
+ }
32
+ _stop() {
33
+ return ["Observation:"];
34
+ }
35
+ constructor(input) {
36
+ super({ ...input, outputParser: undefined });
37
+ Object.defineProperty(this, "lc_namespace", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: ["langchain", "agents", "openai"]
42
+ });
43
+ Object.defineProperty(this, "tools", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ this.tools = input.tools;
50
+ }
51
+ static createPrompt(_tools, fields) {
52
+ const { prefix = PREFIX } = fields || {};
53
+ return ChatPromptTemplate.fromPromptMessages([
54
+ SystemMessagePromptTemplate.fromTemplate(prefix),
55
+ new MessagesPlaceholder("chat_history"),
56
+ HumanMessagePromptTemplate.fromTemplate("{input}"),
57
+ new MessagesPlaceholder("agent_scratchpad"),
58
+ ]);
59
+ }
60
+ static fromLLMAndTools(llm, tools, args) {
61
+ OpenAIAgent.validateTools(tools);
62
+ if (llm._modelType() !== "base_chat_model" || llm._llmType() !== "openai") {
63
+ throw new Error("OpenAIAgent requires an OpenAI chat model");
64
+ }
65
+ const prompt = OpenAIAgent.createPrompt(tools, args);
66
+ const chain = new LLMChain({
67
+ prompt,
68
+ llm,
69
+ callbacks: args?.callbacks,
70
+ });
71
+ return new OpenAIAgent({
72
+ llmChain: chain,
73
+ allowedTools: tools.map((t) => t.name),
74
+ tools,
75
+ });
76
+ }
77
+ async constructScratchPad(steps) {
78
+ return steps.flatMap(({ action, observation }) => [
79
+ new AIChatMessage("", {
80
+ function_call: {
81
+ name: action.tool,
82
+ arguments: JSON.stringify(action.toolInput),
83
+ },
84
+ }),
85
+ new FunctionChatMessage(observation, action.tool),
86
+ ]);
87
+ }
88
+ async plan(steps, inputs, callbackManager) {
89
+ // Add scratchpad and stop to inputs
90
+ const thoughts = await this.constructScratchPad(steps);
91
+ const newInputs = {
92
+ ...inputs,
93
+ agent_scratchpad: thoughts,
94
+ };
95
+ if (this._stop().length !== 0) {
96
+ newInputs.stop = this._stop();
97
+ }
98
+ // Split inputs between prompt and llm
99
+ const llm = this.llmChain.llm;
100
+ const valuesForPrompt = { ...newInputs };
101
+ const valuesForLLM = {
102
+ tools: this.tools,
103
+ };
104
+ for (const key of this.llmChain.llm.callKeys) {
105
+ if (key in inputs) {
106
+ valuesForLLM[key] = inputs[key];
107
+ delete valuesForPrompt[key];
108
+ }
109
+ }
110
+ const promptValue = await this.llmChain.prompt.formatPromptValue(valuesForPrompt);
111
+ const message = await llm.predictMessages(promptValue.toChatMessages(), valuesForLLM, callbackManager);
112
+ console.log("message", message);
113
+ return parseOutput(message);
114
+ }
115
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SUFFIX = exports.PREFIX = void 0;
4
+ exports.PREFIX = `You are a helpful AI assistant.`;
5
+ exports.SUFFIX = ``;
@@ -0,0 +1,2 @@
1
+ export declare const PREFIX = "You are a helpful AI assistant.";
2
+ export declare const SUFFIX = "";
@@ -0,0 +1,2 @@
1
+ export const PREFIX = `You are a helpful AI assistant.`;
2
+ export const SUFFIX = ``;
@@ -4,7 +4,7 @@ import { AgentAction, AgentFinish } from "../schema/index.js";
4
4
  import { BaseOutputParser } from "../schema/output_parser.js";
5
5
  export interface AgentInput {
6
6
  llmChain: LLMChain;
7
- outputParser: AgentActionOutputParser;
7
+ outputParser: AgentActionOutputParser | undefined;
8
8
  allowedTools?: string[];
9
9
  }
10
10
  export declare abstract class AgentActionOutputParser extends BaseOutputParser<AgentAction | AgentFinish> {
@@ -39,11 +39,12 @@ class BaseChain extends index_js_2.BaseLangChain {
39
39
  async run(
40
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
41
  input, callbacks) {
42
- const isKeylessInput = this.inputKeys.length <= 1;
42
+ const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true);
43
+ const isKeylessInput = inputKeys.length <= 1;
43
44
  if (!isKeylessInput) {
44
45
  throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);
45
46
  }
46
- const values = this.inputKeys.length ? { [this.inputKeys[0]]: input } : {};
47
+ const values = inputKeys.length ? { [inputKeys[0]]: input } : {};
47
48
  const returnValues = await this.call(values, callbacks);
48
49
  const keys = Object.keys(returnValues);
49
50
  if (keys.length === 1) {
@@ -36,11 +36,12 @@ export class BaseChain extends BaseLangChain {
36
36
  async run(
37
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
38
  input, callbacks) {
39
- const isKeylessInput = this.inputKeys.length <= 1;
39
+ const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true);
40
+ const isKeylessInput = inputKeys.length <= 1;
40
41
  if (!isKeylessInput) {
41
42
  throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);
42
43
  }
43
- const values = this.inputKeys.length ? { [this.inputKeys[0]]: input } : {};
44
+ const values = inputKeys.length ? { [inputKeys[0]]: input } : {};
44
45
  const returnValues = await this.call(values, callbacks);
45
46
  const keys = Object.keys(returnValues);
46
47
  if (keys.length === 1) {
@@ -42,17 +42,21 @@ class StuffDocumentsChain extends base_js_1.BaseChain {
42
42
  this.inputKey = fields.inputKey ?? this.inputKey;
43
43
  }
44
44
  /** @ignore */
45
- async _call(values, runManager) {
45
+ _prepInputs(values) {
46
46
  if (!(this.inputKey in values)) {
47
47
  throw new Error(`Document key ${this.inputKey} not found.`);
48
48
  }
49
49
  const { [this.inputKey]: docs, ...rest } = values;
50
50
  const texts = docs.map(({ pageContent }) => pageContent);
51
51
  const text = texts.join("\n\n");
52
- const result = await this.llmChain.call({
52
+ return {
53
53
  ...rest,
54
54
  [this.documentVariableName]: text,
55
- }, runManager?.getChild("combine_documents"));
55
+ };
56
+ }
57
+ /** @ignore */
58
+ async _call(values, runManager) {
59
+ const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents"));
56
60
  return result;
57
61
  }
58
62
  _chainType() {
@@ -163,11 +167,11 @@ class MapReduceDocumentsChain extends base_js_1.BaseChain {
163
167
  const canSkipMapStep = i !== 0 || !this.ensureMapStep;
164
168
  if (canSkipMapStep) {
165
169
  // Calculate the total tokens required in the input
166
- const promises = inputs.map(async (i) => {
167
- const prompt = await this.llmChain.prompt.format(i);
168
- return this.llmChain.llm.getNumTokens(prompt);
169
- });
170
- const length = await Promise.all(promises).then((results) => results.reduce((a, b) => a + b, 0));
170
+ const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({
171
+ [this.combineDocumentChain.inputKey]: currentDocs,
172
+ ...rest,
173
+ }));
174
+ const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted);
171
175
  const withinTokenLimit = length < this.maxTokens;
172
176
  // If we can skip the map step, and we're within the token limit, we don't
173
177
  // need to run the map step, so just break out of the loop.
@@ -193,7 +197,10 @@ class MapReduceDocumentsChain extends base_js_1.BaseChain {
193
197
  }
194
198
  // Now, with the final result of all the inputs from the `llmChain`, we can
195
199
  // run the `combineDocumentChain` over them.
196
- const newInputs = { input_documents: currentDocs, ...rest };
200
+ const newInputs = {
201
+ [this.combineDocumentChain.inputKey]: currentDocs,
202
+ ...rest,
203
+ };
197
204
  const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents"));
198
205
  // Return the intermediate steps results if the flag is set
199
206
  if (this.returnIntermediateSteps) {
@@ -213,7 +220,7 @@ class MapReduceDocumentsChain extends base_js_1.BaseChain {
213
220
  }
214
221
  return new MapReduceDocumentsChain({
215
222
  llmChain: await llm_chain_js_1.LLMChain.deserialize(data.llm_chain),
216
- combineDocumentChain: await base_js_1.BaseChain.deserialize(data.combine_document_chain),
223
+ combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain),
217
224
  });
218
225
  }
219
226
  serialize() {
@@ -25,6 +25,8 @@ export declare class StuffDocumentsChain extends BaseChain implements StuffDocum
25
25
  get outputKeys(): string[];
26
26
  constructor(fields: StuffDocumentsChainInput);
27
27
  /** @ignore */
28
+ _prepInputs(values: ChainValues): ChainValues;
29
+ /** @ignore */
28
30
  _call(values: ChainValues, runManager?: CallbackManagerForChainRun): Promise<ChainValues>;
29
31
  _chainType(): "stuff_documents_chain";
30
32
  static deserialize(data: SerializedStuffDocumentsChain): Promise<StuffDocumentsChain>;
@@ -38,7 +40,7 @@ export interface MapReduceDocumentsChainInput extends StuffDocumentsChainInput {
38
40
  /** Ensures that the map step is taken regardless of max tokens */
39
41
  ensureMapStep?: boolean;
40
42
  /** Chain to use to combine results of applying llm_chain to documents. */
41
- combineDocumentChain: BaseChain;
43
+ combineDocumentChain: StuffDocumentsChain;
42
44
  /** Return the results of the map steps in the output. */
43
45
  returnIntermediateSteps?: boolean;
44
46
  }
@@ -57,7 +59,7 @@ export declare class MapReduceDocumentsChain extends BaseChain implements MapRed
57
59
  maxTokens: number;
58
60
  maxIterations: number;
59
61
  ensureMapStep: boolean;
60
- combineDocumentChain: BaseChain;
62
+ combineDocumentChain: StuffDocumentsChain;
61
63
  constructor(fields: MapReduceDocumentsChainInput);
62
64
  /** @ignore */
63
65
  _call(values: ChainValues, runManager?: CallbackManagerForChainRun): Promise<ChainValues>;
@@ -39,17 +39,21 @@ export class StuffDocumentsChain extends BaseChain {
39
39
  this.inputKey = fields.inputKey ?? this.inputKey;
40
40
  }
41
41
  /** @ignore */
42
- async _call(values, runManager) {
42
+ _prepInputs(values) {
43
43
  if (!(this.inputKey in values)) {
44
44
  throw new Error(`Document key ${this.inputKey} not found.`);
45
45
  }
46
46
  const { [this.inputKey]: docs, ...rest } = values;
47
47
  const texts = docs.map(({ pageContent }) => pageContent);
48
48
  const text = texts.join("\n\n");
49
- const result = await this.llmChain.call({
49
+ return {
50
50
  ...rest,
51
51
  [this.documentVariableName]: text,
52
- }, runManager?.getChild("combine_documents"));
52
+ };
53
+ }
54
+ /** @ignore */
55
+ async _call(values, runManager) {
56
+ const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents"));
53
57
  return result;
54
58
  }
55
59
  _chainType() {
@@ -159,11 +163,11 @@ export class MapReduceDocumentsChain extends BaseChain {
159
163
  const canSkipMapStep = i !== 0 || !this.ensureMapStep;
160
164
  if (canSkipMapStep) {
161
165
  // Calculate the total tokens required in the input
162
- const promises = inputs.map(async (i) => {
163
- const prompt = await this.llmChain.prompt.format(i);
164
- return this.llmChain.llm.getNumTokens(prompt);
165
- });
166
- const length = await Promise.all(promises).then((results) => results.reduce((a, b) => a + b, 0));
166
+ const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({
167
+ [this.combineDocumentChain.inputKey]: currentDocs,
168
+ ...rest,
169
+ }));
170
+ const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted);
167
171
  const withinTokenLimit = length < this.maxTokens;
168
172
  // If we can skip the map step, and we're within the token limit, we don't
169
173
  // need to run the map step, so just break out of the loop.
@@ -189,7 +193,10 @@ export class MapReduceDocumentsChain extends BaseChain {
189
193
  }
190
194
  // Now, with the final result of all the inputs from the `llmChain`, we can
191
195
  // run the `combineDocumentChain` over them.
192
- const newInputs = { input_documents: currentDocs, ...rest };
196
+ const newInputs = {
197
+ [this.combineDocumentChain.inputKey]: currentDocs,
198
+ ...rest,
199
+ };
193
200
  const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents"));
194
201
  // Return the intermediate steps results if the flag is set
195
202
  if (this.returnIntermediateSteps) {
@@ -209,7 +216,7 @@ export class MapReduceDocumentsChain extends BaseChain {
209
216
  }
210
217
  return new MapReduceDocumentsChain({
211
218
  llmChain: await LLMChain.deserialize(data.llm_chain),
212
- combineDocumentChain: await BaseChain.deserialize(data.combine_document_chain),
219
+ combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain),
213
220
  });
214
221
  }
215
222
  serialize() {
@@ -45,7 +45,7 @@ export type SerializedChatVectorDBQAChain = {
45
45
  export type SerializedMapReduceDocumentsChain = {
46
46
  _type: "map_reduce_documents_chain";
47
47
  llm_chain?: SerializedLLMChain;
48
- combine_document_chain?: SerializedBaseChain;
48
+ combine_document_chain?: SerializedStuffDocumentsChain;
49
49
  };
50
50
  export type SerializedRefineDocumentsChain = {
51
51
  _type: "refine_documents_chain";