langchain 0.0.212 → 0.0.214

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 (138) hide show
  1. package/README.md +1 -1
  2. package/chains/combine_documents.cjs +1 -0
  3. package/chains/combine_documents.d.ts +1 -0
  4. package/chains/combine_documents.js +1 -0
  5. package/chains/history_aware_retriever.cjs +1 -0
  6. package/chains/history_aware_retriever.d.ts +1 -0
  7. package/chains/history_aware_retriever.js +1 -0
  8. package/chains/retrieval.cjs +1 -0
  9. package/chains/retrieval.d.ts +1 -0
  10. package/chains/retrieval.js +1 -0
  11. package/dist/agents/agent.cjs +1 -0
  12. package/dist/agents/agent.js +1 -0
  13. package/dist/agents/executor.cjs +21 -3
  14. package/dist/agents/executor.d.ts +1 -0
  15. package/dist/agents/executor.js +21 -3
  16. package/dist/agents/format_scratchpad/openai_functions.cjs +22 -1
  17. package/dist/agents/format_scratchpad/openai_functions.d.ts +10 -0
  18. package/dist/agents/format_scratchpad/openai_functions.js +21 -1
  19. package/dist/agents/index.cjs +11 -4
  20. package/dist/agents/index.d.ts +6 -3
  21. package/dist/agents/index.js +5 -3
  22. package/dist/agents/initialize.cjs +1 -1
  23. package/dist/agents/initialize.d.ts +1 -1
  24. package/dist/agents/initialize.js +1 -1
  25. package/dist/agents/openai/output_parser.cjs +20 -196
  26. package/dist/agents/openai/output_parser.d.ts +2 -111
  27. package/dist/agents/openai/output_parser.js +6 -193
  28. package/dist/agents/{openai → openai_functions}/index.cjs +80 -2
  29. package/dist/agents/{openai → openai_functions}/index.d.ts +77 -3
  30. package/dist/agents/{openai → openai_functions}/index.js +78 -1
  31. package/dist/agents/openai_functions/output_parser.cjs +102 -0
  32. package/dist/agents/openai_functions/output_parser.d.ts +56 -0
  33. package/dist/agents/openai_functions/output_parser.js +98 -0
  34. package/dist/agents/openai_tools/index.cjs +83 -0
  35. package/dist/agents/openai_tools/index.d.ts +82 -0
  36. package/dist/agents/openai_tools/index.js +79 -0
  37. package/dist/agents/openai_tools/output_parser.cjs +102 -0
  38. package/dist/agents/openai_tools/output_parser.d.ts +57 -0
  39. package/dist/agents/openai_tools/output_parser.js +98 -0
  40. package/dist/agents/react/index.cjs +77 -0
  41. package/dist/agents/react/index.d.ts +62 -0
  42. package/dist/agents/react/index.js +73 -0
  43. package/dist/agents/react/output_parser.cjs +0 -1
  44. package/dist/agents/react/output_parser.d.ts +0 -1
  45. package/dist/agents/react/output_parser.js +0 -1
  46. package/dist/agents/structured_chat/index.cjs +87 -1
  47. package/dist/agents/structured_chat/index.d.ts +73 -0
  48. package/dist/agents/structured_chat/index.js +85 -0
  49. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.cjs +1 -1
  50. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.js +1 -1
  51. package/dist/agents/toolkits/conversational_retrieval/tool.cjs +1 -0
  52. package/dist/agents/toolkits/conversational_retrieval/tool.d.ts +1 -0
  53. package/dist/agents/toolkits/conversational_retrieval/tool.js +1 -0
  54. package/dist/agents/toolkits/json/json.cjs +2 -0
  55. package/dist/agents/toolkits/json/json.d.ts +2 -0
  56. package/dist/agents/toolkits/json/json.js +2 -0
  57. package/dist/agents/toolkits/openapi/openapi.cjs +2 -0
  58. package/dist/agents/toolkits/openapi/openapi.d.ts +2 -0
  59. package/dist/agents/toolkits/openapi/openapi.js +2 -0
  60. package/dist/agents/toolkits/vectorstore/vectorstore.cjs +2 -0
  61. package/dist/agents/toolkits/vectorstore/vectorstore.d.ts +2 -0
  62. package/dist/agents/toolkits/vectorstore/vectorstore.js +2 -0
  63. package/dist/agents/xml/index.cjs +77 -1
  64. package/dist/agents/xml/index.d.ts +67 -0
  65. package/dist/agents/xml/index.js +75 -0
  66. package/dist/callbacks/index.cjs +1 -4
  67. package/dist/callbacks/index.d.ts +1 -2
  68. package/dist/callbacks/index.js +1 -2
  69. package/dist/chains/combine_documents/base.cjs +16 -0
  70. package/dist/chains/combine_documents/base.d.ts +13 -0
  71. package/dist/chains/combine_documents/base.js +12 -0
  72. package/dist/chains/combine_documents/index.cjs +5 -0
  73. package/dist/chains/combine_documents/index.d.ts +1 -0
  74. package/dist/chains/combine_documents/index.js +1 -0
  75. package/dist/chains/combine_documents/reduce.cjs +5 -2
  76. package/dist/chains/combine_documents/reduce.js +4 -1
  77. package/dist/chains/combine_documents/stuff.cjs +42 -0
  78. package/dist/chains/combine_documents/stuff.d.ts +28 -0
  79. package/dist/chains/combine_documents/stuff.js +38 -0
  80. package/dist/chains/conversational_retrieval_chain.cjs +3 -3
  81. package/dist/chains/conversational_retrieval_chain.js +1 -1
  82. package/dist/chains/history_aware_retriever.cjs +55 -0
  83. package/dist/chains/history_aware_retriever.d.ts +55 -0
  84. package/dist/chains/history_aware_retriever.js +51 -0
  85. package/dist/chains/openai_functions/structured_output.cjs +63 -21
  86. package/dist/chains/openai_functions/structured_output.d.ts +25 -17
  87. package/dist/chains/openai_functions/structured_output.js +62 -20
  88. package/dist/chains/retrieval.cjs +60 -0
  89. package/dist/chains/retrieval.d.ts +65 -0
  90. package/dist/chains/retrieval.js +56 -0
  91. package/dist/experimental/autogpt/prompt.cjs +1 -1
  92. package/dist/experimental/autogpt/prompt.d.ts +1 -1
  93. package/dist/experimental/autogpt/prompt.js +1 -1
  94. package/dist/load/import_map.cjs +7 -3
  95. package/dist/load/import_map.d.ts +4 -0
  96. package/dist/load/import_map.js +4 -0
  97. package/dist/output_parsers/json.cjs +2 -78
  98. package/dist/output_parsers/json.d.ts +1 -1
  99. package/dist/output_parsers/json.js +1 -77
  100. package/dist/output_parsers/openai_functions.d.ts +1 -1
  101. package/dist/retrievers/multi_vector.cjs +11 -2
  102. package/dist/retrievers/multi_vector.d.ts +5 -3
  103. package/dist/retrievers/multi_vector.js +11 -2
  104. package/dist/retrievers/parent_document.cjs +1 -2
  105. package/dist/retrievers/parent_document.d.ts +1 -1
  106. package/dist/retrievers/parent_document.js +1 -2
  107. package/dist/retrievers/remote/chatgpt-plugin.cjs +5 -4
  108. package/dist/retrievers/remote/chatgpt-plugin.d.ts +5 -2
  109. package/dist/retrievers/remote/chatgpt-plugin.js +3 -2
  110. package/dist/retrievers/remote/index.cjs +2 -2
  111. package/dist/retrievers/remote/index.d.ts +1 -1
  112. package/dist/retrievers/remote/index.js +1 -1
  113. package/dist/retrievers/remote/remote-retriever.cjs +3 -2
  114. package/dist/retrievers/remote/remote-retriever.d.ts +3 -1
  115. package/dist/retrievers/remote/remote-retriever.js +2 -1
  116. package/dist/retrievers/vespa.cjs +15 -78
  117. package/dist/retrievers/vespa.d.ts +1 -54
  118. package/dist/retrievers/vespa.js +1 -76
  119. package/dist/schema/runnable/config.d.ts +1 -1
  120. package/dist/tools/retriever.cjs +17 -0
  121. package/dist/tools/retriever.d.ts +10 -0
  122. package/dist/tools/retriever.js +13 -0
  123. package/dist/util/entrypoint_deprecation.cjs +18 -0
  124. package/dist/util/entrypoint_deprecation.d.ts +5 -0
  125. package/dist/util/entrypoint_deprecation.js +14 -0
  126. package/package.json +36 -4
  127. package/tools/retriever.cjs +1 -0
  128. package/tools/retriever.d.ts +1 -0
  129. package/tools/retriever.js +1 -0
  130. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +0 -17
  131. package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +0 -1
  132. package/dist/callbacks/handlers/tracer_langchain_v1.js +0 -1
  133. package/dist/retrievers/remote/base.cjs +0 -68
  134. package/dist/retrievers/remote/base.d.ts +0 -60
  135. package/dist/retrievers/remote/base.js +0 -64
  136. /package/dist/agents/{openai → openai_functions}/prompt.cjs +0 -0
  137. /package/dist/agents/{openai → openai_functions}/prompt.d.ts +0 -0
  138. /package/dist/agents/{openai → openai_functions}/prompt.js +0 -0
@@ -0,0 +1,102 @@
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
+ /**
8
+ * @example
9
+ * ```typescript
10
+ *
11
+ * const prompt = ChatPromptTemplate.fromMessages([
12
+ * ["ai", "You are a helpful assistant"],
13
+ * ["human", "{input}"],
14
+ * new MessagesPlaceholder("agent_scratchpad"),
15
+ * ]);
16
+ *
17
+ * const modelWithFunctions = new ChatOpenAI({
18
+ * modelName: "gpt-4",
19
+ * temperature: 0,
20
+ * }).bind({
21
+ * functions: tools.map((tool) => formatToOpenAIFunction(tool)),
22
+ * });
23
+ *
24
+ * const runnableAgent = RunnableSequence.from([
25
+ * {
26
+ * input: (i) => i.input,
27
+ * agent_scratchpad: (i) => formatAgentSteps(i.steps),
28
+ * },
29
+ * prompt,
30
+ * modelWithFunctions,
31
+ * new OpenAIFunctionsAgentOutputParser(),
32
+ * ]);
33
+ *
34
+ * const result = await runnableAgent.invoke({
35
+ * input: "What is the weather in New York?",
36
+ * steps: agentSteps,
37
+ * });
38
+ *
39
+ * ```
40
+ */
41
+ class OpenAIFunctionsAgentOutputParser extends types_js_1.AgentActionOutputParser {
42
+ constructor() {
43
+ super(...arguments);
44
+ Object.defineProperty(this, "lc_namespace", {
45
+ enumerable: true,
46
+ configurable: true,
47
+ writable: true,
48
+ value: ["langchain", "agents", "openai"]
49
+ });
50
+ }
51
+ static lc_name() {
52
+ return "OpenAIFunctionsAgentOutputParser";
53
+ }
54
+ async parse(text) {
55
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
56
+ }
57
+ async parseResult(generations) {
58
+ if ("message" in generations[0] && (0, index_js_1.isBaseMessage)(generations[0].message)) {
59
+ return this.parseAIMessage(generations[0].message);
60
+ }
61
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
62
+ }
63
+ /**
64
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
65
+ * object.
66
+ * @param message The BaseMessage to parse.
67
+ * @returns A FunctionsAgentAction or AgentFinish object.
68
+ */
69
+ parseAIMessage(message) {
70
+ if (message.content && typeof message.content !== "string") {
71
+ throw new Error("This agent cannot parse non-string model responses.");
72
+ }
73
+ if (message.additional_kwargs.function_call) {
74
+ // eslint-disable-next-line prefer-destructuring
75
+ const function_call = message.additional_kwargs.function_call;
76
+ try {
77
+ const toolInput = function_call.arguments
78
+ ? JSON.parse(function_call.arguments)
79
+ : {};
80
+ return {
81
+ tool: function_call.name,
82
+ toolInput,
83
+ log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
84
+ messageLog: [message],
85
+ };
86
+ }
87
+ catch (error) {
88
+ throw new output_parser_js_1.OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
89
+ }
90
+ }
91
+ else {
92
+ return {
93
+ returnValues: { output: message.content },
94
+ log: message.content,
95
+ };
96
+ }
97
+ }
98
+ getFormatInstructions() {
99
+ throw new Error("getFormatInstructions not implemented inside OpenAIFunctionsAgentOutputParser.");
100
+ }
101
+ }
102
+ exports.OpenAIFunctionsAgentOutputParser = OpenAIFunctionsAgentOutputParser;
@@ -0,0 +1,56 @@
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
+ /**
10
+ * @example
11
+ * ```typescript
12
+ *
13
+ * const prompt = ChatPromptTemplate.fromMessages([
14
+ * ["ai", "You are a helpful assistant"],
15
+ * ["human", "{input}"],
16
+ * new MessagesPlaceholder("agent_scratchpad"),
17
+ * ]);
18
+ *
19
+ * const modelWithFunctions = new ChatOpenAI({
20
+ * modelName: "gpt-4",
21
+ * temperature: 0,
22
+ * }).bind({
23
+ * functions: tools.map((tool) => formatToOpenAIFunction(tool)),
24
+ * });
25
+ *
26
+ * const runnableAgent = RunnableSequence.from([
27
+ * {
28
+ * input: (i) => i.input,
29
+ * agent_scratchpad: (i) => formatAgentSteps(i.steps),
30
+ * },
31
+ * prompt,
32
+ * modelWithFunctions,
33
+ * new OpenAIFunctionsAgentOutputParser(),
34
+ * ]);
35
+ *
36
+ * const result = await runnableAgent.invoke({
37
+ * input: "What is the weather in New York?",
38
+ * steps: agentSteps,
39
+ * });
40
+ *
41
+ * ```
42
+ */
43
+ export declare class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
44
+ lc_namespace: string[];
45
+ static lc_name(): string;
46
+ parse(text: string): Promise<AgentAction | AgentFinish>;
47
+ parseResult(generations: ChatGeneration[]): Promise<AgentFinish | FunctionsAgentAction>;
48
+ /**
49
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
50
+ * object.
51
+ * @param message The BaseMessage to parse.
52
+ * @returns A FunctionsAgentAction or AgentFinish object.
53
+ */
54
+ parseAIMessage(message: BaseMessage): FunctionsAgentAction | AgentFinish;
55
+ getFormatInstructions(): string;
56
+ }
@@ -0,0 +1,98 @@
1
+ import { isBaseMessage, } from "../../schema/index.js";
2
+ import { AgentActionOutputParser } from "../types.js";
3
+ import { OutputParserException } from "../../schema/output_parser.js";
4
+ /**
5
+ * @example
6
+ * ```typescript
7
+ *
8
+ * const prompt = ChatPromptTemplate.fromMessages([
9
+ * ["ai", "You are a helpful assistant"],
10
+ * ["human", "{input}"],
11
+ * new MessagesPlaceholder("agent_scratchpad"),
12
+ * ]);
13
+ *
14
+ * const modelWithFunctions = new ChatOpenAI({
15
+ * modelName: "gpt-4",
16
+ * temperature: 0,
17
+ * }).bind({
18
+ * functions: tools.map((tool) => formatToOpenAIFunction(tool)),
19
+ * });
20
+ *
21
+ * const runnableAgent = RunnableSequence.from([
22
+ * {
23
+ * input: (i) => i.input,
24
+ * agent_scratchpad: (i) => formatAgentSteps(i.steps),
25
+ * },
26
+ * prompt,
27
+ * modelWithFunctions,
28
+ * new OpenAIFunctionsAgentOutputParser(),
29
+ * ]);
30
+ *
31
+ * const result = await runnableAgent.invoke({
32
+ * input: "What is the weather in New York?",
33
+ * steps: agentSteps,
34
+ * });
35
+ *
36
+ * ```
37
+ */
38
+ export class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
39
+ constructor() {
40
+ super(...arguments);
41
+ Object.defineProperty(this, "lc_namespace", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: ["langchain", "agents", "openai"]
46
+ });
47
+ }
48
+ static lc_name() {
49
+ return "OpenAIFunctionsAgentOutputParser";
50
+ }
51
+ async parse(text) {
52
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
53
+ }
54
+ async parseResult(generations) {
55
+ if ("message" in generations[0] && isBaseMessage(generations[0].message)) {
56
+ return this.parseAIMessage(generations[0].message);
57
+ }
58
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
59
+ }
60
+ /**
61
+ * Parses the output message into a FunctionsAgentAction or AgentFinish
62
+ * object.
63
+ * @param message The BaseMessage to parse.
64
+ * @returns A FunctionsAgentAction or AgentFinish object.
65
+ */
66
+ parseAIMessage(message) {
67
+ if (message.content && typeof message.content !== "string") {
68
+ throw new Error("This agent cannot parse non-string model responses.");
69
+ }
70
+ if (message.additional_kwargs.function_call) {
71
+ // eslint-disable-next-line prefer-destructuring
72
+ const function_call = message.additional_kwargs.function_call;
73
+ try {
74
+ const toolInput = function_call.arguments
75
+ ? JSON.parse(function_call.arguments)
76
+ : {};
77
+ return {
78
+ tool: function_call.name,
79
+ toolInput,
80
+ log: `Invoking "${function_call.name}" with ${function_call.arguments ?? "{}"}\n${message.content}`,
81
+ messageLog: [message],
82
+ };
83
+ }
84
+ catch (error) {
85
+ throw new OutputParserException(`Failed to parse function arguments from chat model response. Text: "${function_call.arguments}". ${error}`);
86
+ }
87
+ }
88
+ else {
89
+ return {
90
+ returnValues: { output: message.content },
91
+ log: message.content,
92
+ };
93
+ }
94
+ }
95
+ getFormatInstructions() {
96
+ throw new Error("getFormatInstructions not implemented inside OpenAIFunctionsAgentOutputParser.");
97
+ }
98
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createOpenAIToolsAgent = exports.OpenAIToolsAgentOutputParser = void 0;
4
+ const runnables_1 = require("@langchain/core/runnables");
5
+ const openai_tools_js_1 = require("../format_scratchpad/openai_tools.cjs");
6
+ const convert_to_openai_js_1 = require("../../tools/convert_to_openai.cjs");
7
+ const output_parser_js_1 = require("../openai/output_parser.cjs");
8
+ Object.defineProperty(exports, "OpenAIToolsAgentOutputParser", { enumerable: true, get: function () { return output_parser_js_1.OpenAIToolsAgentOutputParser; } });
9
+ /**
10
+ * Create an agent that uses OpenAI-style tool calling.
11
+ * @param params Params required to create the agent. Includes an LLM, tools, and prompt.
12
+ * @returns A runnable sequence representing an agent. It takes as input all the same input
13
+ * variables as the prompt passed in does. It returns as output either an
14
+ * AgentAction or AgentFinish.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
19
+ * import { pull } from "langchain/hub";
20
+ * import type { ChatPromptTemplate } from "@langchain/core/prompts";
21
+ * import { AIMessage, HumanMessage } from "@langchain/core/messages";
22
+ *
23
+ * import { ChatOpenAI } from "@langchain/openai";
24
+ *
25
+ * // Define the tools the agent will have access to.
26
+ * const tools = [...];
27
+ *
28
+ * // Get the prompt to use - you can modify this!
29
+ * // If you want to see the prompt in full, you can at:
30
+ * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent
31
+ * const prompt = await pull<ChatPromptTemplate>(
32
+ * "hwchase17/openai-tools-agent"
33
+ * );
34
+ *
35
+ * const llm = new ChatOpenAI({
36
+ * temperature: 0,
37
+ * modelName: "gpt-3.5-turbo-1106",
38
+ * });
39
+ *
40
+ * const agent = await createOpenAIToolsAgent({
41
+ * llm,
42
+ * tools,
43
+ * prompt,
44
+ * });
45
+ *
46
+ * const agentExecutor = new AgentExecutor({
47
+ * agent,
48
+ * tools,
49
+ * });
50
+ *
51
+ * const result = await agentExecutor.invoke({
52
+ * input: "what is LangChain?",
53
+ * });
54
+ *
55
+ * // With chat history
56
+ * const result2 = await agentExecutor.invoke({
57
+ * input: "what's my name?",
58
+ * chat_history: [
59
+ * new HumanMessage("hi! my name is cob"),
60
+ * new AIMessage("Hello Cob! How can I assist you today?"),
61
+ * ],
62
+ * });
63
+ * ```
64
+ */
65
+ async function createOpenAIToolsAgent({ llm, tools, prompt, }) {
66
+ if (!prompt.inputVariables.includes("agent_scratchpad")) {
67
+ throw new Error([
68
+ `Prompt must have an input variable named "agent_scratchpad".`,
69
+ `Found ${JSON.stringify(prompt.inputVariables)} instead.`,
70
+ ].join("\n"));
71
+ }
72
+ const modelWithTools = llm.bind({ tools: tools.map(convert_to_openai_js_1.formatToOpenAITool) });
73
+ const agent = runnables_1.RunnableSequence.from([
74
+ runnables_1.RunnablePassthrough.assign({
75
+ agent_scratchpad: (input) => (0, openai_tools_js_1.formatToOpenAIToolMessages)(input.steps),
76
+ }),
77
+ prompt,
78
+ modelWithTools,
79
+ new output_parser_js_1.OpenAIToolsAgentOutputParser(),
80
+ ]);
81
+ return agent;
82
+ }
83
+ exports.createOpenAIToolsAgent = createOpenAIToolsAgent;
@@ -0,0 +1,82 @@
1
+ import type { StructuredToolInterface } from "@langchain/core/tools";
2
+ import type { BaseChatModel, BaseChatModelCallOptions } from "@langchain/core/language_models/chat_models";
3
+ import { ChatPromptTemplate } from "@langchain/core/prompts";
4
+ import { RunnableSequence } from "@langchain/core/runnables";
5
+ import { OpenAIClient } from "@langchain/openai";
6
+ import { OpenAIToolsAgentOutputParser, type ToolsAgentStep } from "../openai/output_parser.js";
7
+ export { OpenAIToolsAgentOutputParser, type ToolsAgentStep };
8
+ /**
9
+ * Params used by the createOpenAIToolsAgent function.
10
+ */
11
+ export type CreateOpenAIToolsAgentParams = {
12
+ /**
13
+ * LLM to use as the agent. Should work with OpenAI tool calling,
14
+ * so must either be an OpenAI model that supports that or a wrapper of
15
+ * a different model that adds in equivalent support.
16
+ */
17
+ llm: BaseChatModel<BaseChatModelCallOptions & {
18
+ tools?: StructuredToolInterface[] | OpenAIClient.ChatCompletionTool[];
19
+ tool_choice?: OpenAIClient.ChatCompletionToolChoiceOption;
20
+ }>;
21
+ /** Tools this agent has access to. */
22
+ tools: StructuredToolInterface[];
23
+ /** The prompt to use, must have an input key of `agent_scratchpad`. */
24
+ prompt: ChatPromptTemplate;
25
+ };
26
+ /**
27
+ * Create an agent that uses OpenAI-style tool calling.
28
+ * @param params Params required to create the agent. Includes an LLM, tools, and prompt.
29
+ * @returns A runnable sequence representing an agent. It takes as input all the same input
30
+ * variables as the prompt passed in does. It returns as output either an
31
+ * AgentAction or AgentFinish.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
36
+ * import { pull } from "langchain/hub";
37
+ * import type { ChatPromptTemplate } from "@langchain/core/prompts";
38
+ * import { AIMessage, HumanMessage } from "@langchain/core/messages";
39
+ *
40
+ * import { ChatOpenAI } from "@langchain/openai";
41
+ *
42
+ * // Define the tools the agent will have access to.
43
+ * const tools = [...];
44
+ *
45
+ * // Get the prompt to use - you can modify this!
46
+ * // If you want to see the prompt in full, you can at:
47
+ * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent
48
+ * const prompt = await pull<ChatPromptTemplate>(
49
+ * "hwchase17/openai-tools-agent"
50
+ * );
51
+ *
52
+ * const llm = new ChatOpenAI({
53
+ * temperature: 0,
54
+ * modelName: "gpt-3.5-turbo-1106",
55
+ * });
56
+ *
57
+ * const agent = await createOpenAIToolsAgent({
58
+ * llm,
59
+ * tools,
60
+ * prompt,
61
+ * });
62
+ *
63
+ * const agentExecutor = new AgentExecutor({
64
+ * agent,
65
+ * tools,
66
+ * });
67
+ *
68
+ * const result = await agentExecutor.invoke({
69
+ * input: "what is LangChain?",
70
+ * });
71
+ *
72
+ * // With chat history
73
+ * const result2 = await agentExecutor.invoke({
74
+ * input: "what's my name?",
75
+ * chat_history: [
76
+ * new HumanMessage("hi! my name is cob"),
77
+ * new AIMessage("Hello Cob! How can I assist you today?"),
78
+ * ],
79
+ * });
80
+ * ```
81
+ */
82
+ export declare function createOpenAIToolsAgent({ llm, tools, prompt, }: CreateOpenAIToolsAgentParams): Promise<RunnableSequence<Record<string, unknown>, import("@langchain/core/agents").AgentFinish | import("@langchain/core/agents").AgentAction[]>>;
@@ -0,0 +1,79 @@
1
+ import { RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables";
2
+ import { formatToOpenAIToolMessages } from "../format_scratchpad/openai_tools.js";
3
+ import { formatToOpenAITool } from "../../tools/convert_to_openai.js";
4
+ import { OpenAIToolsAgentOutputParser, } from "../openai/output_parser.js";
5
+ export { OpenAIToolsAgentOutputParser };
6
+ /**
7
+ * Create an agent that uses OpenAI-style tool calling.
8
+ * @param params Params required to create the agent. Includes an LLM, tools, and prompt.
9
+ * @returns A runnable sequence representing an agent. It takes as input all the same input
10
+ * variables as the prompt passed in does. It returns as output either an
11
+ * AgentAction or AgentFinish.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
16
+ * import { pull } from "langchain/hub";
17
+ * import type { ChatPromptTemplate } from "@langchain/core/prompts";
18
+ * import { AIMessage, HumanMessage } from "@langchain/core/messages";
19
+ *
20
+ * import { ChatOpenAI } from "@langchain/openai";
21
+ *
22
+ * // Define the tools the agent will have access to.
23
+ * const tools = [...];
24
+ *
25
+ * // Get the prompt to use - you can modify this!
26
+ * // If you want to see the prompt in full, you can at:
27
+ * // https://smith.langchain.com/hub/hwchase17/openai-tools-agent
28
+ * const prompt = await pull<ChatPromptTemplate>(
29
+ * "hwchase17/openai-tools-agent"
30
+ * );
31
+ *
32
+ * const llm = new ChatOpenAI({
33
+ * temperature: 0,
34
+ * modelName: "gpt-3.5-turbo-1106",
35
+ * });
36
+ *
37
+ * const agent = await createOpenAIToolsAgent({
38
+ * llm,
39
+ * tools,
40
+ * prompt,
41
+ * });
42
+ *
43
+ * const agentExecutor = new AgentExecutor({
44
+ * agent,
45
+ * tools,
46
+ * });
47
+ *
48
+ * const result = await agentExecutor.invoke({
49
+ * input: "what is LangChain?",
50
+ * });
51
+ *
52
+ * // With chat history
53
+ * const result2 = await agentExecutor.invoke({
54
+ * input: "what's my name?",
55
+ * chat_history: [
56
+ * new HumanMessage("hi! my name is cob"),
57
+ * new AIMessage("Hello Cob! How can I assist you today?"),
58
+ * ],
59
+ * });
60
+ * ```
61
+ */
62
+ export async function createOpenAIToolsAgent({ llm, tools, prompt, }) {
63
+ if (!prompt.inputVariables.includes("agent_scratchpad")) {
64
+ throw new Error([
65
+ `Prompt must have an input variable named "agent_scratchpad".`,
66
+ `Found ${JSON.stringify(prompt.inputVariables)} instead.`,
67
+ ].join("\n"));
68
+ }
69
+ const modelWithTools = llm.bind({ tools: tools.map(formatToOpenAITool) });
70
+ const agent = RunnableSequence.from([
71
+ RunnablePassthrough.assign({
72
+ agent_scratchpad: (input) => formatToOpenAIToolMessages(input.steps),
73
+ }),
74
+ prompt,
75
+ modelWithTools,
76
+ new OpenAIToolsAgentOutputParser(),
77
+ ]);
78
+ return agent;
79
+ }
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpenAIToolsAgentOutputParser = 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
+ /**
8
+ * @example
9
+ * ```typescript
10
+ *
11
+ * const prompt = ChatPromptTemplate.fromMessages([
12
+ * ["ai", "You are a helpful assistant"],
13
+ * ["human", "{input}"],
14
+ * new MessagesPlaceholder("agent_scratchpad"),
15
+ * ]);
16
+ *
17
+ * const runnableAgent = RunnableSequence.from([
18
+ * {
19
+ * input: (i: { input: string; steps: ToolsAgentStep[] }) => i.input,
20
+ * agent_scratchpad: (i: { input: string; steps: ToolsAgentStep[] }) =>
21
+ * formatToOpenAIToolMessages(i.steps),
22
+ * },
23
+ * prompt,
24
+ * new ChatOpenAI({
25
+ * modelName: "gpt-3.5-turbo-1106",
26
+ * temperature: 0,
27
+ * }).bind({ tools: tools.map(formatToOpenAITool) }),
28
+ * new OpenAIToolsAgentOutputParser(),
29
+ * ]).withConfig({ runName: "OpenAIToolsAgent" });
30
+ *
31
+ * const result = await runnableAgent.invoke({
32
+ * input:
33
+ * "What is the sum of the current temperature in San Francisco, New York, and Tokyo?",
34
+ * });
35
+ *
36
+ * ```
37
+ */
38
+ class OpenAIToolsAgentOutputParser extends types_js_1.AgentMultiActionOutputParser {
39
+ constructor() {
40
+ super(...arguments);
41
+ Object.defineProperty(this, "lc_namespace", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: ["langchain", "agents", "openai"]
46
+ });
47
+ }
48
+ static lc_name() {
49
+ return "OpenAIToolsAgentOutputParser";
50
+ }
51
+ async parse(text) {
52
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
53
+ }
54
+ async parseResult(generations) {
55
+ if ("message" in generations[0] && (0, index_js_1.isBaseMessage)(generations[0].message)) {
56
+ return this.parseAIMessage(generations[0].message);
57
+ }
58
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
59
+ }
60
+ /**
61
+ * Parses the output message into a ToolsAgentAction[] or AgentFinish
62
+ * object.
63
+ * @param message The BaseMessage to parse.
64
+ * @returns A ToolsAgentAction[] or AgentFinish object.
65
+ */
66
+ parseAIMessage(message) {
67
+ if (message.content && typeof message.content !== "string") {
68
+ throw new Error("This agent cannot parse non-string model responses.");
69
+ }
70
+ if (message.additional_kwargs.tool_calls) {
71
+ const toolCalls = message.additional_kwargs.tool_calls;
72
+ try {
73
+ return toolCalls.map((toolCall, i) => {
74
+ const toolInput = toolCall.function.arguments
75
+ ? JSON.parse(toolCall.function.arguments)
76
+ : {};
77
+ const messageLog = i === 0 ? [message] : [];
78
+ return {
79
+ tool: toolCall.function.name,
80
+ toolInput,
81
+ toolCallId: toolCall.id,
82
+ log: `Invoking "${toolCall.function.name}" with ${toolCall.function.arguments ?? "{}"}\n${message.content}`,
83
+ messageLog,
84
+ };
85
+ });
86
+ }
87
+ catch (error) {
88
+ throw new output_parser_js_1.OutputParserException(`Failed to parse tool arguments from chat model response. Text: "${JSON.stringify(toolCalls)}". ${error}`);
89
+ }
90
+ }
91
+ else {
92
+ return {
93
+ returnValues: { output: message.content },
94
+ log: message.content,
95
+ };
96
+ }
97
+ }
98
+ getFormatInstructions() {
99
+ throw new Error("getFormatInstructions not implemented inside OpenAIToolsAgentOutputParser.");
100
+ }
101
+ }
102
+ exports.OpenAIToolsAgentOutputParser = OpenAIToolsAgentOutputParser;
@@ -0,0 +1,57 @@
1
+ import { AgentAction, AgentFinish, AgentStep, BaseMessage, ChatGeneration } from "../../schema/index.js";
2
+ import { AgentMultiActionOutputParser } from "../types.js";
3
+ /**
4
+ * Type that represents an agent action with an optional message log.
5
+ */
6
+ export type ToolsAgentAction = AgentAction & {
7
+ toolCallId: string;
8
+ messageLog?: BaseMessage[];
9
+ };
10
+ export type ToolsAgentStep = AgentStep & {
11
+ action: ToolsAgentAction;
12
+ };
13
+ /**
14
+ * @example
15
+ * ```typescript
16
+ *
17
+ * const prompt = ChatPromptTemplate.fromMessages([
18
+ * ["ai", "You are a helpful assistant"],
19
+ * ["human", "{input}"],
20
+ * new MessagesPlaceholder("agent_scratchpad"),
21
+ * ]);
22
+ *
23
+ * const runnableAgent = RunnableSequence.from([
24
+ * {
25
+ * input: (i: { input: string; steps: ToolsAgentStep[] }) => i.input,
26
+ * agent_scratchpad: (i: { input: string; steps: ToolsAgentStep[] }) =>
27
+ * formatToOpenAIToolMessages(i.steps),
28
+ * },
29
+ * prompt,
30
+ * new ChatOpenAI({
31
+ * modelName: "gpt-3.5-turbo-1106",
32
+ * temperature: 0,
33
+ * }).bind({ tools: tools.map(formatToOpenAITool) }),
34
+ * new OpenAIToolsAgentOutputParser(),
35
+ * ]).withConfig({ runName: "OpenAIToolsAgent" });
36
+ *
37
+ * const result = await runnableAgent.invoke({
38
+ * input:
39
+ * "What is the sum of the current temperature in San Francisco, New York, and Tokyo?",
40
+ * });
41
+ *
42
+ * ```
43
+ */
44
+ export declare class OpenAIToolsAgentOutputParser extends AgentMultiActionOutputParser {
45
+ lc_namespace: string[];
46
+ static lc_name(): string;
47
+ parse(text: string): Promise<AgentAction[] | AgentFinish>;
48
+ parseResult(generations: ChatGeneration[]): Promise<AgentFinish | ToolsAgentAction[]>;
49
+ /**
50
+ * Parses the output message into a ToolsAgentAction[] or AgentFinish
51
+ * object.
52
+ * @param message The BaseMessage to parse.
53
+ * @returns A ToolsAgentAction[] or AgentFinish object.
54
+ */
55
+ parseAIMessage(message: BaseMessage): ToolsAgentAction[] | AgentFinish;
56
+ getFormatInstructions(): string;
57
+ }