langchain 0.0.76 → 0.0.78

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 (162) hide show
  1. package/chains/query_constructor/ir.cjs +1 -0
  2. package/chains/query_constructor/ir.d.ts +1 -0
  3. package/chains/query_constructor/ir.js +1 -0
  4. package/chains/query_constructor.cjs +1 -0
  5. package/chains/query_constructor.d.ts +1 -0
  6. package/chains/query_constructor.js +1 -0
  7. package/dist/agents/agent.d.ts +5 -4
  8. package/dist/agents/agent_toolkits/sql/sql.cjs +2 -2
  9. package/dist/agents/agent_toolkits/sql/sql.d.ts +1 -1
  10. package/dist/agents/agent_toolkits/sql/sql.js +2 -2
  11. package/dist/agents/chat/index.cjs +3 -3
  12. package/dist/agents/chat/index.d.ts +1 -0
  13. package/dist/agents/chat/index.js +3 -3
  14. package/dist/agents/chat_convo/index.cjs +30 -14
  15. package/dist/agents/chat_convo/index.d.ts +5 -1
  16. package/dist/agents/chat_convo/index.js +31 -15
  17. package/dist/agents/chat_convo/outputParser.cjs +79 -7
  18. package/dist/agents/chat_convo/outputParser.d.ts +25 -13
  19. package/dist/agents/chat_convo/outputParser.js +77 -6
  20. package/dist/agents/chat_convo/prompt.cjs +11 -8
  21. package/dist/agents/chat_convo/prompt.d.ts +2 -2
  22. package/dist/agents/chat_convo/prompt.js +11 -8
  23. package/dist/agents/executor.d.ts +2 -3
  24. package/dist/agents/index.cjs +6 -1
  25. package/dist/agents/index.d.ts +2 -0
  26. package/dist/agents/index.js +2 -0
  27. package/dist/agents/initialize.cjs +19 -13
  28. package/dist/agents/initialize.d.ts +12 -2
  29. package/dist/agents/initialize.js +16 -10
  30. package/dist/agents/mrkl/index.cjs +3 -3
  31. package/dist/agents/mrkl/index.d.ts +1 -0
  32. package/dist/agents/mrkl/index.js +3 -3
  33. package/dist/agents/mrkl/outputParser.cjs +2 -2
  34. package/dist/agents/mrkl/outputParser.js +2 -2
  35. package/dist/agents/structured_chat/index.cjs +106 -0
  36. package/dist/agents/structured_chat/index.d.ts +44 -0
  37. package/dist/agents/structured_chat/index.js +102 -0
  38. package/dist/agents/structured_chat/outputParser.cjs +92 -0
  39. package/dist/agents/structured_chat/outputParser.d.ts +24 -0
  40. package/dist/agents/structured_chat/outputParser.js +87 -0
  41. package/dist/agents/structured_chat/prompt.cjs +62 -0
  42. package/dist/agents/structured_chat/prompt.d.ts +4 -0
  43. package/dist/agents/structured_chat/prompt.js +59 -0
  44. package/dist/callbacks/handlers/tracer_langchain.cjs +12 -4
  45. package/dist/callbacks/handlers/tracer_langchain.d.ts +4 -1
  46. package/dist/callbacks/handlers/tracer_langchain.js +12 -4
  47. package/dist/callbacks/manager.cjs +6 -2
  48. package/dist/callbacks/manager.js +6 -2
  49. package/dist/chains/query_constructor/index.cjs +105 -0
  50. package/dist/chains/query_constructor/index.d.ts +37 -0
  51. package/dist/chains/query_constructor/index.js +95 -0
  52. package/dist/chains/query_constructor/ir.cjs +116 -0
  53. package/dist/chains/query_constructor/ir.d.ts +60 -0
  54. package/dist/chains/query_constructor/ir.js +107 -0
  55. package/dist/chains/query_constructor/parser.cjs +103 -0
  56. package/dist/chains/query_constructor/parser.d.ts +12 -0
  57. package/dist/chains/query_constructor/parser.js +99 -0
  58. package/dist/chains/query_constructor/prompt.cjs +127 -0
  59. package/dist/chains/query_constructor/prompt.d.ts +15 -0
  60. package/dist/chains/query_constructor/prompt.js +124 -0
  61. package/dist/chains/sql_db/sql_db_chain.cjs +13 -0
  62. package/dist/chains/sql_db/sql_db_chain.d.ts +2 -0
  63. package/dist/chains/sql_db/sql_db_chain.js +13 -0
  64. package/dist/client/langchainplus.cjs +21 -15
  65. package/dist/client/langchainplus.d.ts +4 -2
  66. package/dist/client/langchainplus.js +21 -15
  67. package/dist/llms/sagemaker_endpoint.cjs +123 -0
  68. package/dist/llms/sagemaker_endpoint.d.ts +82 -0
  69. package/dist/llms/sagemaker_endpoint.js +118 -0
  70. package/dist/memory/buffer_memory.cjs +1 -1
  71. package/dist/memory/buffer_memory.js +1 -1
  72. package/dist/memory/buffer_window_memory.cjs +1 -1
  73. package/dist/memory/buffer_window_memory.js +1 -1
  74. package/dist/output_parsers/expression.cjs +68 -0
  75. package/dist/output_parsers/expression.d.ts +25 -0
  76. package/dist/output_parsers/expression.js +49 -0
  77. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs +26 -0
  78. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.d.ts +7 -0
  79. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js +22 -0
  80. package/dist/output_parsers/expression_type_handlers/base.cjs +67 -0
  81. package/dist/output_parsers/expression_type_handlers/base.d.ts +23 -0
  82. package/dist/output_parsers/expression_type_handlers/base.js +62 -0
  83. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.cjs +24 -0
  84. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.d.ts +7 -0
  85. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.js +20 -0
  86. package/dist/output_parsers/expression_type_handlers/call_expression_handler.cjs +52 -0
  87. package/dist/output_parsers/expression_type_handlers/call_expression_handler.d.ts +7 -0
  88. package/dist/output_parsers/expression_type_handlers/call_expression_handler.js +48 -0
  89. package/dist/output_parsers/expression_type_handlers/factory.cjs +56 -0
  90. package/dist/output_parsers/expression_type_handlers/factory.d.ts +9 -0
  91. package/dist/output_parsers/expression_type_handlers/factory.js +52 -0
  92. package/dist/output_parsers/expression_type_handlers/identifier_handler.cjs +22 -0
  93. package/dist/output_parsers/expression_type_handlers/identifier_handler.d.ts +7 -0
  94. package/dist/output_parsers/expression_type_handlers/identifier_handler.js +18 -0
  95. package/dist/output_parsers/expression_type_handlers/member_expression_handler.cjs +45 -0
  96. package/dist/output_parsers/expression_type_handlers/member_expression_handler.d.ts +7 -0
  97. package/dist/output_parsers/expression_type_handlers/member_expression_handler.js +41 -0
  98. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.cjs +24 -0
  99. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.d.ts +7 -0
  100. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.js +20 -0
  101. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.cjs +29 -0
  102. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.d.ts +7 -0
  103. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.js +25 -0
  104. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.cjs +36 -0
  105. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.d.ts +7 -0
  106. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.js +32 -0
  107. package/dist/output_parsers/expression_type_handlers/string_literal_handler.cjs +22 -0
  108. package/dist/output_parsers/expression_type_handlers/string_literal_handler.d.ts +7 -0
  109. package/dist/output_parsers/expression_type_handlers/string_literal_handler.js +18 -0
  110. package/dist/output_parsers/expression_type_handlers/types.cjs +2 -0
  111. package/dist/output_parsers/expression_type_handlers/types.d.ts +41 -0
  112. package/dist/output_parsers/expression_type_handlers/types.js +1 -0
  113. package/dist/output_parsers/index.cjs +2 -1
  114. package/dist/output_parsers/index.d.ts +1 -1
  115. package/dist/output_parsers/index.js +1 -1
  116. package/dist/output_parsers/structured.cjs +81 -23
  117. package/dist/output_parsers/structured.d.ts +18 -0
  118. package/dist/output_parsers/structured.js +79 -22
  119. package/dist/retrievers/self_query/index.cjs +79 -0
  120. package/dist/retrievers/self_query/index.d.ts +33 -0
  121. package/dist/retrievers/self_query/index.js +74 -0
  122. package/dist/retrievers/self_query/translator.cjs +72 -0
  123. package/dist/retrievers/self_query/translator.d.ts +14 -0
  124. package/dist/retrievers/self_query/translator.js +67 -0
  125. package/dist/schema/query_constructor.cjs +26 -0
  126. package/dist/schema/query_constructor.d.ts +6 -0
  127. package/dist/schema/query_constructor.js +22 -0
  128. package/dist/text_splitter.cjs +2 -1
  129. package/dist/text_splitter.js +2 -1
  130. package/dist/tools/dynamic.cjs +39 -1
  131. package/dist/tools/dynamic.d.ts +18 -3
  132. package/dist/tools/dynamic.js +38 -1
  133. package/dist/tools/index.cjs +2 -1
  134. package/dist/tools/index.d.ts +1 -1
  135. package/dist/tools/index.js +1 -1
  136. package/dist/tools/json.cjs +3 -1
  137. package/dist/tools/json.js +3 -1
  138. package/dist/tools/sql.cjs +17 -11
  139. package/dist/tools/sql.d.ts +7 -1
  140. package/dist/tools/sql.js +17 -11
  141. package/dist/util/event-source-parse.cjs +31 -5
  142. package/dist/util/event-source-parse.d.ts +3 -3
  143. package/dist/util/event-source-parse.js +31 -5
  144. package/dist/vectorstores/faiss.cjs +245 -0
  145. package/dist/vectorstores/faiss.d.ts +39 -0
  146. package/dist/vectorstores/faiss.js +218 -0
  147. package/llms/sagemaker_endpoint.cjs +1 -0
  148. package/llms/sagemaker_endpoint.d.ts +1 -0
  149. package/llms/sagemaker_endpoint.js +1 -0
  150. package/output_parsers/expression.cjs +1 -0
  151. package/output_parsers/expression.d.ts +1 -0
  152. package/output_parsers/expression.js +1 -0
  153. package/package.json +79 -3
  154. package/retrievers/self_query.cjs +1 -0
  155. package/retrievers/self_query.d.ts +1 -0
  156. package/retrievers/self_query.js +1 -0
  157. package/schema/query_constructor.cjs +1 -0
  158. package/schema/query_constructor.d.ts +1 -0
  159. package/schema/query_constructor.js +1 -0
  160. package/vectorstores/faiss.cjs +1 -0
  161. package/vectorstores/faiss.d.ts +1 -0
  162. package/vectorstores/faiss.js +1 -0
@@ -1,5 +1,5 @@
1
1
  export declare const DEFAULT_PREFIX = "Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.";
2
2
  export declare const PREFIX_END = " However, above all else, all responses must adhere to the format of RESPONSE FORMAT INSTRUCTIONS.";
3
- export declare const FORMAT_INSTRUCTIONS = "RESPONSE FORMAT INSTRUCTIONS\n----------------------------\n\nWhen responding to me please, please output a response in one of two formats:\n\n**Option 1:**\nUse this if you want the human to use a tool.\nMarkdown code snippet formatted in the following schema:\n\n```json\n{{{{\n \"action\": string \\ The action to take. Must be one of {tool_names}\n \"action_input\": string \\ The input to the action\n}}}}\n```\n\n**Option #2:**\nUse this if you want to respond directly to the human. Markdown code snippet formatted in the following schema:\n\n```json\n{{{{\n \"action\": \"Final Answer\",\n \"action_input\": string \\ You should put what you want to return to use here and make sure to use valid json newline characters.\n}}}}\n```";
4
- export declare const DEFAULT_SUFFIX = "TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}";
3
+ export declare const FORMAT_INSTRUCTIONS = "RESPONSE FORMAT INSTRUCTIONS\n----------------------------\n\nOutput a JSON markdown code snippet containing a valid JSON object in one of two formats:\n\n**Option 1:**\nUse this if you want the human to use a tool.\nMarkdown code snippet formatted in the following schema:\n\n```json\n{{{{\n \"action\": string // The action to take. Must be one of [{tool_names}]\n \"action_input\": string // The input to the action. May be a stringified object.\n}}}}\n```\n\n**Option #2:**\nUse this if you want to respond directly and conversationally to the human. Markdown code snippet formatted in the following schema:\n\n```json\n{{{{\n \"action\": \"Final Answer\",\n \"action_input\": string // You should put what you want to return to use here and make sure to use valid json newline characters.\n}}}}\n```\n\nFor both options, remember to always include the surrounding markdown code snippet delimiters (begin with \"```json\" and end with \"```\")!\n";
4
+ export declare const DEFAULT_SUFFIX = "TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{tools}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{input}}";
5
5
  export declare const TEMPLATE_TOOL_RESPONSE = "TOOL RESPONSE:\n---------------------\n{observation}\n\nUSER'S INPUT\n--------------------\n\nOkay, so what is the response to my original question? If using information from tools, you must say it explicitly - I have forgotten all TOOL RESPONSES! Remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else.";
@@ -9,7 +9,7 @@ export const PREFIX_END = ` However, above all else, all responses must adhere t
9
9
  export const FORMAT_INSTRUCTIONS = `RESPONSE FORMAT INSTRUCTIONS
10
10
  ----------------------------
11
11
 
12
- When responding to me please, please output a response in one of two formats:
12
+ Output a JSON markdown code snippet containing a valid JSON object in one of two formats:
13
13
 
14
14
  **Option 1:**
15
15
  Use this if you want the human to use a tool.
@@ -17,25 +17,28 @@ Markdown code snippet formatted in the following schema:
17
17
 
18
18
  \`\`\`json
19
19
  {{{{
20
- "action": string \\ The action to take. Must be one of {tool_names}
21
- "action_input": string \\ The input to the action
20
+ "action": string // The action to take. Must be one of [{tool_names}]
21
+ "action_input": string // The input to the action. May be a stringified object.
22
22
  }}}}
23
23
  \`\`\`
24
24
 
25
25
  **Option #2:**
26
- Use this if you want to respond directly to the human. Markdown code snippet formatted in the following schema:
26
+ Use this if you want to respond directly and conversationally to the human. Markdown code snippet formatted in the following schema:
27
27
 
28
28
  \`\`\`json
29
29
  {{{{
30
30
  "action": "Final Answer",
31
- "action_input": string \\ You should put what you want to return to use here and make sure to use valid json newline characters.
31
+ "action_input": string // You should put what you want to return to use here and make sure to use valid json newline characters.
32
32
  }}}}
33
- \`\`\``;
33
+ \`\`\`
34
+
35
+ For both options, remember to always include the surrounding markdown code snippet delimiters (begin with "\`\`\`json" and end with "\`\`\`")!
36
+ `;
34
37
  export const DEFAULT_SUFFIX = `TOOLS
35
38
  ------
36
39
  Assistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:
37
40
 
38
- {{tools}}
41
+ {tools}
39
42
 
40
43
  {format_instructions}
41
44
 
@@ -43,7 +46,7 @@ USER'S INPUT
43
46
  --------------------
44
47
  Here is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):
45
48
 
46
- {{{{input}}}}`;
49
+ {{input}}`;
47
50
  export const TEMPLATE_TOOL_RESPONSE = `TOOL RESPONSE:
48
51
  ---------------------
49
52
  {observation}
@@ -1,13 +1,12 @@
1
1
  import { BaseChain, ChainInputs } from "../chains/base.js";
2
2
  import { BaseMultiActionAgent, BaseSingleActionAgent } from "./agent.js";
3
- import { Tool } from "../tools/base.js";
4
3
  import { StoppingMethod } from "./types.js";
5
4
  import { SerializedLLMChain } from "../chains/serde.js";
6
5
  import { ChainValues } from "../schema/index.js";
7
6
  import { CallbackManagerForChainRun } from "../callbacks/manager.js";
8
7
  export interface AgentExecutorInput extends ChainInputs {
9
8
  agent: BaseSingleActionAgent | BaseMultiActionAgent;
10
- tools: Tool[];
9
+ tools: this["agent"]["ToolType"][];
11
10
  returnIntermediateSteps?: boolean;
12
11
  maxIterations?: number;
13
12
  earlyStoppingMethod?: StoppingMethod;
@@ -18,7 +17,7 @@ export interface AgentExecutorInput extends ChainInputs {
18
17
  */
19
18
  export declare class AgentExecutor extends BaseChain {
20
19
  agent: BaseSingleActionAgent | BaseMultiActionAgent;
21
- tools: Tool[];
20
+ tools: this["agent"]["ToolType"][];
22
21
  returnIntermediateSteps: boolean;
23
22
  maxIterations?: number;
24
23
  earlyStoppingMethod: StoppingMethod;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentActionOutputParser = exports.ZeroShotAgentOutputParser = exports.ZeroShotAgent = exports.initializeAgentExecutorWithOptions = exports.initializeAgentExecutor = exports.AgentExecutor = 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.StructuredChatOutputParserWithRetries = exports.StructuredChatOutputParser = exports.StructuredChatAgent = exports.AgentActionOutputParser = exports.ZeroShotAgentOutputParser = exports.ZeroShotAgent = exports.initializeAgentExecutorWithOptions = exports.initializeAgentExecutor = exports.AgentExecutor = 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; } });
@@ -39,3 +39,8 @@ var outputParser_js_3 = require("./mrkl/outputParser.cjs");
39
39
  Object.defineProperty(exports, "ZeroShotAgentOutputParser", { enumerable: true, get: function () { return outputParser_js_3.ZeroShotAgentOutputParser; } });
40
40
  var types_js_1 = require("./types.cjs");
41
41
  Object.defineProperty(exports, "AgentActionOutputParser", { enumerable: true, get: function () { return types_js_1.AgentActionOutputParser; } });
42
+ var index_js_5 = require("./structured_chat/index.cjs");
43
+ Object.defineProperty(exports, "StructuredChatAgent", { enumerable: true, get: function () { return index_js_5.StructuredChatAgent; } });
44
+ var outputParser_js_4 = require("./structured_chat/outputParser.cjs");
45
+ Object.defineProperty(exports, "StructuredChatOutputParser", { enumerable: true, get: function () { return outputParser_js_4.StructuredChatOutputParser; } });
46
+ Object.defineProperty(exports, "StructuredChatOutputParserWithRetries", { enumerable: true, get: function () { return outputParser_js_4.StructuredChatOutputParserWithRetries; } });
@@ -10,3 +10,5 @@ export { initializeAgentExecutor, initializeAgentExecutorWithOptions, Initialize
10
10
  export { ZeroShotAgent, ZeroShotAgentInput, ZeroShotCreatePromptArgs, } from "./mrkl/index.js";
11
11
  export { ZeroShotAgentOutputParser } from "./mrkl/outputParser.js";
12
12
  export { AgentActionOutputParser, AgentInput, SerializedAgent, SerializedAgentT, SerializedZeroShotAgent, StoppingMethod, } from "./types.js";
13
+ export { StructuredChatAgent, StructuredChatAgentInput, StructuredChatCreatePromptArgs, } from "./structured_chat/index.js";
14
+ export { StructuredChatOutputParser, StructuredChatOutputParserWithRetries, } from "./structured_chat/outputParser.js";
@@ -10,3 +10,5 @@ export { initializeAgentExecutor, initializeAgentExecutorWithOptions, } from "./
10
10
  export { ZeroShotAgent, } from "./mrkl/index.js";
11
11
  export { ZeroShotAgentOutputParser } from "./mrkl/outputParser.js";
12
12
  export { AgentActionOutputParser, } from "./types.js";
13
+ export { StructuredChatAgent, } from "./structured_chat/index.js";
14
+ export { StructuredChatOutputParser, StructuredChatOutputParserWithRetries, } from "./structured_chat/outputParser.js";
@@ -4,8 +4,9 @@ exports.initializeAgentExecutorWithOptions = exports.initializeAgentExecutor = v
4
4
  const buffer_memory_js_1 = require("../memory/buffer_memory.cjs");
5
5
  const index_js_1 = require("./chat/index.cjs");
6
6
  const index_js_2 = require("./chat_convo/index.cjs");
7
+ const index_js_3 = require("./structured_chat/index.cjs");
7
8
  const executor_js_1 = require("./executor.cjs");
8
- const index_js_3 = require("./mrkl/index.cjs");
9
+ const index_js_4 = require("./mrkl/index.cjs");
9
10
  /**
10
11
  * @deprecated use initializeAgentExecutorWithOptions instead
11
12
  */
@@ -16,7 +17,7 @@ const initializeAgentExecutor = async (tools, llm, _agentType, _verbose, _callba
16
17
  switch (agentType) {
17
18
  case "zero-shot-react-description":
18
19
  return executor_js_1.AgentExecutor.fromAgentAndTools({
19
- agent: index_js_3.ZeroShotAgent.fromLLMAndTools(llm, tools),
20
+ agent: index_js_4.ZeroShotAgent.fromLLMAndTools(llm, tools),
20
21
  tools,
21
22
  returnIntermediateSteps: true,
22
23
  verbose,
@@ -42,23 +43,19 @@ const initializeAgentExecutor = async (tools, llm, _agentType, _verbose, _callba
42
43
  }
43
44
  };
44
45
  exports.initializeAgentExecutor = initializeAgentExecutor;
45
- /**
46
- * Initialize an agent executor with options
47
- * @param tools Array of tools to use in the agent
48
- * @param llm LLM or ChatModel to use in the agent
49
- * @param options Options for the agent, including agentType, agentArgs, and other options for AgentExecutor.fromAgentAndTools
50
- * @returns AgentExecutor
51
- */
52
- const initializeAgentExecutorWithOptions = async (tools, llm, options = {
46
+ async function initializeAgentExecutorWithOptions(tools, llm, options = {
53
47
  agentType: llm._modelType() === "base_chat_model"
54
48
  ? "chat-zero-shot-react-description"
55
49
  : "zero-shot-react-description",
56
- }) => {
50
+ }) {
51
+ // Note this tools cast is safe as the overload signatures prevent
52
+ // the function from being called with a StructuredTool[] when
53
+ // the agentType is not in InitializeAgentExecutorOptionsStructured
57
54
  switch (options.agentType) {
58
55
  case "zero-shot-react-description": {
59
56
  const { agentArgs, ...rest } = options;
60
57
  return executor_js_1.AgentExecutor.fromAgentAndTools({
61
- agent: index_js_3.ZeroShotAgent.fromLLMAndTools(llm, tools, agentArgs),
58
+ agent: index_js_4.ZeroShotAgent.fromLLMAndTools(llm, tools, agentArgs),
62
59
  tools,
63
60
  ...rest,
64
61
  });
@@ -86,9 +83,18 @@ const initializeAgentExecutorWithOptions = async (tools, llm, options = {
86
83
  });
87
84
  return executor;
88
85
  }
86
+ case "structured-chat-zero-shot-react-description": {
87
+ const { agentArgs, ...rest } = options;
88
+ const executor = executor_js_1.AgentExecutor.fromAgentAndTools({
89
+ agent: index_js_3.StructuredChatAgent.fromLLMAndTools(llm, tools, agentArgs),
90
+ tools,
91
+ ...rest,
92
+ });
93
+ return executor;
94
+ }
89
95
  default: {
90
96
  throw new Error("Unknown agent type");
91
97
  }
92
98
  }
93
- };
99
+ }
94
100
  exports.initializeAgentExecutorWithOptions = initializeAgentExecutorWithOptions;
@@ -1,8 +1,9 @@
1
1
  import { BaseLanguageModel } from "../base_language/index.js";
2
2
  import { CallbackManager } from "../callbacks/manager.js";
3
- import { Tool } from "../tools/base.js";
3
+ import { StructuredTool, Tool } from "../tools/base.js";
4
4
  import { ChatAgent } from "./chat/index.js";
5
5
  import { ChatConversationalAgent } from "./chat_convo/index.js";
6
+ import { StructuredChatAgent } from "./structured_chat/index.js";
6
7
  import { AgentExecutor, AgentExecutorInput } from "./executor.js";
7
8
  import { ZeroShotAgent } from "./mrkl/index.js";
8
9
  type AgentType = "zero-shot-react-description" | "chat-zero-shot-react-description" | "chat-conversational-react-description";
@@ -25,6 +26,14 @@ export type InitializeAgentExecutorOptions = ({
25
26
  agentType: "chat-conversational-react-description";
26
27
  agentArgs?: Parameters<typeof ChatConversationalAgent.fromLLMAndTools>[2];
27
28
  } & Omit<AgentExecutorInput, "agent" | "tools">);
29
+ /**
30
+ * @interface
31
+ */
32
+ export type InitializeAgentExecutorOptionsStructured = {
33
+ agentType: "structured-chat-zero-shot-react-description";
34
+ agentArgs?: Parameters<typeof StructuredChatAgent.fromLLMAndTools>[2];
35
+ memory?: never;
36
+ } & Omit<AgentExecutorInput, "agent" | "tools">;
28
37
  /**
29
38
  * Initialize an agent executor with options
30
39
  * @param tools Array of tools to use in the agent
@@ -32,5 +41,6 @@ export type InitializeAgentExecutorOptions = ({
32
41
  * @param options Options for the agent, including agentType, agentArgs, and other options for AgentExecutor.fromAgentAndTools
33
42
  * @returns AgentExecutor
34
43
  */
35
- export declare const initializeAgentExecutorWithOptions: (tools: Tool[], llm: BaseLanguageModel, options?: InitializeAgentExecutorOptions) => Promise<AgentExecutor>;
44
+ export declare function initializeAgentExecutorWithOptions(tools: StructuredTool[], llm: BaseLanguageModel, options: InitializeAgentExecutorOptionsStructured): Promise<AgentExecutor>;
45
+ export declare function initializeAgentExecutorWithOptions(tools: Tool[], llm: BaseLanguageModel, options?: InitializeAgentExecutorOptions): Promise<AgentExecutor>;
36
46
  export {};
@@ -1,6 +1,7 @@
1
1
  import { BufferMemory } from "../memory/buffer_memory.js";
2
2
  import { ChatAgent } from "./chat/index.js";
3
3
  import { ChatConversationalAgent } from "./chat_convo/index.js";
4
+ import { StructuredChatAgent } from "./structured_chat/index.js";
4
5
  import { AgentExecutor } from "./executor.js";
5
6
  import { ZeroShotAgent } from "./mrkl/index.js";
6
7
  /**
@@ -38,18 +39,14 @@ export const initializeAgentExecutor = async (tools, llm, _agentType, _verbose,
38
39
  throw new Error("Unknown agent type");
39
40
  }
40
41
  };
41
- /**
42
- * Initialize an agent executor with options
43
- * @param tools Array of tools to use in the agent
44
- * @param llm LLM or ChatModel to use in the agent
45
- * @param options Options for the agent, including agentType, agentArgs, and other options for AgentExecutor.fromAgentAndTools
46
- * @returns AgentExecutor
47
- */
48
- export const initializeAgentExecutorWithOptions = async (tools, llm, options = {
42
+ export async function initializeAgentExecutorWithOptions(tools, llm, options = {
49
43
  agentType: llm._modelType() === "base_chat_model"
50
44
  ? "chat-zero-shot-react-description"
51
45
  : "zero-shot-react-description",
52
- }) => {
46
+ }) {
47
+ // Note this tools cast is safe as the overload signatures prevent
48
+ // the function from being called with a StructuredTool[] when
49
+ // the agentType is not in InitializeAgentExecutorOptionsStructured
53
50
  switch (options.agentType) {
54
51
  case "zero-shot-react-description": {
55
52
  const { agentArgs, ...rest } = options;
@@ -82,8 +79,17 @@ export const initializeAgentExecutorWithOptions = async (tools, llm, options = {
82
79
  });
83
80
  return executor;
84
81
  }
82
+ case "structured-chat-zero-shot-react-description": {
83
+ const { agentArgs, ...rest } = options;
84
+ const executor = AgentExecutor.fromAgentAndTools({
85
+ agent: StructuredChatAgent.fromLLMAndTools(llm, tools, agentArgs),
86
+ tools,
87
+ ...rest,
88
+ });
89
+ return executor;
90
+ }
85
91
  default: {
86
92
  throw new Error("Unknown agent type");
87
93
  }
88
94
  }
89
- };
95
+ }
@@ -30,9 +30,9 @@ class ZeroShotAgent extends agent_js_1.Agent {
30
30
  return new outputParser_js_1.ZeroShotAgentOutputParser(fields);
31
31
  }
32
32
  static validateTools(tools) {
33
- const invalidTool = tools.find((tool) => !tool.description);
34
- if (invalidTool) {
35
- const msg = `Got a tool ${invalidTool.name} without a description.` +
33
+ const descriptionlessTool = tools.find((tool) => !tool.description);
34
+ if (descriptionlessTool) {
35
+ const msg = `Got a tool ${descriptionlessTool.name} without a description.` +
36
36
  ` This agent requires descriptions for all tools.`;
37
37
  throw new Error(msg);
38
38
  }
@@ -19,6 +19,7 @@ export type ZeroShotAgentInput = Optional<AgentInput, "outputParser">;
19
19
  * @augments Agent
20
20
  */
21
21
  export declare class ZeroShotAgent extends Agent {
22
+ ToolType: Tool;
22
23
  constructor(input: ZeroShotAgentInput);
23
24
  _agentType(): "zero-shot-react-description";
24
25
  observationPrefix(): string;
@@ -27,9 +27,9 @@ export class ZeroShotAgent extends Agent {
27
27
  return new ZeroShotAgentOutputParser(fields);
28
28
  }
29
29
  static validateTools(tools) {
30
- const invalidTool = tools.find((tool) => !tool.description);
31
- if (invalidTool) {
32
- const msg = `Got a tool ${invalidTool.name} without a description.` +
30
+ const descriptionlessTool = tools.find((tool) => !tool.description);
31
+ if (descriptionlessTool) {
32
+ const msg = `Got a tool ${descriptionlessTool.name} without a description.` +
33
33
  ` This agent requires descriptions for all tools.`;
34
34
  throw new Error(msg);
35
35
  }
@@ -24,13 +24,13 @@ class ZeroShotAgentOutputParser extends types_js_1.AgentActionOutputParser {
24
24
  log: text,
25
25
  };
26
26
  }
27
- const match = /Action: (.*)\nAction Input: (.*)/s.exec(text);
27
+ const match = /Action: ([\s\S]*?)(?:\nAction Input: ([\s\S]*?))?$/.exec(text);
28
28
  if (!match) {
29
29
  throw new Error(`Could not parse LLM output: ${text}`);
30
30
  }
31
31
  return {
32
32
  tool: match[1].trim(),
33
- toolInput: match[2].trim().replace(/^"+|"+$/g, "") ?? "",
33
+ toolInput: match[2].trim().replace(/^("+)(.*?)(\1)$/, "$2") ?? "",
34
34
  log: text,
35
35
  };
36
36
  }
@@ -21,13 +21,13 @@ export class ZeroShotAgentOutputParser extends AgentActionOutputParser {
21
21
  log: text,
22
22
  };
23
23
  }
24
- const match = /Action: (.*)\nAction Input: (.*)/s.exec(text);
24
+ const match = /Action: ([\s\S]*?)(?:\nAction Input: ([\s\S]*?))?$/.exec(text);
25
25
  if (!match) {
26
26
  throw new Error(`Could not parse LLM output: ${text}`);
27
27
  }
28
28
  return {
29
29
  tool: match[1].trim(),
30
- toolInput: match[2].trim().replace(/^"+|"+$/g, "") ?? "",
30
+ toolInput: match[2].trim().replace(/^("+)(.*?)(\1)$/, "$2") ?? "",
31
31
  log: text,
32
32
  };
33
33
  }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StructuredChatAgent = void 0;
4
+ const zod_to_json_schema_1 = require("zod-to-json-schema");
5
+ const llm_chain_js_1 = require("../../chains/llm_chain.cjs");
6
+ const prompt_js_1 = require("../../prompts/prompt.cjs");
7
+ const chat_js_1 = require("../../prompts/chat.cjs");
8
+ const agent_js_1 = require("../agent.cjs");
9
+ const outputParser_js_1 = require("./outputParser.cjs");
10
+ const prompt_js_2 = require("./prompt.cjs");
11
+ /**
12
+ * Agent that interoperates with Structured Tools using React logic.
13
+ * @augments Agent
14
+ */
15
+ class StructuredChatAgent extends agent_js_1.Agent {
16
+ constructor(input) {
17
+ const outputParser = input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();
18
+ super({ ...input, outputParser });
19
+ }
20
+ _agentType() {
21
+ return "structured-chat-zero-shot-react-description";
22
+ }
23
+ observationPrefix() {
24
+ return "Observation: ";
25
+ }
26
+ llmPrefix() {
27
+ return "Thought:";
28
+ }
29
+ _stop() {
30
+ return ["Observation:"];
31
+ }
32
+ static validateTools(tools) {
33
+ const descriptionlessTool = tools.find((tool) => !tool.description);
34
+ if (descriptionlessTool) {
35
+ const msg = `Got a tool ${descriptionlessTool.name} without a description.` +
36
+ ` This agent requires descriptions for all tools.`;
37
+ throw new Error(msg);
38
+ }
39
+ }
40
+ static getDefaultOutputParser(fields) {
41
+ if (fields?.llm) {
42
+ return outputParser_js_1.StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {
43
+ toolNames: fields.toolNames,
44
+ });
45
+ }
46
+ return new outputParser_js_1.StructuredChatOutputParserWithRetries({
47
+ toolNames: fields?.toolNames,
48
+ });
49
+ }
50
+ async constructScratchPad(steps) {
51
+ const agentScratchpad = await super.constructScratchPad(steps);
52
+ if (agentScratchpad) {
53
+ return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\n${agentScratchpad}`;
54
+ }
55
+ return agentScratchpad;
56
+ }
57
+ static createToolSchemasString(tools) {
58
+ return tools
59
+ .map((tool) => `${tool.name}: ${tool.description}, args: ${JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(tool.schema).properties)}`)
60
+ .join("\n");
61
+ }
62
+ /**
63
+ * Create prompt in the style of the agent.
64
+ *
65
+ * @param tools - List of tools the agent will have access to, used to format the prompt.
66
+ * @param args - Arguments to create the prompt with.
67
+ * @param args.suffix - String to put after the list of tools.
68
+ * @param args.prefix - String to put before the list of tools.
69
+ */
70
+ static createPrompt(tools, args) {
71
+ const { prefix = prompt_js_2.PREFIX, suffix = prompt_js_2.SUFFIX } = args ?? {};
72
+ const template = [prefix, prompt_js_2.FORMAT_INSTRUCTIONS, suffix].join("\n\n");
73
+ const messages = [
74
+ new chat_js_1.SystemMessagePromptTemplate(new prompt_js_1.PromptTemplate({
75
+ template,
76
+ inputVariables: [],
77
+ partialVariables: {
78
+ tool_schemas: StructuredChatAgent.createToolSchemasString(tools),
79
+ tool_names: tools.map((tool) => tool.name).join(", "),
80
+ },
81
+ })),
82
+ chat_js_1.HumanMessagePromptTemplate.fromTemplate("{input}\n\n{agent_scratchpad}"),
83
+ ];
84
+ return chat_js_1.ChatPromptTemplate.fromPromptMessages(messages);
85
+ }
86
+ static fromLLMAndTools(llm, tools, args) {
87
+ StructuredChatAgent.validateTools(tools);
88
+ const prompt = StructuredChatAgent.createPrompt(tools, args);
89
+ const outputParser = args?.outputParser ??
90
+ StructuredChatAgent.getDefaultOutputParser({
91
+ llm,
92
+ toolNames: tools.map((tool) => tool.name),
93
+ });
94
+ const chain = new llm_chain_js_1.LLMChain({
95
+ prompt,
96
+ llm,
97
+ callbacks: args?.callbacks,
98
+ });
99
+ return new StructuredChatAgent({
100
+ llmChain: chain,
101
+ outputParser,
102
+ allowedTools: tools.map((t) => t.name),
103
+ });
104
+ }
105
+ }
106
+ exports.StructuredChatAgent = StructuredChatAgent;
@@ -0,0 +1,44 @@
1
+ import { BaseLanguageModel } from "../../base_language/index.js";
2
+ import { ChatPromptTemplate } from "../../prompts/chat.js";
3
+ import { AgentStep } from "../../schema/index.js";
4
+ import { StructuredTool } from "../../tools/base.js";
5
+ import { Optional } from "../../types/type-utils.js";
6
+ import { Agent, AgentArgs, OutputParserArgs } from "../agent.js";
7
+ import { AgentInput } from "../types.js";
8
+ import { StructuredChatOutputParserWithRetries } from "./outputParser.js";
9
+ export interface StructuredChatCreatePromptArgs {
10
+ /** String to put after the list of tools. */
11
+ suffix?: string;
12
+ /** String to put before the list of tools. */
13
+ prefix?: string;
14
+ /** List of input variables the final prompt will expect. */
15
+ inputVariables?: string[];
16
+ }
17
+ export type StructuredChatAgentInput = Optional<AgentInput, "outputParser">;
18
+ /**
19
+ * Agent that interoperates with Structured Tools using React logic.
20
+ * @augments Agent
21
+ */
22
+ export declare class StructuredChatAgent extends Agent {
23
+ constructor(input: StructuredChatAgentInput);
24
+ _agentType(): "structured-chat-zero-shot-react-description";
25
+ observationPrefix(): string;
26
+ llmPrefix(): string;
27
+ _stop(): string[];
28
+ static validateTools(tools: StructuredTool[]): void;
29
+ static getDefaultOutputParser(fields?: OutputParserArgs & {
30
+ toolNames: string[];
31
+ }): StructuredChatOutputParserWithRetries;
32
+ constructScratchPad(steps: AgentStep[]): Promise<string>;
33
+ static createToolSchemasString(tools: StructuredTool[]): string;
34
+ /**
35
+ * Create prompt in the style of the agent.
36
+ *
37
+ * @param tools - List of tools the agent will have access to, used to format the prompt.
38
+ * @param args - Arguments to create the prompt with.
39
+ * @param args.suffix - String to put after the list of tools.
40
+ * @param args.prefix - String to put before the list of tools.
41
+ */
42
+ static createPrompt(tools: StructuredTool[], args?: StructuredChatCreatePromptArgs): ChatPromptTemplate;
43
+ static fromLLMAndTools(llm: BaseLanguageModel, tools: StructuredTool[], args?: StructuredChatCreatePromptArgs & AgentArgs): StructuredChatAgent;
44
+ }
@@ -0,0 +1,102 @@
1
+ import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { LLMChain } from "../../chains/llm_chain.js";
3
+ import { PromptTemplate } from "../../prompts/prompt.js";
4
+ import { ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate, } from "../../prompts/chat.js";
5
+ import { Agent } from "../agent.js";
6
+ import { StructuredChatOutputParserWithRetries } from "./outputParser.js";
7
+ import { FORMAT_INSTRUCTIONS, PREFIX, SUFFIX } from "./prompt.js";
8
+ /**
9
+ * Agent that interoperates with Structured Tools using React logic.
10
+ * @augments Agent
11
+ */
12
+ export class StructuredChatAgent extends Agent {
13
+ constructor(input) {
14
+ const outputParser = input?.outputParser ?? StructuredChatAgent.getDefaultOutputParser();
15
+ super({ ...input, outputParser });
16
+ }
17
+ _agentType() {
18
+ return "structured-chat-zero-shot-react-description";
19
+ }
20
+ observationPrefix() {
21
+ return "Observation: ";
22
+ }
23
+ llmPrefix() {
24
+ return "Thought:";
25
+ }
26
+ _stop() {
27
+ return ["Observation:"];
28
+ }
29
+ static validateTools(tools) {
30
+ const descriptionlessTool = tools.find((tool) => !tool.description);
31
+ if (descriptionlessTool) {
32
+ const msg = `Got a tool ${descriptionlessTool.name} without a description.` +
33
+ ` This agent requires descriptions for all tools.`;
34
+ throw new Error(msg);
35
+ }
36
+ }
37
+ static getDefaultOutputParser(fields) {
38
+ if (fields?.llm) {
39
+ return StructuredChatOutputParserWithRetries.fromLLM(fields.llm, {
40
+ toolNames: fields.toolNames,
41
+ });
42
+ }
43
+ return new StructuredChatOutputParserWithRetries({
44
+ toolNames: fields?.toolNames,
45
+ });
46
+ }
47
+ async constructScratchPad(steps) {
48
+ const agentScratchpad = await super.constructScratchPad(steps);
49
+ if (agentScratchpad) {
50
+ return `This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\n${agentScratchpad}`;
51
+ }
52
+ return agentScratchpad;
53
+ }
54
+ static createToolSchemasString(tools) {
55
+ return tools
56
+ .map((tool) => `${tool.name}: ${tool.description}, args: ${JSON.stringify(zodToJsonSchema(tool.schema).properties)}`)
57
+ .join("\n");
58
+ }
59
+ /**
60
+ * Create prompt in the style of the agent.
61
+ *
62
+ * @param tools - List of tools the agent will have access to, used to format the prompt.
63
+ * @param args - Arguments to create the prompt with.
64
+ * @param args.suffix - String to put after the list of tools.
65
+ * @param args.prefix - String to put before the list of tools.
66
+ */
67
+ static createPrompt(tools, args) {
68
+ const { prefix = PREFIX, suffix = SUFFIX } = args ?? {};
69
+ const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join("\n\n");
70
+ const messages = [
71
+ new SystemMessagePromptTemplate(new PromptTemplate({
72
+ template,
73
+ inputVariables: [],
74
+ partialVariables: {
75
+ tool_schemas: StructuredChatAgent.createToolSchemasString(tools),
76
+ tool_names: tools.map((tool) => tool.name).join(", "),
77
+ },
78
+ })),
79
+ HumanMessagePromptTemplate.fromTemplate("{input}\n\n{agent_scratchpad}"),
80
+ ];
81
+ return ChatPromptTemplate.fromPromptMessages(messages);
82
+ }
83
+ static fromLLMAndTools(llm, tools, args) {
84
+ StructuredChatAgent.validateTools(tools);
85
+ const prompt = StructuredChatAgent.createPrompt(tools, args);
86
+ const outputParser = args?.outputParser ??
87
+ StructuredChatAgent.getDefaultOutputParser({
88
+ llm,
89
+ toolNames: tools.map((tool) => tool.name),
90
+ });
91
+ const chain = new LLMChain({
92
+ prompt,
93
+ llm,
94
+ callbacks: args?.callbacks,
95
+ });
96
+ return new StructuredChatAgent({
97
+ llmChain: chain,
98
+ outputParser,
99
+ allowedTools: tools.map((t) => t.name),
100
+ });
101
+ }
102
+ }