langchain 0.0.171 → 0.0.173

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 (110) hide show
  1. package/agents/format_scratchpad/log.cjs +1 -0
  2. package/agents/format_scratchpad/log.d.ts +1 -0
  3. package/agents/format_scratchpad/log.js +1 -0
  4. package/agents/format_scratchpad/log_to_message.cjs +1 -0
  5. package/agents/format_scratchpad/log_to_message.d.ts +1 -0
  6. package/agents/format_scratchpad/log_to_message.js +1 -0
  7. package/agents/format_scratchpad/xml.cjs +1 -0
  8. package/agents/format_scratchpad/xml.d.ts +1 -0
  9. package/agents/format_scratchpad/xml.js +1 -0
  10. package/agents/format_scratchpad.cjs +1 -1
  11. package/agents/format_scratchpad.d.ts +1 -1
  12. package/agents/format_scratchpad.js +1 -1
  13. package/agents/openai/output_parser.cjs +1 -0
  14. package/agents/openai/output_parser.d.ts +1 -0
  15. package/agents/openai/output_parser.js +1 -0
  16. package/agents/react/output_parser.cjs +1 -0
  17. package/agents/react/output_parser.d.ts +1 -0
  18. package/agents/react/output_parser.js +1 -0
  19. package/agents/xml/output_parser.cjs +1 -0
  20. package/agents/xml/output_parser.d.ts +1 -0
  21. package/agents/xml/output_parser.js +1 -0
  22. package/dist/agents/format_scratchpad/log.cjs +16 -0
  23. package/dist/agents/format_scratchpad/log.d.ts +9 -0
  24. package/dist/agents/format_scratchpad/log.js +12 -0
  25. package/dist/agents/format_scratchpad/log_to_message.cjs +22 -0
  26. package/dist/agents/format_scratchpad/log_to_message.d.ts +2 -0
  27. package/dist/agents/format_scratchpad/log_to_message.js +18 -0
  28. package/dist/agents/{format_scratchpad.cjs → format_scratchpad/openai_functions.cjs} +3 -3
  29. package/dist/agents/{format_scratchpad.d.ts → format_scratchpad/openai_functions.d.ts} +1 -1
  30. package/dist/agents/{format_scratchpad.js → format_scratchpad/openai_functions.js} +3 -3
  31. package/dist/agents/format_scratchpad/xml.cjs +12 -0
  32. package/dist/agents/format_scratchpad/xml.d.ts +2 -0
  33. package/dist/agents/format_scratchpad/xml.js +8 -0
  34. package/dist/agents/index.cjs +3 -1
  35. package/dist/agents/index.d.ts +1 -0
  36. package/dist/agents/index.js +1 -0
  37. package/dist/agents/openai/index.cjs +8 -31
  38. package/dist/agents/openai/index.d.ts +2 -0
  39. package/dist/agents/openai/index.js +8 -31
  40. package/dist/agents/openai/output_parser.cjs +65 -0
  41. package/dist/agents/openai/output_parser.d.ts +22 -0
  42. package/dist/agents/openai/output_parser.js +61 -0
  43. package/dist/agents/react/output_parser.cjs +96 -0
  44. package/dist/agents/react/output_parser.d.ts +47 -0
  45. package/dist/agents/react/output_parser.js +92 -0
  46. package/dist/agents/react/prompt.cjs +13 -0
  47. package/dist/agents/react/prompt.d.ts +1 -0
  48. package/dist/agents/react/prompt.js +10 -0
  49. package/dist/agents/toolkits/conversational_retrieval/tool.cjs +2 -1
  50. package/dist/agents/toolkits/conversational_retrieval/tool.js +2 -1
  51. package/dist/agents/xml/index.cjs +9 -25
  52. package/dist/agents/xml/index.d.ts +2 -7
  53. package/dist/agents/xml/index.js +8 -23
  54. package/dist/agents/xml/output_parser.cjs +44 -0
  55. package/dist/agents/xml/output_parser.d.ts +14 -0
  56. package/dist/agents/xml/output_parser.js +40 -0
  57. package/dist/document_loaders/fs/pdf.cjs +2 -1
  58. package/dist/document_loaders/fs/pdf.js +2 -1
  59. package/dist/document_loaders/web/pdf.cjs +2 -1
  60. package/dist/document_loaders/web/pdf.js +2 -1
  61. package/dist/embeddings/openai.cjs +11 -0
  62. package/dist/embeddings/openai.d.ts +2 -0
  63. package/dist/embeddings/openai.js +11 -0
  64. package/dist/load/import_constants.cjs +1 -0
  65. package/dist/load/import_constants.js +1 -0
  66. package/dist/load/import_map.cjs +11 -3
  67. package/dist/load/import_map.d.ts +9 -1
  68. package/dist/load/import_map.js +9 -1
  69. package/dist/memory/vector_store.cjs +2 -1
  70. package/dist/memory/vector_store.js +2 -1
  71. package/dist/storage/file_system.cjs +167 -0
  72. package/dist/storage/file_system.d.ts +60 -0
  73. package/dist/storage/file_system.js +140 -0
  74. package/dist/tools/index.cjs +3 -1
  75. package/dist/tools/index.d.ts +1 -0
  76. package/dist/tools/index.js +1 -0
  77. package/dist/tools/render.cjs +36 -0
  78. package/dist/tools/render.d.ts +25 -0
  79. package/dist/tools/render.js +31 -0
  80. package/dist/tools/serpapi.d.ts +2 -2
  81. package/dist/tools/webbrowser.cjs +2 -1
  82. package/dist/tools/webbrowser.js +2 -1
  83. package/dist/util/document.cjs +12 -0
  84. package/dist/util/document.d.ts +9 -0
  85. package/dist/util/document.js +8 -0
  86. package/dist/vectorstores/analyticdb.cjs +7 -3
  87. package/dist/vectorstores/analyticdb.d.ts +1 -1
  88. package/dist/vectorstores/analyticdb.js +7 -3
  89. package/dist/vectorstores/cassandra.cjs +130 -35
  90. package/dist/vectorstores/cassandra.d.ts +21 -10
  91. package/dist/vectorstores/cassandra.js +130 -35
  92. package/dist/vectorstores/pgvector.cjs +13 -7
  93. package/dist/vectorstores/pgvector.d.ts +7 -0
  94. package/dist/vectorstores/pgvector.js +13 -7
  95. package/dist/vectorstores/qdrant.cjs +19 -11
  96. package/dist/vectorstores/qdrant.d.ts +1 -1
  97. package/dist/vectorstores/qdrant.js +19 -11
  98. package/dist/vectorstores/redis.cjs +4 -1
  99. package/dist/vectorstores/redis.d.ts +1 -1
  100. package/dist/vectorstores/redis.js +4 -1
  101. package/package.json +75 -3
  102. package/storage/file_system.cjs +1 -0
  103. package/storage/file_system.d.ts +1 -0
  104. package/storage/file_system.js +1 -0
  105. package/tools/render.cjs +1 -0
  106. package/tools/render.d.ts +1 -0
  107. package/tools/render.js +1 -0
  108. package/util/document.cjs +1 -0
  109. package/util/document.d.ts +1 -0
  110. package/util/document.js +1 -0
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/format_scratchpad/log.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/log.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/log.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/format_scratchpad/log_to_message.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/log_to_message.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/log_to_message.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/format_scratchpad/xml.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/xml.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/xml.js'
@@ -1 +1 @@
1
- module.exports = require('../dist/agents/format_scratchpad.cjs');
1
+ module.exports = require('../dist/agents/format_scratchpad/openai_functions.cjs');
@@ -1 +1 @@
1
- export * from '../dist/agents/format_scratchpad.js'
1
+ export * from '../dist/agents/format_scratchpad/openai_functions.js'
@@ -1 +1 @@
1
- export * from '../dist/agents/format_scratchpad.js'
1
+ export * from '../dist/agents/format_scratchpad/openai_functions.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/openai/output_parser.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/openai/output_parser.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/openai/output_parser.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/react/output_parser.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/react/output_parser.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/react/output_parser.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/xml/output_parser.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/xml/output_parser.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/xml/output_parser.js'
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatLogToString = void 0;
4
+ /**
5
+ * Construct the scratchpad that lets the agent continue its thought process.
6
+ * @param intermediateSteps
7
+ * @param observationPrefix
8
+ * @param llmPrefix
9
+ * @returns a string with the formatted observations and agent logs
10
+ */
11
+ function formatLogToString(intermediateSteps, observationPrefix = "Observation: ", llmPrefix = "Thought: ") {
12
+ const formattedSteps = intermediateSteps.reduce((thoughts, { action, observation }) => thoughts +
13
+ [action.log, `\n${observationPrefix}${observation}`, llmPrefix].join("\n"), "");
14
+ return formattedSteps;
15
+ }
16
+ exports.formatLogToString = formatLogToString;
@@ -0,0 +1,9 @@
1
+ import { AgentStep } from "../../schema/index.js";
2
+ /**
3
+ * Construct the scratchpad that lets the agent continue its thought process.
4
+ * @param intermediateSteps
5
+ * @param observationPrefix
6
+ * @param llmPrefix
7
+ * @returns a string with the formatted observations and agent logs
8
+ */
9
+ export declare function formatLogToString(intermediateSteps: AgentStep[], observationPrefix?: string, llmPrefix?: string): string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Construct the scratchpad that lets the agent continue its thought process.
3
+ * @param intermediateSteps
4
+ * @param observationPrefix
5
+ * @param llmPrefix
6
+ * @returns a string with the formatted observations and agent logs
7
+ */
8
+ export function formatLogToString(intermediateSteps, observationPrefix = "Observation: ", llmPrefix = "Thought: ") {
9
+ const formattedSteps = intermediateSteps.reduce((thoughts, { action, observation }) => thoughts +
10
+ [action.log, `\n${observationPrefix}${observation}`, llmPrefix].join("\n"), "");
11
+ return formattedSteps;
12
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatLogToMessage = void 0;
4
+ const template_js_1 = require("../../prompts/template.cjs");
5
+ const index_js_1 = require("../../schema/index.cjs");
6
+ function formatLogToMessage(intermediateSteps, templateToolResponse = "{observation}") {
7
+ // Get all input variables, if there is more than one, throw an error.
8
+ const matches = [...templateToolResponse.matchAll(/{([^}]*)}/g)];
9
+ const stringsInsideBrackets = matches.map((match) => match[1]);
10
+ if (stringsInsideBrackets.length > 1) {
11
+ throw new Error(`templateToolResponse must contain one input variable: ${templateToolResponse}`);
12
+ }
13
+ const thoughts = [];
14
+ for (const step of intermediateSteps) {
15
+ thoughts.push(new index_js_1.AIMessage(step.action.log));
16
+ thoughts.push(new index_js_1.HumanMessage((0, template_js_1.renderTemplate)(templateToolResponse, "f-string", {
17
+ [stringsInsideBrackets[0]]: step.observation,
18
+ })));
19
+ }
20
+ return thoughts;
21
+ }
22
+ exports.formatLogToMessage = formatLogToMessage;
@@ -0,0 +1,2 @@
1
+ import { AgentStep, BaseMessage } from "../../schema/index.js";
2
+ export declare function formatLogToMessage(intermediateSteps: AgentStep[], templateToolResponse?: string): BaseMessage[];
@@ -0,0 +1,18 @@
1
+ import { renderTemplate } from "../../prompts/template.js";
2
+ import { AIMessage, HumanMessage, } from "../../schema/index.js";
3
+ export function formatLogToMessage(intermediateSteps, templateToolResponse = "{observation}") {
4
+ // Get all input variables, if there is more than one, throw an error.
5
+ const matches = [...templateToolResponse.matchAll(/{([^}]*)}/g)];
6
+ const stringsInsideBrackets = matches.map((match) => match[1]);
7
+ if (stringsInsideBrackets.length > 1) {
8
+ throw new Error(`templateToolResponse must contain one input variable: ${templateToolResponse}`);
9
+ }
10
+ const thoughts = [];
11
+ for (const step of intermediateSteps) {
12
+ thoughts.push(new AIMessage(step.action.log));
13
+ thoughts.push(new HumanMessage(renderTemplate(templateToolResponse, "f-string", {
14
+ [stringsInsideBrackets[0]]: step.observation,
15
+ })));
16
+ }
17
+ return thoughts;
18
+ }
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.formatForOpenAIFunctions = void 0;
4
- const template_js_1 = require("../prompts/template.cjs");
5
- const index_js_1 = require("../schema/index.cjs");
6
- const prompt_js_1 = require("./chat_convo/prompt.cjs");
4
+ const template_js_1 = require("../../prompts/template.cjs");
5
+ const index_js_1 = require("../../schema/index.cjs");
6
+ const prompt_js_1 = require("../chat_convo/prompt.cjs");
7
7
  /**
8
8
  * Format a list of AgentSteps into a list of BaseMessage instances for
9
9
  * agents that use OpenAI's API. Helpful for passing in previous agent
@@ -1,4 +1,4 @@
1
- import { AgentStep, BaseMessage } from "../schema/index.js";
1
+ import { AgentStep, BaseMessage } from "../../schema/index.js";
2
2
  /**
3
3
  * Format a list of AgentSteps into a list of BaseMessage instances for
4
4
  * agents that use OpenAI's API. Helpful for passing in previous agent
@@ -1,6 +1,6 @@
1
- import { renderTemplate } from "../prompts/template.js";
2
- import { AIMessage, HumanMessage, } from "../schema/index.js";
3
- import { TEMPLATE_TOOL_RESPONSE } from "./chat_convo/prompt.js";
1
+ import { renderTemplate } from "../../prompts/template.js";
2
+ import { AIMessage, HumanMessage, } from "../../schema/index.js";
3
+ import { TEMPLATE_TOOL_RESPONSE } from "../chat_convo/prompt.js";
4
4
  /**
5
5
  * Format a list of AgentSteps into a list of BaseMessage instances for
6
6
  * agents that use OpenAI's API. Helpful for passing in previous agent
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatXml = void 0;
4
+ function formatXml(intermediateSteps) {
5
+ let log = "";
6
+ for (const step of intermediateSteps) {
7
+ const { action, observation } = step;
8
+ log += `<tool>${action.tool}</tool><tool_input>${action.toolInput}\n</tool_input><observation>${observation}</observation>`;
9
+ }
10
+ return log;
11
+ }
12
+ exports.formatXml = formatXml;
@@ -0,0 +1,2 @@
1
+ import { AgentStep } from "../../schema/index.js";
2
+ export declare function formatXml(intermediateSteps: AgentStep[]): string;
@@ -0,0 +1,8 @@
1
+ export function formatXml(intermediateSteps) {
2
+ let log = "";
3
+ for (const step of intermediateSteps) {
4
+ const { action, observation } = step;
5
+ log += `<tool>${action.tool}</tool><tool_input>${action.toolInput}\n</tool_input><observation>${observation}</observation>`;
6
+ }
7
+ return log;
8
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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.createOpenApiAgent = exports.createJsonAgent = exports.ZapierToolKit = exports.VectorStoreToolkit = exports.VectorStoreRouterToolkit = exports.RequestsToolkit = exports.OpenApiToolkit = exports.JsonToolkit = exports.LLMSingleActionAgent = exports.BaseSingleActionAgent = exports.Agent = void 0;
3
+ exports.XMLAgent = 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.createOpenApiAgent = exports.createJsonAgent = exports.ZapierToolKit = exports.VectorStoreToolkit = exports.VectorStoreRouterToolkit = 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, "StructuredChatOutputParser", { enumerable: true,
45
45
  Object.defineProperty(exports, "StructuredChatOutputParserWithRetries", { enumerable: true, get: function () { return outputParser_js_4.StructuredChatOutputParserWithRetries; } });
46
46
  var index_js_6 = require("./openai/index.cjs");
47
47
  Object.defineProperty(exports, "OpenAIAgent", { enumerable: true, get: function () { return index_js_6.OpenAIAgent; } });
48
+ var index_js_7 = require("./xml/index.cjs");
49
+ Object.defineProperty(exports, "XMLAgent", { enumerable: true, get: function () { return index_js_7.XMLAgent; } });
@@ -13,3 +13,4 @@ export { AgentActionOutputParser, type AgentInput, type SerializedAgent, type Se
13
13
  export { StructuredChatAgent, type StructuredChatAgentInput, type StructuredChatCreatePromptArgs, } from "./structured_chat/index.js";
14
14
  export { StructuredChatOutputParser, type StructuredChatOutputParserArgs, StructuredChatOutputParserWithRetries, } from "./structured_chat/outputParser.js";
15
15
  export { OpenAIAgent, type OpenAIAgentInput, type OpenAIAgentCreatePromptArgs, } from "./openai/index.js";
16
+ export { XMLAgent, type XMLAgentInput } from "./xml/index.js";
@@ -13,3 +13,4 @@ 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
15
  export { OpenAIAgent, } from "./openai/index.js";
16
+ export { XMLAgent } from "./xml/index.js";
@@ -6,36 +6,7 @@ const agent_js_1 = require("../agent.cjs");
6
6
  const prompt_js_1 = require("./prompt.cjs");
7
7
  const chat_js_1 = require("../../prompts/chat.cjs");
8
8
  const llm_chain_js_1 = require("../../chains/llm_chain.cjs");
9
- const output_parser_js_1 = require("../../schema/output_parser.cjs");
10
- /**
11
- * Parses the output message into a FunctionsAgentAction or AgentFinish
12
- * object.
13
- * @param message The BaseMessage to parse.
14
- * @returns A FunctionsAgentAction or AgentFinish object.
15
- */
16
- function parseOutput(message) {
17
- if (message.additional_kwargs.function_call) {
18
- // eslint-disable-next-line prefer-destructuring
19
- const function_call = message.additional_kwargs.function_call;
20
- try {
21
- const toolInput = function_call.arguments
22
- ? JSON.parse(function_call.arguments)
23
- : {};
24
- return {
25
- tool: function_call.name,
26
- toolInput,
27
- log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
28
- messageLog: [message],
29
- };
30
- }
31
- catch (error) {
32
- throw new output_parser_js_1.OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
33
- }
34
- }
35
- else {
36
- return { returnValues: { output: message.content }, log: message.content };
37
- }
38
- }
9
+ const output_parser_js_1 = require("./output_parser.cjs");
39
10
  /**
40
11
  * Checks if the given action is a FunctionsAgentAction.
41
12
  * @param action The action to check.
@@ -91,6 +62,12 @@ class OpenAIAgent extends agent_js_1.Agent {
91
62
  writable: true,
92
63
  value: void 0
93
64
  });
65
+ Object.defineProperty(this, "outputParser", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: new output_parser_js_1.OpenAIFunctionsAgentOutputParser()
70
+ });
94
71
  this.tools = input.tools;
95
72
  }
96
73
  /**
@@ -173,7 +150,7 @@ class OpenAIAgent extends agent_js_1.Agent {
173
150
  }
174
151
  const promptValue = await this.llmChain.prompt.formatPromptValue(valuesForPrompt);
175
152
  const message = await llm.predictMessages(promptValue.toChatMessages(), valuesForLLM, callbackManager);
176
- return parseOutput(message);
153
+ return this.outputParser.parseAIMessage(message);
177
154
  }
178
155
  }
179
156
  exports.OpenAIAgent = OpenAIAgent;
@@ -5,6 +5,7 @@ import { StructuredTool } from "../../tools/base.js";
5
5
  import { Agent, AgentArgs } from "../agent.js";
6
6
  import { AgentInput } from "../types.js";
7
7
  import { BaseLanguageModel } from "../../base_language/index.js";
8
+ import { OpenAIFunctionsAgentOutputParser } from "./output_parser.js";
8
9
  export declare function _formatIntermediateSteps(intermediateSteps: AgentStep[]): BaseMessage[];
9
10
  /**
10
11
  * Interface for the input data required to create an OpenAIAgent.
@@ -33,6 +34,7 @@ export declare class OpenAIAgent extends Agent {
33
34
  llmPrefix(): string;
34
35
  _stop(): string[];
35
36
  tools: StructuredTool[];
37
+ outputParser: OpenAIFunctionsAgentOutputParser;
36
38
  constructor(input: Omit<OpenAIAgentInput, "outputParser">);
37
39
  /**
38
40
  * Creates a prompt for the OpenAIAgent using the provided tools and
@@ -3,36 +3,7 @@ import { Agent } from "../agent.js";
3
3
  import { PREFIX } from "./prompt.js";
4
4
  import { ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, } from "../../prompts/chat.js";
5
5
  import { LLMChain } from "../../chains/llm_chain.js";
6
- import { OutputParserException } from "../../schema/output_parser.js";
7
- /**
8
- * Parses the output message into a FunctionsAgentAction or AgentFinish
9
- * object.
10
- * @param message The BaseMessage to parse.
11
- * @returns A FunctionsAgentAction or AgentFinish object.
12
- */
13
- function parseOutput(message) {
14
- if (message.additional_kwargs.function_call) {
15
- // eslint-disable-next-line prefer-destructuring
16
- const function_call = message.additional_kwargs.function_call;
17
- try {
18
- const toolInput = function_call.arguments
19
- ? JSON.parse(function_call.arguments)
20
- : {};
21
- return {
22
- tool: function_call.name,
23
- toolInput,
24
- log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
25
- messageLog: [message],
26
- };
27
- }
28
- catch (error) {
29
- throw new OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
30
- }
31
- }
32
- else {
33
- return { returnValues: { output: message.content }, log: message.content };
34
- }
35
- }
6
+ import { OpenAIFunctionsAgentOutputParser, } from "./output_parser.js";
36
7
  /**
37
8
  * Checks if the given action is a FunctionsAgentAction.
38
9
  * @param action The action to check.
@@ -87,6 +58,12 @@ export class OpenAIAgent extends Agent {
87
58
  writable: true,
88
59
  value: void 0
89
60
  });
61
+ Object.defineProperty(this, "outputParser", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: new OpenAIFunctionsAgentOutputParser()
66
+ });
90
67
  this.tools = input.tools;
91
68
  }
92
69
  /**
@@ -169,6 +146,6 @@ export class OpenAIAgent extends Agent {
169
146
  }
170
147
  const promptValue = await this.llmChain.prompt.formatPromptValue(valuesForPrompt);
171
148
  const message = await llm.predictMessages(promptValue.toChatMessages(), valuesForLLM, callbackManager);
172
- return parseOutput(message);
149
+ return this.outputParser.parseAIMessage(message);
173
150
  }
174
151
  }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpenAIFunctionsAgentOutputParser = void 0;
4
+ const index_js_1 = require("../../schema/index.cjs");
5
+ const types_js_1 = require("../types.cjs");
6
+ const output_parser_js_1 = require("../../schema/output_parser.cjs");
7
+ class OpenAIFunctionsAgentOutputParser extends types_js_1.AgentActionOutputParser {
8
+ constructor() {
9
+ super(...arguments);
10
+ Object.defineProperty(this, "lc_namespace", {
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true,
14
+ value: ["langchain", "agents", "openai"]
15
+ });
16
+ }
17
+ static lc_name() {
18
+ return "OpenAIFunctionsAgentOutputParser";
19
+ }
20
+ async parse(text) {
21
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
22
+ }
23
+ async parseResult(generations) {
24
+ if ("message" in generations[0] && (0, index_js_1.isBaseMessage)(generations[0].message)) {
25
+ return this.parseAIMessage(generations[0].message);
26
+ }
27
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
28
+ }
29
+ /**
30
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
31
+ * object.
32
+ * @param message The BaseMessage to parse.
33
+ * @returns A FunctionsAgentAction or AgentFinish object.
34
+ */
35
+ parseAIMessage(message) {
36
+ if (message.additional_kwargs.function_call) {
37
+ // eslint-disable-next-line prefer-destructuring
38
+ const function_call = message.additional_kwargs.function_call;
39
+ try {
40
+ const toolInput = function_call.arguments
41
+ ? JSON.parse(function_call.arguments)
42
+ : {};
43
+ return {
44
+ tool: function_call.name,
45
+ toolInput,
46
+ log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
47
+ messageLog: [message],
48
+ };
49
+ }
50
+ catch (error) {
51
+ throw new output_parser_js_1.OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
52
+ }
53
+ }
54
+ else {
55
+ return {
56
+ returnValues: { output: message.content },
57
+ log: message.content,
58
+ };
59
+ }
60
+ }
61
+ getFormatInstructions() {
62
+ throw new Error("getFormatInstructions not implemented inside OpenAIFunctionsAgentOutputParser.");
63
+ }
64
+ }
65
+ exports.OpenAIFunctionsAgentOutputParser = OpenAIFunctionsAgentOutputParser;
@@ -0,0 +1,22 @@
1
+ import { AgentAction, AgentFinish, BaseMessage, ChatGeneration } from "../../schema/index.js";
2
+ import { AgentActionOutputParser } from "../types.js";
3
+ /**
4
+ * Type that represents an agent action with an optional message log.
5
+ */
6
+ export type FunctionsAgentAction = AgentAction & {
7
+ messageLog?: BaseMessage[];
8
+ };
9
+ export declare class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
10
+ lc_namespace: string[];
11
+ static lc_name(): string;
12
+ parse(text: string): Promise<AgentAction | AgentFinish>;
13
+ parseResult(generations: ChatGeneration[]): Promise<AgentFinish | FunctionsAgentAction>;
14
+ /**
15
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
16
+ * object.
17
+ * @param message The BaseMessage to parse.
18
+ * @returns A FunctionsAgentAction or AgentFinish object.
19
+ */
20
+ parseAIMessage(message: BaseMessage): FunctionsAgentAction | AgentFinish;
21
+ getFormatInstructions(): string;
22
+ }
@@ -0,0 +1,61 @@
1
+ import { isBaseMessage, } from "../../schema/index.js";
2
+ import { AgentActionOutputParser } from "../types.js";
3
+ import { OutputParserException } from "../../schema/output_parser.js";
4
+ export class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
5
+ constructor() {
6
+ super(...arguments);
7
+ Object.defineProperty(this, "lc_namespace", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: ["langchain", "agents", "openai"]
12
+ });
13
+ }
14
+ static lc_name() {
15
+ return "OpenAIFunctionsAgentOutputParser";
16
+ }
17
+ async parse(text) {
18
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
19
+ }
20
+ async parseResult(generations) {
21
+ if ("message" in generations[0] && isBaseMessage(generations[0].message)) {
22
+ return this.parseAIMessage(generations[0].message);
23
+ }
24
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
25
+ }
26
+ /**
27
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
28
+ * object.
29
+ * @param message The BaseMessage to parse.
30
+ * @returns A FunctionsAgentAction or AgentFinish object.
31
+ */
32
+ parseAIMessage(message) {
33
+ if (message.additional_kwargs.function_call) {
34
+ // eslint-disable-next-line prefer-destructuring
35
+ const function_call = message.additional_kwargs.function_call;
36
+ try {
37
+ const toolInput = function_call.arguments
38
+ ? JSON.parse(function_call.arguments)
39
+ : {};
40
+ return {
41
+ tool: function_call.name,
42
+ toolInput,
43
+ log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
44
+ messageLog: [message],
45
+ };
46
+ }
47
+ catch (error) {
48
+ throw new OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
49
+ }
50
+ }
51
+ else {
52
+ return {
53
+ returnValues: { output: message.content },
54
+ log: message.content,
55
+ };
56
+ }
57
+ }
58
+ getFormatInstructions() {
59
+ throw new Error("getFormatInstructions not implemented inside OpenAIFunctionsAgentOutputParser.");
60
+ }
61
+ }
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReActSingleInputOutputParser = void 0;
4
+ const template_js_1 = require("../../prompts/template.cjs");
5
+ const types_js_1 = require("../types.cjs");
6
+ const prompt_js_1 = require("./prompt.cjs");
7
+ const FINAL_ANSWER_ACTION = "Final Answer:";
8
+ const FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE = "Parsing LLM output produced both a final answer and a parse-able action:";
9
+ /**
10
+ * Parses ReAct-style LLM calls that have a single tool input.
11
+ *
12
+ * Expects output to be in one of two formats.
13
+ *
14
+ * If the output signals that an action should be taken,
15
+ * should be in the below format. This will result in an AgentAction
16
+ * being returned.
17
+ *
18
+ * ```
19
+ * Thought: agent thought here
20
+ * Action: search
21
+ * Action Input: what is the temperature in SF?
22
+ * ```
23
+ *
24
+ * If the output signals that a final answer should be given,
25
+ * should be in the below format. This will result in an AgentFinish
26
+ * being returned.
27
+ *
28
+ * ```
29
+ * Thought: agent thought here
30
+ * Final Answer: The temperature is 100 degrees
31
+ * ```
32
+ */
33
+ class ReActSingleInputOutputParser extends types_js_1.AgentActionOutputParser {
34
+ constructor(fields) {
35
+ super(...arguments);
36
+ Object.defineProperty(this, "lc_namespace", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: ["langchain", "agents", "react"]
41
+ });
42
+ Object.defineProperty(this, "toolNames", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ this.toolNames = fields.toolNames;
49
+ }
50
+ /**
51
+ * Parses the given text into an AgentAction or AgentFinish object. If an
52
+ * output fixing parser is defined, uses it to parse the text.
53
+ * @param text Text to parse.
54
+ * @returns Promise that resolves to an AgentAction or AgentFinish object.
55
+ */
56
+ async parse(text) {
57
+ const includesAnswer = text.includes(FINAL_ANSWER_ACTION);
58
+ const regex = /Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)/;
59
+ const actionMatch = text.match(regex);
60
+ if (actionMatch) {
61
+ if (includesAnswer) {
62
+ throw new Error(`${FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: ${text}`);
63
+ }
64
+ const action = actionMatch[1];
65
+ const actionInput = actionMatch[2];
66
+ const toolInput = actionInput.trim().replace(/"/g, "");
67
+ return {
68
+ tool: action,
69
+ toolInput,
70
+ log: text,
71
+ };
72
+ }
73
+ if (includesAnswer) {
74
+ const finalAnswerText = text.split(FINAL_ANSWER_ACTION)[1].trim();
75
+ return {
76
+ returnValues: {
77
+ output: finalAnswerText,
78
+ },
79
+ log: text,
80
+ };
81
+ }
82
+ throw new Error(`Could not parse LLM output: ${text}`);
83
+ }
84
+ /**
85
+ * Returns the format instructions as a string. If the 'raw' option is
86
+ * true, returns the raw FORMAT_INSTRUCTIONS.
87
+ * @param options Options for getting the format instructions.
88
+ * @returns Format instructions as a string.
89
+ */
90
+ getFormatInstructions() {
91
+ return (0, template_js_1.renderTemplate)(prompt_js_1.FORMAT_INSTRUCTIONS, "f-string", {
92
+ tool_names: this.toolNames.join(", "),
93
+ });
94
+ }
95
+ }
96
+ exports.ReActSingleInputOutputParser = ReActSingleInputOutputParser;