@langchain/classic 1.0.6-dev-1765433794876 → 1.0.7-dev-1765937705265
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/agents/chat/outputParser.d.cts +2 -2
- package/dist/agents/chat/outputParser.d.cts.map +1 -1
- package/dist/agents/chat/outputParser.d.ts +2 -2
- package/dist/agents/chat/outputParser.d.ts.map +1 -1
- package/dist/agents/mrkl/outputParser.d.cts +1 -1
- package/dist/agents/mrkl/outputParser.d.cts.map +1 -1
- package/dist/agents/mrkl/outputParser.d.ts +1 -1
- package/dist/agents/mrkl/outputParser.d.ts.map +1 -1
- package/dist/agents/react/index.d.cts +2 -2
- package/dist/agents/react/index.d.cts.map +1 -1
- package/dist/agents/react/index.d.ts +2 -2
- package/dist/agents/react/index.d.ts.map +1 -1
- package/dist/agents/structured_chat/index.d.ts +2 -2
- package/dist/agents/structured_chat/index.d.ts.map +1 -1
- package/dist/agents/tool_calling/index.d.cts +2 -2
- package/dist/agents/tool_calling/index.d.cts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.cts +1 -1
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.cts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts +2 -2
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.d.cts +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.d.cts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.d.ts +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.d.ts.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs +13 -0
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.js +13 -0
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/evaluation/agents/trajectory.d.cts +2 -2
- package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
- package/dist/evaluation/agents/trajectory.d.ts +2 -2
- package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts +3 -3
- package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.ts +3 -3
- package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts +3 -3
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.ts +3 -3
- package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
- package/dist/experimental/autogpt/prompt.d.cts +2 -2
- package/dist/experimental/autogpt/prompt.d.cts.map +1 -1
- package/dist/experimental/autogpt/prompt.d.ts +2 -2
- package/dist/experimental/autogpt/prompt.d.ts.map +1 -1
- package/dist/tools/retriever.d.cts +1 -1
- package/dist/tools/retriever.d.cts.map +1 -1
- package/dist/tools/retriever.d.ts +1 -1
- package/dist/tools/retriever.d.ts.map +1 -1
- package/package.json +19 -19
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @langchain/classic
|
|
2
2
|
|
|
3
|
+
## 1.0.6
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#9596](https://github.com/langchain-ai/langchainjs/pull/9596) [`316392e`](https://github.com/langchain-ai/langchainjs/commit/316392ea5666008873ab88971f599469ea7a2765) Thanks [@christian-bromann](https://github.com/christian-bromann)! - fix(@langchain/classic): add langsmith as external dependency
|
|
8
|
+
|
|
9
|
+
- [#9606](https://github.com/langchain-ai/langchainjs/pull/9606) [`41b26a4`](https://github.com/langchain-ai/langchainjs/commit/41b26a499625f5f6cd817433832a8d2c2639d2fb) Thanks [@patrykkopycinski](https://github.com/patrykkopycinski)! - bin p-retry
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`5a01b5b`](https://github.com/langchain-ai/langchainjs/commit/5a01b5b705f6933958f61318b22f00b5f4763be8), [`eab88a5`](https://github.com/langchain-ai/langchainjs/commit/eab88a5ab7610f5b63212f753ebcbeee2f393622), [`5f79bc5`](https://github.com/langchain-ai/langchainjs/commit/5f79bc50aebc093c90b6716c0aebf5c4813d0171), [`7b301c0`](https://github.com/langchain-ai/langchainjs/commit/7b301c00ac851c286a13c2a908757cb40180c768), [`bb2f422`](https://github.com/langchain-ai/langchainjs/commit/bb2f422cd8e0d709d82baca44565980abb57120f), [`2a5ba50`](https://github.com/langchain-ai/langchainjs/commit/2a5ba50d240e7d6181546facf088142fbb7b4977), [`47edf3f`](https://github.com/langchain-ai/langchainjs/commit/47edf3fc673eb0627ec585a3a5c2b9381e234527), [`2e563e3`](https://github.com/langchain-ai/langchainjs/commit/2e563e332772aa0468f610c334cbedd7f3513ce8), [`72795fe`](https://github.com/langchain-ai/langchainjs/commit/72795fe76b515d9edc7d78fb28db59df844ce0c3), [`f97b488`](https://github.com/langchain-ai/langchainjs/commit/f97b488200b34c485b15a743277984ecacc62160), [`29a8480`](https://github.com/langchain-ai/langchainjs/commit/29a8480799d4c3534892a29cef4a135c437deb9b), [`3ecc1e7`](https://github.com/langchain-ai/langchainjs/commit/3ecc1e716704a032e941e670d1d9fbf5370d57aa), [`6baa851`](https://github.com/langchain-ai/langchainjs/commit/6baa851176b5dde5da19891df114a4645dfe7481), [`a552cad`](https://github.com/langchain-ai/langchainjs/commit/a552cad1a463239a0d1d1b5da7798978722738cf), [`69a1045`](https://github.com/langchain-ai/langchainjs/commit/69a1045e1e14aed9273a1a4085ac35e601a1ecc7)]:
|
|
12
|
+
- @langchain/openai@1.2.0
|
|
13
|
+
- @langchain/textsplitters@1.0.1
|
|
14
|
+
|
|
3
15
|
## 1.0.5
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
|
@@ -51,12 +51,12 @@ declare class ChatAgentOutputParser extends AgentActionOutputParser {
|
|
|
51
51
|
* @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.
|
|
52
52
|
*/
|
|
53
53
|
parse(text: string): Promise<{
|
|
54
|
+
tool?: undefined;
|
|
55
|
+
toolInput?: undefined;
|
|
54
56
|
returnValues: {
|
|
55
57
|
output: string;
|
|
56
58
|
};
|
|
57
59
|
log: string;
|
|
58
|
-
tool?: undefined;
|
|
59
|
-
toolInput?: undefined;
|
|
60
60
|
} | {
|
|
61
61
|
returnValues?: undefined;
|
|
62
62
|
tool: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.d.cts","names":["AgentActionOutputParser","FINAL_ANSWER_ACTION","ChatAgentOutputParser","Promise"],"sources":["../../../src/agents/chat/outputParser.d.ts"],"sourcesContent":["import { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends the AgentActionOutputParser to parse the output of\n * the ChatAgent in LangChain. It checks if the output text contains the\n * final answer action or a JSON response, and parses it accordingly.\n * @example\n * ```typescript\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\n * \"ai\",\n * `{PREFIX}\n * {FORMAT_INSTRUCTIONS}\n * {SUFFIX}`,\n * ],\n * [\"human\", \"Question: {input}\"],\n * ]);\n * const runnableAgent = RunnableSequence.from([\n * {\n * input: (i: { input: string; steps: AgentStep[] }) => i.input,\n * agent_scratchpad: (i: { input: string; steps: AgentStep[] }) =>\n * formatLogToString(i.steps),\n * },\n * prompt,\n * new OpenAI({ temperature: 0 }),\n * new ChatAgentOutputParser(),\n * ]);\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n *\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport declare class ChatAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n /**\n * Parses the output text from the MRKL chain into an agent action or\n * agent finish. If the text contains the final answer action or does not\n * contain an action, it returns an AgentFinish with the output and log.\n * If the text contains a JSON response, it returns the tool, toolInput,\n * and log.\n * @param text The output text from the MRKL chain.\n * @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n
|
|
1
|
+
{"version":3,"file":"outputParser.d.cts","names":["AgentActionOutputParser","FINAL_ANSWER_ACTION","ChatAgentOutputParser","Promise"],"sources":["../../../src/agents/chat/outputParser.d.ts"],"sourcesContent":["import { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends the AgentActionOutputParser to parse the output of\n * the ChatAgent in LangChain. It checks if the output text contains the\n * final answer action or a JSON response, and parses it accordingly.\n * @example\n * ```typescript\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\n * \"ai\",\n * `{PREFIX}\n * {FORMAT_INSTRUCTIONS}\n * {SUFFIX}`,\n * ],\n * [\"human\", \"Question: {input}\"],\n * ]);\n * const runnableAgent = RunnableSequence.from([\n * {\n * input: (i: { input: string; steps: AgentStep[] }) => i.input,\n * agent_scratchpad: (i: { input: string; steps: AgentStep[] }) =>\n * formatLogToString(i.steps),\n * },\n * prompt,\n * new OpenAI({ temperature: 0 }),\n * new ChatAgentOutputParser(),\n * ]);\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n *\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport declare class ChatAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n /**\n * Parses the output text from the MRKL chain into an agent action or\n * agent finish. If the text contains the final answer action or does not\n * contain an action, it returns an AgentFinish with the output and log.\n * If the text contains a JSON response, it returns the tool, toolInput,\n * and log.\n * @param text The output text from the MRKL chain.\n * @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.\n */\n parse(text: string): Promise<{\n tool?: undefined;\n toolInput?: undefined;\n returnValues: {\n output: string;\n };\n log: string;\n } | {\n returnValues?: undefined;\n tool: any;\n toolInput: any;\n log: string;\n }>;\n /**\n * Returns the format instructions used in the output parser for the\n * ChatAgent class.\n * @returns The format instructions as a string.\n */\n getFormatInstructions(): string;\n}\n//# sourceMappingURL=outputParser.d.ts.map"],"mappings":";;;;;AAuCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAqBE,qBAAAA,SAA8BF,uBAAuB;;;;;;;;;;;uBAWjDG"}
|
|
@@ -51,12 +51,12 @@ declare class ChatAgentOutputParser extends AgentActionOutputParser {
|
|
|
51
51
|
* @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.
|
|
52
52
|
*/
|
|
53
53
|
parse(text: string): Promise<{
|
|
54
|
-
tool?: undefined;
|
|
55
|
-
toolInput?: undefined;
|
|
56
54
|
returnValues: {
|
|
57
55
|
output: string;
|
|
58
56
|
};
|
|
59
57
|
log: string;
|
|
58
|
+
tool?: undefined;
|
|
59
|
+
toolInput?: undefined;
|
|
60
60
|
} | {
|
|
61
61
|
returnValues?: undefined;
|
|
62
62
|
tool: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.d.ts","names":["AgentActionOutputParser","FINAL_ANSWER_ACTION","ChatAgentOutputParser","Promise"],"sources":["../../../src/agents/chat/outputParser.d.ts"],"sourcesContent":["import { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends the AgentActionOutputParser to parse the output of\n * the ChatAgent in LangChain. It checks if the output text contains the\n * final answer action or a JSON response, and parses it accordingly.\n * @example\n * ```typescript\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\n * \"ai\",\n * `{PREFIX}\n * {FORMAT_INSTRUCTIONS}\n * {SUFFIX}`,\n * ],\n * [\"human\", \"Question: {input}\"],\n * ]);\n * const runnableAgent = RunnableSequence.from([\n * {\n * input: (i: { input: string; steps: AgentStep[] }) => i.input,\n * agent_scratchpad: (i: { input: string; steps: AgentStep[] }) =>\n * formatLogToString(i.steps),\n * },\n * prompt,\n * new OpenAI({ temperature: 0 }),\n * new ChatAgentOutputParser(),\n * ]);\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n *\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport declare class ChatAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n /**\n * Parses the output text from the MRKL chain into an agent action or\n * agent finish. If the text contains the final answer action or does not\n * contain an action, it returns an AgentFinish with the output and log.\n * If the text contains a JSON response, it returns the tool, toolInput,\n * and log.\n * @param text The output text from the MRKL chain.\n * @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.\n */\n parse(text: string): Promise<{\n
|
|
1
|
+
{"version":3,"file":"outputParser.d.ts","names":["AgentActionOutputParser","FINAL_ANSWER_ACTION","ChatAgentOutputParser","Promise"],"sources":["../../../src/agents/chat/outputParser.d.ts"],"sourcesContent":["import { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends the AgentActionOutputParser to parse the output of\n * the ChatAgent in LangChain. It checks if the output text contains the\n * final answer action or a JSON response, and parses it accordingly.\n * @example\n * ```typescript\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\n * \"ai\",\n * `{PREFIX}\n * {FORMAT_INSTRUCTIONS}\n * {SUFFIX}`,\n * ],\n * [\"human\", \"Question: {input}\"],\n * ]);\n * const runnableAgent = RunnableSequence.from([\n * {\n * input: (i: { input: string; steps: AgentStep[] }) => i.input,\n * agent_scratchpad: (i: { input: string; steps: AgentStep[] }) =>\n * formatLogToString(i.steps),\n * },\n * prompt,\n * new OpenAI({ temperature: 0 }),\n * new ChatAgentOutputParser(),\n * ]);\n *\n * const executor = AgentExecutor.fromAgentAndTools({\n * agent: runnableAgent,\n * tools: [new SerpAPI(), new Calculator()],\n * });\n *\n * const result = await executor.invoke({\n * input:\n * \"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\",\n * });\n * ```\n */\nexport declare class ChatAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n /**\n * Parses the output text from the MRKL chain into an agent action or\n * agent finish. If the text contains the final answer action or does not\n * contain an action, it returns an AgentFinish with the output and log.\n * If the text contains a JSON response, it returns the tool, toolInput,\n * and log.\n * @param text The output text from the MRKL chain.\n * @returns An object that satisfies the AgentFinish interface or an object with the tool, toolInput, and log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n tool?: undefined;\n toolInput?: undefined;\n } | {\n returnValues?: undefined;\n tool: any;\n toolInput: any;\n log: string;\n }>;\n /**\n * Returns the format instructions used in the output parser for the\n * ChatAgent class.\n * @returns The format instructions as a string.\n */\n getFormatInstructions(): string;\n}\n//# sourceMappingURL=outputParser.d.ts.map"],"mappings":";;;;;AAuCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAqBE,qBAAAA,SAA8BF,uBAAuB;;;;;;;;;;;uBAWjDG"}
|
|
@@ -25,10 +25,10 @@ declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {
|
|
|
25
25
|
tool?: undefined;
|
|
26
26
|
toolInput?: undefined;
|
|
27
27
|
} | {
|
|
28
|
+
returnValues?: undefined;
|
|
28
29
|
tool: string;
|
|
29
30
|
toolInput: string;
|
|
30
31
|
log: string;
|
|
31
|
-
returnValues?: undefined;
|
|
32
32
|
}>;
|
|
33
33
|
/**
|
|
34
34
|
* Returns the format instructions for parsing the output of an agent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.d.cts","names":["OutputParserArgs","AgentActionOutputParser","FINAL_ANSWER_ACTION","ZeroShotAgentOutputParser","Promise"],"sources":["../../../src/agents/mrkl/outputParser.d.ts"],"sourcesContent":["import { OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends `AgentActionOutputParser` to provide a custom\n * implementation for parsing the output of a ZeroShotAgent action.\n */\nexport declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n finishToolName: string;\n constructor(fields?: OutputParserArgs);\n /**\n * Parses the text output of an agent action, extracting the tool, tool\n * input, and output.\n * @param text The text output of an agent action.\n * @returns An object containing the tool, tool input, and output extracted from the text, along with the original text as a log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n tool?: undefined;\n toolInput?: undefined;\n } | {\n tool: string;\n toolInput: string;\n log: string;\n
|
|
1
|
+
{"version":3,"file":"outputParser.d.cts","names":["OutputParserArgs","AgentActionOutputParser","FINAL_ANSWER_ACTION","ZeroShotAgentOutputParser","Promise"],"sources":["../../../src/agents/mrkl/outputParser.d.ts"],"sourcesContent":["import { OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends `AgentActionOutputParser` to provide a custom\n * implementation for parsing the output of a ZeroShotAgent action.\n */\nexport declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n finishToolName: string;\n constructor(fields?: OutputParserArgs);\n /**\n * Parses the text output of an agent action, extracting the tool, tool\n * input, and output.\n * @param text The text output of an agent action.\n * @returns An object containing the tool, tool input, and output extracted from the text, along with the original text as a log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n tool?: undefined;\n toolInput?: undefined;\n } | {\n returnValues?: undefined;\n tool: string;\n toolInput: string;\n log: string;\n }>;\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the ZeroShotAgent.\n * @returns The format instructions for parsing the output.\n */\n getFormatInstructions(): string;\n}\n//# sourceMappingURL=outputParser.d.ts.map"],"mappings":";;;;;;AAOA;;;AAAuDC,cAAlCE,yBAAAA,SAAkCF,uBAAAA,CAAAA;EAAuB,YAAA,EAAA,MAAA,EAAA;;uBAGrDD;;;;;;;uBAOAI"}
|
|
@@ -25,10 +25,10 @@ declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {
|
|
|
25
25
|
tool?: undefined;
|
|
26
26
|
toolInput?: undefined;
|
|
27
27
|
} | {
|
|
28
|
-
returnValues?: undefined;
|
|
29
28
|
tool: string;
|
|
30
29
|
toolInput: string;
|
|
31
30
|
log: string;
|
|
31
|
+
returnValues?: undefined;
|
|
32
32
|
}>;
|
|
33
33
|
/**
|
|
34
34
|
* Returns the format instructions for parsing the output of an agent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outputParser.d.ts","names":["OutputParserArgs","AgentActionOutputParser","FINAL_ANSWER_ACTION","ZeroShotAgentOutputParser","Promise"],"sources":["../../../src/agents/mrkl/outputParser.d.ts"],"sourcesContent":["import { OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends `AgentActionOutputParser` to provide a custom\n * implementation for parsing the output of a ZeroShotAgent action.\n */\nexport declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n finishToolName: string;\n constructor(fields?: OutputParserArgs);\n /**\n * Parses the text output of an agent action, extracting the tool, tool\n * input, and output.\n * @param text The text output of an agent action.\n * @returns An object containing the tool, tool input, and output extracted from the text, along with the original text as a log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n tool?: undefined;\n toolInput?: undefined;\n } | {\n
|
|
1
|
+
{"version":3,"file":"outputParser.d.ts","names":["OutputParserArgs","AgentActionOutputParser","FINAL_ANSWER_ACTION","ZeroShotAgentOutputParser","Promise"],"sources":["../../../src/agents/mrkl/outputParser.d.ts"],"sourcesContent":["import { OutputParserArgs } from \"../agent.js\";\nimport { AgentActionOutputParser } from \"../types.js\";\nexport declare const FINAL_ANSWER_ACTION = \"Final Answer:\";\n/**\n * A class that extends `AgentActionOutputParser` to provide a custom\n * implementation for parsing the output of a ZeroShotAgent action.\n */\nexport declare class ZeroShotAgentOutputParser extends AgentActionOutputParser {\n lc_namespace: string[];\n finishToolName: string;\n constructor(fields?: OutputParserArgs);\n /**\n * Parses the text output of an agent action, extracting the tool, tool\n * input, and output.\n * @param text The text output of an agent action.\n * @returns An object containing the tool, tool input, and output extracted from the text, along with the original text as a log.\n */\n parse(text: string): Promise<{\n returnValues: {\n output: string;\n };\n log: string;\n tool?: undefined;\n toolInput?: undefined;\n } | {\n tool: string;\n toolInput: string;\n log: string;\n returnValues?: undefined;\n }>;\n /**\n * Returns the format instructions for parsing the output of an agent\n * action in the style of the ZeroShotAgent.\n * @returns The format instructions for parsing the output.\n */\n getFormatInstructions(): string;\n}\n//# sourceMappingURL=outputParser.d.ts.map"],"mappings":";;;;;;AAOA;;;AAAuDC,cAAlCE,yBAAAA,SAAkCF,uBAAAA,CAAAA;EAAuB,YAAA,EAAA,MAAA,EAAA;;uBAGrDD;;;;;;;uBAOAI"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentRunnableSequence } from "../agent.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as _langchain_core_agents5 from "@langchain/core/agents";
|
|
3
3
|
import { AgentStep } from "@langchain/core/agents";
|
|
4
4
|
import { BasePromptTemplate } from "@langchain/core/prompts";
|
|
5
5
|
import { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
|
|
@@ -75,7 +75,7 @@ declare function createReactAgent({
|
|
|
75
75
|
streamRunnable
|
|
76
76
|
}: CreateReactAgentParams): Promise<AgentRunnableSequence<{
|
|
77
77
|
steps: AgentStep[];
|
|
78
|
-
},
|
|
78
|
+
}, _langchain_core_agents5.AgentAction | _langchain_core_agents5.AgentFinish>>;
|
|
79
79
|
//#endregion
|
|
80
80
|
export { CreateReactAgentParams, createReactAgent };
|
|
81
81
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["ToolInterface","BasePromptTemplate","BaseLanguageModelInterface","AgentStep","AgentRunnableSequence","CreateReactAgentParams","createReactAgent","llm","tools","prompt","streamRunnable","
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["ToolInterface","BasePromptTemplate","BaseLanguageModelInterface","AgentStep","AgentRunnableSequence","CreateReactAgentParams","createReactAgent","llm","tools","prompt","streamRunnable","_langchain_core_agents5","AgentAction","AgentFinish","Promise"],"sources":["../../../src/agents/react/index.d.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport declare function createReactAgent({ llm, tools, prompt, streamRunnable }: CreateReactAgentParams): Promise<AgentRunnableSequence<{\n steps: AgentStep[];\n}, import(\"@langchain/core/agents\").AgentAction | import(\"@langchain/core/agents\").AgentFinish>>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;AAQYK,KAAAA,sBAAAA,GAAsB;EAEzBH;EAEEF,GAAAA,EAFFE,0BAEEF;EAKCC;EAAkB,KAAA,EALnBD,aAKmB,EAAA;EAkDNM;;;;EAAuCI,MAAAA,EAlDnDT,kBAkDmDS;EAAkBL;;;;EAAiCD,cAAAA,CAAAA,EAAAA,OAAAA;CAARU;AAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAzFR,gBAAAA;;;;;GAAyDD,yBAAyBS,QAAQV;SACvGD;GAASQ,uBAAAA,CACgBC,WAAAA,GAAWD,uBAAAA,CAAoCE"}
|
|
@@ -2,7 +2,7 @@ import { AgentRunnableSequence } from "../agent.js";
|
|
|
2
2
|
import { BasePromptTemplate } from "@langchain/core/prompts";
|
|
3
3
|
import { ToolInterface } from "@langchain/core/tools";
|
|
4
4
|
import { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
|
|
5
|
-
import * as
|
|
5
|
+
import * as _langchain_core_agents1 from "@langchain/core/agents";
|
|
6
6
|
import { AgentStep } from "@langchain/core/agents";
|
|
7
7
|
|
|
8
8
|
//#region src/agents/react/index.d.ts
|
|
@@ -75,7 +75,7 @@ declare function createReactAgent({
|
|
|
75
75
|
streamRunnable
|
|
76
76
|
}: CreateReactAgentParams): Promise<AgentRunnableSequence<{
|
|
77
77
|
steps: AgentStep[];
|
|
78
|
-
},
|
|
78
|
+
}, _langchain_core_agents1.AgentAction | _langchain_core_agents1.AgentFinish>>;
|
|
79
79
|
//#endregion
|
|
80
80
|
export { CreateReactAgentParams, createReactAgent };
|
|
81
81
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["ToolInterface","BasePromptTemplate","BaseLanguageModelInterface","AgentStep","AgentRunnableSequence","CreateReactAgentParams","createReactAgent","llm","tools","prompt","streamRunnable","
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["ToolInterface","BasePromptTemplate","BaseLanguageModelInterface","AgentStep","AgentRunnableSequence","CreateReactAgentParams","createReactAgent","llm","tools","prompt","streamRunnable","_langchain_core_agents1","AgentAction","AgentFinish","Promise"],"sources":["../../../src/agents/react/index.d.ts"],"sourcesContent":["import type { ToolInterface } from \"@langchain/core/tools\";\nimport { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { AgentRunnableSequence } from \"../agent.js\";\n/**\n * Params used by the createXmlAgent function.\n */\nexport type CreateReactAgentParams = {\n /** LLM to use for the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: ToolInterface[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n/**\n * Create an agent that uses ReAct prompting.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createReactAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { PromptTemplate } from \"@langchain/core/prompts\";\n *\n * import { OpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/react\n * const prompt = await pull<PromptTemplate>(\"hwchase17/react\");\n *\n * const llm = new OpenAI({\n * temperature: 0,\n * });\n *\n * const agent = await createReactAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n * ```\n */\nexport declare function createReactAgent({ llm, tools, prompt, streamRunnable }: CreateReactAgentParams): Promise<AgentRunnableSequence<{\n steps: AgentStep[];\n}, import(\"@langchain/core/agents\").AgentAction | import(\"@langchain/core/agents\").AgentFinish>>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;AAQYK,KAAAA,sBAAAA,GAAsB;EAEzBH;EAEEF,GAAAA,EAFFE,0BAEEF;EAKCC;EAAkB,KAAA,EALnBD,aAKmB,EAAA;EAkDNM;;;;EAAuCI,MAAAA,EAlDnDT,kBAkDmDS;EAAkBL;;;;EAAiCD,cAAAA,CAAAA,EAAAA,OAAAA;CAARU;AAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAzFR,gBAAAA;;;;;GAAyDD,yBAAyBS,QAAQV;SACvGD;GAASQ,uBAAAA,CACgBC,WAAAA,GAAWD,uBAAAA,CAAoCE"}
|
|
@@ -5,7 +5,7 @@ import { StructuredChatOutputParserWithRetries } from "./outputParser.js";
|
|
|
5
5
|
import { BaseMessagePromptTemplate, BasePromptTemplate, ChatPromptTemplate } from "@langchain/core/prompts";
|
|
6
6
|
import { StructuredToolInterface } from "@langchain/core/tools";
|
|
7
7
|
import { BaseLanguageModelInterface, ToolDefinition } from "@langchain/core/language_models/base";
|
|
8
|
-
import * as
|
|
8
|
+
import * as _langchain_core_agents0 from "@langchain/core/agents";
|
|
9
9
|
import { AgentStep } from "@langchain/core/agents";
|
|
10
10
|
|
|
11
11
|
//#region src/agents/structured_chat/index.d.ts
|
|
@@ -176,7 +176,7 @@ declare function createStructuredChatAgent({
|
|
|
176
176
|
streamRunnable
|
|
177
177
|
}: CreateStructuredChatAgentParams): Promise<AgentRunnableSequence<{
|
|
178
178
|
steps: AgentStep[];
|
|
179
|
-
},
|
|
179
|
+
}, _langchain_core_agents0.AgentAction | _langchain_core_agents0.AgentFinish>>;
|
|
180
180
|
//#endregion
|
|
181
181
|
export { CreateStructuredChatAgentParams, StructuredChatAgent, StructuredChatAgentInput, StructuredChatCreatePromptArgs, createStructuredChatAgent };
|
|
182
182
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["StructuredToolInterface","BaseLanguageModelInterface","ToolDefinition","BasePromptTemplate","BaseMessagePromptTemplate","ChatPromptTemplate","AgentStep","Optional","Agent","AgentArgs","AgentRunnableSequence","OutputParserArgs","AgentInput","StructuredChatOutputParserWithRetries","StructuredChatCreatePromptArgs","StructuredChatAgentInput","StructuredChatAgent","Promise","CreateStructuredChatAgentParams","createStructuredChatAgent","llm","tools","prompt","streamRunnable","
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["StructuredToolInterface","BaseLanguageModelInterface","ToolDefinition","BasePromptTemplate","BaseMessagePromptTemplate","ChatPromptTemplate","AgentStep","Optional","Agent","AgentArgs","AgentRunnableSequence","OutputParserArgs","AgentInput","StructuredChatOutputParserWithRetries","StructuredChatCreatePromptArgs","StructuredChatAgentInput","StructuredChatAgent","Promise","CreateStructuredChatAgentParams","createStructuredChatAgent","llm","tools","prompt","streamRunnable","_langchain_core_agents0","AgentAction","AgentFinish"],"sources":["../../../src/agents/structured_chat/index.d.ts"],"sourcesContent":["import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { type BaseLanguageModelInterface, type ToolDefinition } from \"@langchain/core/language_models/base\";\nimport type { BasePromptTemplate } from \"@langchain/core/prompts\";\nimport { BaseMessagePromptTemplate, ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { AgentStep } from \"@langchain/core/agents\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { Agent, AgentArgs, AgentRunnableSequence, OutputParserArgs } from \"../agent.js\";\nimport { AgentInput } from \"../types.js\";\nimport { StructuredChatOutputParserWithRetries } from \"./outputParser.js\";\n/**\n * Interface for arguments used to create a prompt for a\n * StructuredChatAgent.\n */\nexport interface StructuredChatCreatePromptArgs {\n /** String to put after the list of tools. */\n suffix?: string;\n /** String to put before the list of tools. */\n prefix?: string;\n /** String to use directly as the human message template. */\n humanMessageTemplate?: string;\n /** List of input variables the final prompt will expect. */\n inputVariables?: string[];\n /** List of historical prompts from memory. */\n memoryPrompts?: BaseMessagePromptTemplate[];\n}\n/**\n * Type for input data for creating a StructuredChatAgent, with the\n * 'outputParser' property made optional.\n */\nexport type StructuredChatAgentInput = Optional<AgentInput, \"outputParser\">;\n/**\n * Agent that interoperates with Structured Tools using React logic.\n * @augments Agent\n */\nexport declare class StructuredChatAgent extends Agent {\n static lc_name(): string;\n lc_namespace: string[];\n constructor(input: StructuredChatAgentInput);\n _agentType(): \"structured-chat-zero-shot-react-description\";\n observationPrefix(): string;\n llmPrefix(): string;\n _stop(): string[];\n /**\n * Validates that all provided tools have a description. Throws an error\n * if any tool lacks a description.\n * @param tools Array of StructuredTool instances to validate.\n */\n static validateTools(tools: StructuredToolInterface[]): void;\n /**\n * Returns a default output parser for the StructuredChatAgent. If an LLM\n * is provided, it creates an output parser with retry logic from the LLM.\n * @param fields Optional fields to customize the output parser. Can include an LLM and a list of tool names.\n * @returns An instance of StructuredChatOutputParserWithRetries.\n */\n static getDefaultOutputParser(fields?: OutputParserArgs & {\n toolNames: string[];\n }): StructuredChatOutputParserWithRetries;\n /**\n * Constructs the agent's scratchpad from a list of steps. If the agent's\n * scratchpad is not empty, it prepends a message indicating that the\n * agent has not seen any previous work.\n * @param steps Array of AgentStep instances to construct the scratchpad from.\n * @returns A Promise that resolves to a string representing the agent's scratchpad.\n */\n constructScratchPad(steps: AgentStep[]): Promise<string>;\n /**\n * Creates a string representation of the schemas of the provided tools.\n * @param tools Array of StructuredTool instances to create the schemas string from.\n * @returns A string representing the schemas of the provided tools.\n */\n static createToolSchemasString(tools: StructuredToolInterface[]): string;\n /**\n * Create prompt in the style of the agent.\n *\n * @param tools - List of tools the agent will have access to, used to format the prompt.\n * @param args - Arguments to create the prompt with.\n * @param args.suffix - String to put after the list of tools.\n * @param args.prefix - String to put before the list of tools.\n * @param args.inputVariables List of input variables the final prompt will expect.\n * @param args.memoryPrompts List of historical prompts from memory.\n */\n static createPrompt(tools: StructuredToolInterface[], args?: StructuredChatCreatePromptArgs): ChatPromptTemplate<any, any>;\n /**\n * Creates a StructuredChatAgent from an LLM and a list of tools.\n * Validates the tools, creates a prompt, and sets up an LLM chain for the\n * agent.\n * @param llm BaseLanguageModel instance to create the agent from.\n * @param tools Array of StructuredTool instances to create the agent from.\n * @param args Optional arguments to customize the creation of the agent. Can include arguments for creating the prompt and AgentArgs.\n * @returns A new instance of StructuredChatAgent.\n */\n static fromLLMAndTools(llm: BaseLanguageModelInterface, tools: StructuredToolInterface[], args?: StructuredChatCreatePromptArgs & AgentArgs): StructuredChatAgent;\n}\n/**\n * Params used by the createStructuredChatAgent function.\n */\nexport type CreateStructuredChatAgentParams = {\n /** LLM to use as the agent. */\n llm: BaseLanguageModelInterface;\n /** Tools this agent has access to. */\n tools: (StructuredToolInterface | ToolDefinition)[];\n /**\n * The prompt to use. Must have input keys for\n * `tools`, `tool_names`, and `agent_scratchpad`.\n */\n prompt: BasePromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n/**\n * Create an agent aimed at supporting tools with multiple inputs.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n *\n * @example\n * ```typescript\n * import { AgentExecutor, createStructuredChatAgent } from \"langchain/agents\";\n * import { pull } from \"langchain/hub\";\n * import type { ChatPromptTemplate } from \"@langchain/core/prompts\";\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * // Get the prompt to use - you can modify this!\n * // If you want to see the prompt in full, you can at:\n * // https://smith.langchain.com/hub/hwchase17/structured-chat-agent\n * const prompt = await pull<ChatPromptTemplate>(\n * \"hwchase17/structured-chat-agent\"\n * );\n *\n * const llm = new ChatOpenAI({\n * temperature: 0,\n * model: \"gpt-3.5-turbo-1106\",\n * });\n *\n * const agent = await createStructuredChatAgent({\n * llm,\n * tools,\n * prompt,\n * });\n *\n * const agentExecutor = new AgentExecutor({\n * agent,\n * tools,\n * });\n *\n * const result = await agentExecutor.invoke({\n * input: \"what is LangChain?\",\n * });\n *\n * // With chat history\n * const result2 = await agentExecutor.invoke({\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage(\"hi! my name is cob\"),\n * new AIMessage(\"Hello Cob! How can I assist you today?\"),\n * ],\n * });\n * ```\n */\nexport declare function createStructuredChatAgent({ llm, tools, prompt, streamRunnable }: CreateStructuredChatAgentParams): Promise<AgentRunnableSequence<{\n steps: AgentStep[];\n}, import(\"@langchain/core/agents\").AgentAction | import(\"@langchain/core/agents\").AgentFinish>>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;;;;AAaA;AAgBA;AAKqBgB,UAr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AAWD,uBAAAA,CAAoCE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ToolsAgentStep } from "./output_parser.cjs";
|
|
2
2
|
import { AgentRunnableSequence } from "../agent.cjs";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _langchain_core_agents1 from "@langchain/core/agents";
|
|
4
4
|
import { ChatPromptTemplate } from "@langchain/core/prompts";
|
|
5
5
|
import { LanguageModelLike, ToolDefinition } from "@langchain/core/language_models/base";
|
|
6
6
|
import { StructuredToolInterface } from "@langchain/core/tools";
|
|
@@ -83,7 +83,7 @@ declare function createToolCallingAgent({
|
|
|
83
83
|
streamRunnable
|
|
84
84
|
}: CreateToolCallingAgentParams): AgentRunnableSequence<{
|
|
85
85
|
steps: ToolsAgentStep[];
|
|
86
|
-
},
|
|
86
|
+
}, _langchain_core_agents1.AgentFinish | _langchain_core_agents1.AgentAction[]>;
|
|
87
87
|
//#endregion
|
|
88
88
|
export { CreateToolCallingAgentParams, createToolCallingAgent };
|
|
89
89
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["ChatPromptTemplate","StructuredToolInterface","LanguageModelLike","ToolDefinition","AgentRunnableSequence","ToolsAgentStep","CreateToolCallingAgentParams","createToolCallingAgent","llm","tools","prompt","streamRunnable","
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["ChatPromptTemplate","StructuredToolInterface","LanguageModelLike","ToolDefinition","AgentRunnableSequence","ToolsAgentStep","CreateToolCallingAgentParams","createToolCallingAgent","llm","tools","prompt","streamRunnable","_langchain_core_agents1","AgentFinish","AgentAction"],"sources":["../../../src/agents/tool_calling/index.d.ts"],"sourcesContent":["import { ChatPromptTemplate } from \"@langchain/core/prompts\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { LanguageModelLike, ToolDefinition } from \"@langchain/core/language_models/base\";\nimport { AgentRunnableSequence } from \"../agent.js\";\nimport { ToolsAgentStep } from \"./output_parser.js\";\n/**\n * Params used by the createOpenAIToolsAgent function.\n */\nexport type CreateToolCallingAgentParams = {\n /**\n * LLM to use as the agent. Should work with OpenAI tool calling,\n * so must either be an OpenAI model that supports that or a wrapper of\n * a different model that adds in equivalent support.\n */\n llm: LanguageModelLike;\n /** Tools this agent has access to. */\n tools: StructuredToolInterface[] | ToolDefinition[];\n /** The prompt to use, must have an input key of `agent_scratchpad`. */\n prompt: ChatPromptTemplate;\n /**\n * Whether to invoke the underlying model in streaming mode,\n * allowing streaming of intermediate steps. Defaults to true.\n */\n streamRunnable?: boolean;\n};\n/**\n * Create an agent that uses tools.\n * @param params Params required to create the agent. Includes an LLM, tools, and prompt.\n * @returns A runnable sequence representing an agent. It takes as input all the same input\n * variables as the prompt passed in does. It returns as output either an\n * AgentAction or AgentFinish.\n * @example\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n * import { AgentExecutor, createToolCallingAgent } from \"langchain/agents\";\n *\n * const prompt = ChatPromptTemplate.fromMessages(\n * [\n * [\"system\", \"You are a helpful assistant\"],\n * [\"placeholder\", \"{chat_history}\"],\n * [\"human\", \"{input}\"],\n * [\"placeholder\", \"{agent_scratchpad}\"],\n * ]\n * );\n *\n *\n * const llm = new ChatAnthropic({\n * modelName: \"claude-3-opus-20240229\",\n * temperature: 0,\n * });\n *\n * // Define the tools the agent will have access to.\n * const tools = [...];\n *\n * const agent = createToolCallingAgent({ llm, tools, prompt });\n *\n * const agentExecutor = new AgentExecutor({ agent, tools });\n *\n * const result = await agentExecutor.invoke({input: \"what is LangChain?\"});\n *\n * // Using with chat history\n * import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n *\n * const result2 = await agentExecutor.invoke(\n * {\n * input: \"what's my name?\",\n * chat_history: [\n * new HumanMessage({content: \"hi! my name is bob\"}),\n * new AIMessage({content: \"Hello Bob! How can I assist you today?\"}),\n * ],\n * }\n * );\n * ```\n */\nexport declare function createToolCallingAgent({ llm, tools, prompt, streamRunnable }: CreateToolCallingAgentParams): AgentRunnableSequence<{\n steps: ToolsAgentStep[];\n}, import(\"@langchain/core/agents\").AgentFinish | import(\"@langchain/core/agents\").AgentAction[]>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;AAQYM,KAAAA,4BAAAA,GAA4B;EAM/BJ;;;;AAIqB;EAyDNK,GAAAA,EA7DfL,iBA6DeK;EAAyBC;EAAKC,KAAAA,EA3D3CR,uBA2D2CQ,EAAAA,GA3DfN,cA2DeM,EAAAA;EAAOC;EAAQC,MAAAA,EAzDzDX,kBAyDyDW;EAAkBL;;;;EAA+BF,cAAAA,CAAAA,EAAAA,OAAAA;AAAqB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAnHG,sBAAAA;;;;;GAA+DD,+BAA+BF;SAC3GC;GAAcO,uBAAAA,CACWC,WAAAA,GAAWD,uBAAAA,CAAoCE,WAAAA"}
|
|
@@ -37,7 +37,7 @@ declare class OpenAIAgentTokenBufferMemory extends BaseChatMemory {
|
|
|
37
37
|
* Retrieves the messages from the chat history.
|
|
38
38
|
* @returns Promise that resolves with the messages from the chat history.
|
|
39
39
|
*/
|
|
40
|
-
getMessages(): Promise<_langchain_core_messages0.BaseMessage<_langchain_core_messages0.MessageStructure
|
|
40
|
+
getMessages(): Promise<_langchain_core_messages0.BaseMessage<_langchain_core_messages0.MessageStructure<_langchain_core_messages0.MessageToolSet>, _langchain_core_messages0.MessageType>[]>;
|
|
41
41
|
/**
|
|
42
42
|
* Loads memory variables from the input values.
|
|
43
43
|
* @param _values Input values.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token_buffer_memory.d.cts","names":["ChatOpenAI","InputValues","MemoryVariables","OutputValues","BaseChatMemory","BaseChatMemoryInput","OpenAIAgentTokenBufferMemoryFields","OpenAIAgentTokenBufferMemory","_langchain_core_messages0","MessageStructure","MessageType","BaseMessage","Promise"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts"],"sourcesContent":["import { ChatOpenAI } from \"@langchain/openai\";\nimport { InputValues, MemoryVariables, OutputValues } from \"@langchain/core/memory\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"../../../memory/chat_memory.js\";\n/**\n * Type definition for the fields required to initialize an instance of\n * OpenAIAgentTokenBufferMemory.\n */\nexport type OpenAIAgentTokenBufferMemoryFields = BaseChatMemoryInput & {\n llm: ChatOpenAI;\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n maxTokenLimit?: number;\n returnMessages?: boolean;\n outputKey?: string;\n intermediateStepsKey?: string;\n};\n/**\n * Memory used to save agent output and intermediate steps.\n */\nexport declare class OpenAIAgentTokenBufferMemory extends BaseChatMemory {\n humanPrefix: string;\n aiPrefix: string;\n llm: ChatOpenAI;\n memoryKey: string;\n maxTokenLimit: number;\n returnMessages: boolean;\n outputKey: string;\n intermediateStepsKey: string;\n constructor(fields: OpenAIAgentTokenBufferMemoryFields);\n get memoryKeys(): string[];\n /**\n * Retrieves the messages from the chat history.\n * @returns Promise that resolves with the messages from the chat history.\n */\n getMessages(): Promise<import(\"@langchain/core/messages\").BaseMessage<import(\"@langchain/core/messages\").MessageStructure
|
|
1
|
+
{"version":3,"file":"token_buffer_memory.d.cts","names":["ChatOpenAI","InputValues","MemoryVariables","OutputValues","BaseChatMemory","BaseChatMemoryInput","OpenAIAgentTokenBufferMemoryFields","OpenAIAgentTokenBufferMemory","_langchain_core_messages0","MessageToolSet","MessageStructure","MessageType","BaseMessage","Promise"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts"],"sourcesContent":["import { ChatOpenAI } from \"@langchain/openai\";\nimport { InputValues, MemoryVariables, OutputValues } from \"@langchain/core/memory\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"../../../memory/chat_memory.js\";\n/**\n * Type definition for the fields required to initialize an instance of\n * OpenAIAgentTokenBufferMemory.\n */\nexport type OpenAIAgentTokenBufferMemoryFields = BaseChatMemoryInput & {\n llm: ChatOpenAI;\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n maxTokenLimit?: number;\n returnMessages?: boolean;\n outputKey?: string;\n intermediateStepsKey?: string;\n};\n/**\n * Memory used to save agent output and intermediate steps.\n */\nexport declare class OpenAIAgentTokenBufferMemory extends BaseChatMemory {\n humanPrefix: string;\n aiPrefix: string;\n llm: ChatOpenAI;\n memoryKey: string;\n maxTokenLimit: number;\n returnMessages: boolean;\n outputKey: string;\n intermediateStepsKey: string;\n constructor(fields: OpenAIAgentTokenBufferMemoryFields);\n get memoryKeys(): string[];\n /**\n * Retrieves the messages from the chat history.\n * @returns Promise that resolves with the messages from the chat history.\n */\n getMessages(): Promise<import(\"@langchain/core/messages\").BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[]>;\n /**\n * Loads memory variables from the input values.\n * @param _values Input values.\n * @returns Promise that resolves with the loaded memory variables.\n */\n loadMemoryVariables(_values: InputValues): Promise<MemoryVariables>;\n /**\n * Saves the context of the chat, including user input, AI output, and\n * intermediate steps. Prunes the chat history if the total token count\n * exceeds the maximum limit.\n * @param inputValues Input values.\n * @param outputValues Output values.\n * @returns Promise that resolves when the context has been saved.\n */\n saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;\n}\n//# sourceMappingURL=token_buffer_memory.d.ts.map"],"mappings":";;;;;;;;;;AAOA;AAaqBO,KAbTD,kCAAAA,GAAqCD,mBAaA,GAAA;EAGxCL,GAAAA,EAfAA,UAeAA;EAMeM,WAAAA,CAAAA,EAAAA,MAAAA;EAAkCE,QAAAA,CAAAA,EAAAA,MAAAA;EAMqHA,SAAAA,CAAAA,EAAAA,MAAAA;EAAlDA,aAAAA,CAAAA,EAAAA,MAAAA;EAAmGA,cAAAA,CAAAA,EAAAA,OAAlKI;EAA3CC,SAAAA,CAAAA,EAAAA,MAAAA;EAMcZ,oBAAAA,CAAAA,EAAAA,MAAAA;CAAsBC;;;;AASgBW,cA9BlDN,4BAAAA,SAAqCH,cAAAA,CA8BaS;EA9BbT,WAAAA,EAAAA,MAAAA;EAAc,QAAA,EAAA,MAAA;OAG/DJ;;;;;;sBAMeM;;;;;;iBAMLO,QAA6ML,yBAAAA,CAAlKI,YAAiHJ,yBAAAA,CAAlEE,iBANnDF,yBAAAA,CAMuGC,cAAAA,GAApCD,yBAAAA,CAAwFG,WAAAA;;;;;;+BAMpLV,cAAcY,QAAQX;;;;;;;;;2BAS1BD,2BAA2BE,eAAeU"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseChatMemory, BaseChatMemoryInput } from "../../../memory/chat_memory.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as _langchain_core_messages2 from "@langchain/core/messages";
|
|
3
3
|
import { InputValues, MemoryVariables, OutputValues } from "@langchain/core/memory";
|
|
4
4
|
import { ChatOpenAI } from "@langchain/openai";
|
|
5
5
|
|
|
@@ -37,7 +37,7 @@ declare class OpenAIAgentTokenBufferMemory extends BaseChatMemory {
|
|
|
37
37
|
* Retrieves the messages from the chat history.
|
|
38
38
|
* @returns Promise that resolves with the messages from the chat history.
|
|
39
39
|
*/
|
|
40
|
-
getMessages(): Promise<
|
|
40
|
+
getMessages(): Promise<_langchain_core_messages2.BaseMessage<_langchain_core_messages2.MessageStructure<_langchain_core_messages2.MessageToolSet>, _langchain_core_messages2.MessageType>[]>;
|
|
41
41
|
/**
|
|
42
42
|
* Loads memory variables from the input values.
|
|
43
43
|
* @param _values Input values.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token_buffer_memory.d.ts","names":["ChatOpenAI","InputValues","MemoryVariables","OutputValues","BaseChatMemory","BaseChatMemoryInput","OpenAIAgentTokenBufferMemoryFields","OpenAIAgentTokenBufferMemory","
|
|
1
|
+
{"version":3,"file":"token_buffer_memory.d.ts","names":["ChatOpenAI","InputValues","MemoryVariables","OutputValues","BaseChatMemory","BaseChatMemoryInput","OpenAIAgentTokenBufferMemoryFields","OpenAIAgentTokenBufferMemory","_langchain_core_messages2","MessageToolSet","MessageStructure","MessageType","BaseMessage","Promise"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts"],"sourcesContent":["import { ChatOpenAI } from \"@langchain/openai\";\nimport { InputValues, MemoryVariables, OutputValues } from \"@langchain/core/memory\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"../../../memory/chat_memory.js\";\n/**\n * Type definition for the fields required to initialize an instance of\n * OpenAIAgentTokenBufferMemory.\n */\nexport type OpenAIAgentTokenBufferMemoryFields = BaseChatMemoryInput & {\n llm: ChatOpenAI;\n humanPrefix?: string;\n aiPrefix?: string;\n memoryKey?: string;\n maxTokenLimit?: number;\n returnMessages?: boolean;\n outputKey?: string;\n intermediateStepsKey?: string;\n};\n/**\n * Memory used to save agent output and intermediate steps.\n */\nexport declare class OpenAIAgentTokenBufferMemory extends BaseChatMemory {\n humanPrefix: string;\n aiPrefix: string;\n llm: ChatOpenAI;\n memoryKey: string;\n maxTokenLimit: number;\n returnMessages: boolean;\n outputKey: string;\n intermediateStepsKey: string;\n constructor(fields: OpenAIAgentTokenBufferMemoryFields);\n get memoryKeys(): string[];\n /**\n * Retrieves the messages from the chat history.\n * @returns Promise that resolves with the messages from the chat history.\n */\n getMessages(): Promise<import(\"@langchain/core/messages\").BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[]>;\n /**\n * Loads memory variables from the input values.\n * @param _values Input values.\n * @returns Promise that resolves with the loaded memory variables.\n */\n loadMemoryVariables(_values: InputValues): Promise<MemoryVariables>;\n /**\n * Saves the context of the chat, including user input, AI output, and\n * intermediate steps. Prunes the chat history if the total token count\n * exceeds the maximum limit.\n * @param inputValues Input values.\n * @param outputValues Output values.\n * @returns Promise that resolves when the context has been saved.\n */\n saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;\n}\n//# sourceMappingURL=token_buffer_memory.d.ts.map"],"mappings":";;;;;;;;;;AAOA;AAaqBO,KAbTD,kCAAAA,GAAqCD,mBAaA,GAAA;EAGxCL,GAAAA,EAfAA,UAeAA;EAMeM,WAAAA,CAAAA,EAAAA,MAAAA;EAAkCE,QAAAA,CAAAA,EAAAA,MAAAA;EAMqHA,SAAAA,CAAAA,EAAAA,MAAAA;EAAlDA,aAAAA,CAAAA,EAAAA,MAAAA;EAAmGA,cAAAA,CAAAA,EAAAA,OAAlKI;EAA3CC,SAAAA,CAAAA,EAAAA,MAAAA;EAMcZ,oBAAAA,CAAAA,EAAAA,MAAAA;CAAsBC;;;;AASgBW,cA9BlDN,4BAAAA,SAAqCH,cAAAA,CA8BaS;EA9BbT,WAAAA,EAAAA,MAAAA;EAAc,QAAA,EAAA,MAAA;OAG/DJ;;;;;;sBAMeM;;;;;;iBAMLO,QAA6ML,yBAAAA,CAAlKI,YAAiHJ,yBAAAA,CAAlEE,iBANnDF,yBAAAA,CAMuGC,cAAAA,GAApCD,yBAAAA,CAAwFG,WAAAA;;;;;;+BAMpLV,cAAcY,QAAQX;;;;;;;;;2BAS1BD,2BAA2BE,eAAeU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.cts","names":["BaseRetrieverInterface","z","DynamicStructuredTool","DynamicStructuredToolInput","createRetrieverTool","Omit","ZodString","ZodTypeAny","ZodObject"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.d.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { DynamicStructuredTool, DynamicStructuredToolInput } from \"@langchain/core/tools\";\nexport declare function createRetrieverTool(retriever: BaseRetrieverInterface, input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">): DynamicStructuredTool<z.ZodObject<{\n input: z.ZodString;\n}, \"strip\", z.ZodTypeAny, {\n input: string;\n}, {\n input: string;\n}>, {\n input: string;\n}, {\n input: string;\n}, string>;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;;iBAGwBI,mBAAAA,YAA+BJ,+BAA+BK,KAAKF,iDAAiDD,sBAAsBD,CAAAA,CAAEO;SACzJP,CAAAA,CAAEK;AADb,CAAA,EAAA,OAAwBF,EAEZH,CAAAA,CAAEM,UAFUH,EAAmB;EAAYJ,KAAAA,EAAAA,MAAAA;CAAoCG,EAAAA;EAALE,KAAAA,EAAAA,MAAAA;CAC3EJ,CAAAA,EAAEK;EACCC,KAAAA,EAAAA,MAAAA;CAFoJN,EAAEO;EAAxBN,KAAAA,EAAAA,MAAAA;AAAqB,CAAA,EAAA,MAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"tool.d.cts","names":["BaseRetrieverInterface","z","DynamicStructuredTool","DynamicStructuredToolInput","createRetrieverTool","Omit","ZodString","ZodTypeAny","ZodObject"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.d.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { DynamicStructuredTool, DynamicStructuredToolInput } from \"@langchain/core/tools\";\nexport declare function createRetrieverTool(retriever: BaseRetrieverInterface, input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">): DynamicStructuredTool<z.ZodObject<{\n input: z.ZodString;\n}, \"strip\", z.ZodTypeAny, {\n input: string;\n}, {\n input: string;\n}>, {\n input: string;\n}, {\n input: string;\n}, string, string>;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;;iBAGwBI,mBAAAA,YAA+BJ,+BAA+BK,KAAKF,iDAAiDD,sBAAsBD,CAAAA,CAAEO;SACzJP,CAAAA,CAAEK;AADb,CAAA,EAAA,OAAwBF,EAEZH,CAAAA,CAAEM,UAFUH,EAAmB;EAAYJ,KAAAA,EAAAA,MAAAA;CAAoCG,EAAAA;EAALE,KAAAA,EAAAA,MAAAA;CAC3EJ,CAAAA,EAAEK;EACCC,KAAAA,EAAAA,MAAAA;CAFoJN,EAAEO;EAAxBN,KAAAA,EAAAA,MAAAA;AAAqB,CAAA,EAAA,MAAA,EAAA,MAAA,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","names":["BaseRetrieverInterface","z","DynamicStructuredTool","DynamicStructuredToolInput","createRetrieverTool","Omit","ZodString","ZodTypeAny","ZodObject"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.d.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { DynamicStructuredTool, DynamicStructuredToolInput } from \"@langchain/core/tools\";\nexport declare function createRetrieverTool(retriever: BaseRetrieverInterface, input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">): DynamicStructuredTool<z.ZodObject<{\n input: z.ZodString;\n}, \"strip\", z.ZodTypeAny, {\n input: string;\n}, {\n input: string;\n}>, {\n input: string;\n}, {\n input: string;\n}, string>;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;;iBAGwBI,mBAAAA,YAA+BJ,+BAA+BK,KAAKF,iDAAiDD,sBAAsBD,CAAAA,CAAEO;SACzJP,CAAAA,CAAEK;AADb,CAAA,EAAA,OAAwBF,EAEZH,CAAAA,CAAEM,UAFUH,EAAmB;EAAYJ,KAAAA,EAAAA,MAAAA;CAAoCG,EAAAA;EAALE,KAAAA,EAAAA,MAAAA;CAC3EJ,CAAAA,EAAEK;EACCC,KAAAA,EAAAA,MAAAA;CAFoJN,EAAEO;EAAxBN,KAAAA,EAAAA,MAAAA;AAAqB,CAAA,EAAA,MAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"tool.d.ts","names":["BaseRetrieverInterface","z","DynamicStructuredTool","DynamicStructuredToolInput","createRetrieverTool","Omit","ZodString","ZodTypeAny","ZodObject"],"sources":["../../../../src/agents/toolkits/conversational_retrieval/tool.d.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { z } from \"zod\";\nimport { DynamicStructuredTool, DynamicStructuredToolInput } from \"@langchain/core/tools\";\nexport declare function createRetrieverTool(retriever: BaseRetrieverInterface, input: Omit<DynamicStructuredToolInput, \"func\" | \"schema\">): DynamicStructuredTool<z.ZodObject<{\n input: z.ZodString;\n}, \"strip\", z.ZodTypeAny, {\n input: string;\n}, {\n input: string;\n}>, {\n input: string;\n}, {\n input: string;\n}, string, string>;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;;iBAGwBI,mBAAAA,YAA+BJ,+BAA+BK,KAAKF,iDAAiDD,sBAAsBD,CAAAA,CAAEO;SACzJP,CAAAA,CAAEK;AADb,CAAA,EAAA,OAAwBF,EAEZH,CAAAA,CAAEM,UAFUH,EAAmB;EAAYJ,KAAAA,EAAAA,MAAAA;CAAoCG,EAAAA;EAALE,KAAAA,EAAAA,MAAAA;CAC3EJ,CAAAA,EAAEK;EACCC,KAAAA,EAAAA,MAAAA;CAFoJN,EAAEO;EAAxBN,KAAAA,EAAAA,MAAAA;AAAqB,CAAA,EAAA,MAAA,EAAA,MAAA,CAAA"}
|
|
@@ -8,6 +8,17 @@ const __langchain_core_prompts = require_rolldown_runtime.__toESM(require("@lang
|
|
|
8
8
|
|
|
9
9
|
//#region src/chains/openai_functions/openapi.ts
|
|
10
10
|
/**
|
|
11
|
+
* Gets the composition type of a schema if it exists.
|
|
12
|
+
* @param schema
|
|
13
|
+
* @returns The composition type of the schema if it exists.
|
|
14
|
+
*/
|
|
15
|
+
function getCompositionType(schema) {
|
|
16
|
+
if (schema.anyOf !== void 0) return "anyOf";
|
|
17
|
+
if (schema.allOf !== void 0) return "allOf";
|
|
18
|
+
if (schema.oneOf !== void 0) return "oneOf";
|
|
19
|
+
return void 0;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
11
22
|
* Formats a URL by replacing path parameters with their corresponding
|
|
12
23
|
* values.
|
|
13
24
|
* @param url The URL to format.
|
|
@@ -87,6 +98,8 @@ function convertOpenAPIParamsToJSONSchema(params, spec) {
|
|
|
87
98
|
* @returns The JSON schema representation of the OpenAPI schema.
|
|
88
99
|
*/
|
|
89
100
|
function convertOpenAPISchemaToJSONSchema(schema, spec) {
|
|
101
|
+
const compositionType = getCompositionType(schema);
|
|
102
|
+
if (compositionType !== void 0 && schema[compositionType] !== void 0) return { [compositionType]: schema[compositionType].map((s) => convertOpenAPISchemaToJSONSchema(spec.getSchema(s), spec)) };
|
|
90
103
|
if (schema.type === "object") return Object.keys(schema.properties ?? {}).reduce((jsonSchema, propertyName) => {
|
|
91
104
|
if (!schema.properties) return jsonSchema;
|
|
92
105
|
const openAPIProperty = spec.getSchema(schema.properties[propertyName]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.cjs","names":["url: string","pathParams: Record<string, string>","newParams: Record<string, string>","params: OpenAPIV3_1.ParameterObject[]","spec: OpenAPISpec","jsonSchema: JsonSchema7ObjectType","schema: OpenAPIV3_1.SchemaObject","nameToCallMap: Record<string, { method: string; url: string }>","operationParams: Record<string, OpenAPIV3_1.ParameterObject[]>","paramLocationToRequestArgNameMap: Record<string, string>","requestArgsSchema: Record<string, JsonSchema7ObjectType> & {\n data?:\n | JsonSchema7ObjectType\n | {\n anyOf?: JsonSchema7ObjectType[];\n };\n }","requestBodySchemas: Record<string, JsonSchema7ObjectType>","openAIFunction: OpenAIClient.Chat.ChatCompletionCreateParams.Function","OpenAPISpec","name: string","requestArgs: Record<string, any>","options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }","filteredArgs: Record<string, any>","headers: Record<string, string>","BaseChain","config: { requestMethod: SimpleRequestChainExecutionMethod }","values: ChainValues","_runManager?: CallbackManagerForChainRun","spec: OpenAPIV3_1.Document | string","options: OpenAPIChainOptions","ChatPromptTemplate","HumanMessagePromptTemplate","LLMChain","JsonOutputFunctionsParser","SequentialChain"],"sources":["../../../src/chains/openai_functions/openapi.ts"],"sourcesContent":["import type { OpenAIClient } from \"@langchain/openai\";\nimport {\n type JsonSchema7ObjectType,\n type JsonSchema7ArrayType,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport type { OpenAPIV3_1 } from \"openapi-types\";\n\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { BaseFunctionCallOptions } from \"@langchain/core/language_models/base\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n BasePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { OpenAPISpec } from \"../../util/openapi.js\";\nimport { BaseChain } from \"../base.js\";\nimport { LLMChain, LLMChainInput } from \"../llm_chain.js\";\nimport { SequentialChain } from \"../sequential_chain.js\";\nimport { JsonOutputFunctionsParser } from \"../../output_parsers/openai_functions.js\";\n\n/**\n * Type representing a function for executing OpenAPI requests.\n */\ntype OpenAPIExecutionMethod = (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>,\n options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }\n) => Promise<string>;\n\n/**\n * Formats a URL by replacing path parameters with their corresponding\n * values.\n * @param url The URL to format.\n * @param pathParams The path parameters to replace in the URL.\n * @returns The formatted URL.\n */\nfunction formatURL(url: string, pathParams: Record<string, string>): string {\n const expectedPathParamNames = [...url.matchAll(/{(.*?)}/g)].map(\n (match) => match[1]\n );\n const newParams: Record<string, string> = {};\n for (const paramName of expectedPathParamNames) {\n const cleanParamName = paramName.replace(/^\\.;/, \"\").replace(/\\*$/, \"\");\n const value = pathParams[cleanParamName];\n let formattedValue;\n if (Array.isArray(value)) {\n if (paramName.startsWith(\".\")) {\n const separator = paramName.endsWith(\"*\") ? \".\" : \",\";\n formattedValue = `.${value.join(separator)}`;\n } else if (paramName.startsWith(\",\")) {\n const separator = paramName.endsWith(\"*\") ? `${cleanParamName}=` : \",\";\n formattedValue = `${cleanParamName}=${value.join(separator)}`;\n } else {\n formattedValue = value.join(\",\");\n }\n } else if (typeof value === \"object\") {\n const kvSeparator = paramName.endsWith(\"*\") ? \"=\" : \",\";\n const kvStrings = Object.entries(value).map(\n ([k, v]) => k + kvSeparator + v\n );\n let entrySeparator;\n if (paramName.startsWith(\".\")) {\n entrySeparator = \".\";\n formattedValue = \".\";\n } else if (paramName.startsWith(\";\")) {\n entrySeparator = \";\";\n formattedValue = \";\";\n } else {\n entrySeparator = \",\";\n formattedValue = \"\";\n }\n formattedValue += kvStrings.join(entrySeparator);\n } else {\n if (paramName.startsWith(\".\")) {\n formattedValue = `.${value}`;\n } else if (paramName.startsWith(\";\")) {\n formattedValue = `;${cleanParamName}=${value}`;\n } else {\n formattedValue = value;\n }\n }\n newParams[paramName] = formattedValue;\n }\n let formattedUrl = url;\n for (const [key, newValue] of Object.entries(newParams)) {\n formattedUrl = formattedUrl.replace(`{${key}}`, newValue);\n }\n return formattedUrl;\n}\n\n/**\n * Converts OpenAPI parameters to JSON schema format.\n * @param params The OpenAPI parameters to convert.\n * @param spec The OpenAPI specification that contains the parameters.\n * @returns The JSON schema representation of the OpenAPI parameters.\n */\nfunction convertOpenAPIParamsToJSONSchema(\n params: OpenAPIV3_1.ParameterObject[],\n spec: OpenAPISpec\n) {\n return params.reduce(\n (jsonSchema: JsonSchema7ObjectType, param) => {\n let schema;\n if (param.schema) {\n schema = spec.getSchema(param.schema);\n jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n );\n } else if (param.content) {\n const mediaTypeSchema = Object.values(param.content)[0].schema;\n if (mediaTypeSchema) {\n schema = spec.getSchema(mediaTypeSchema);\n }\n if (!schema) {\n return jsonSchema;\n }\n if (schema.description === undefined) {\n schema.description = param.description ?? \"\";\n }\n jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n );\n } else {\n return jsonSchema;\n }\n if (param.required && Array.isArray(jsonSchema.required)) {\n jsonSchema.required.push(param.name);\n }\n return jsonSchema;\n },\n {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: {},\n }\n );\n}\n\n// OpenAI throws errors on extraneous schema properties, e.g. if \"required\" is set on individual ones\n/**\n * Converts OpenAPI schemas to JSON schema format.\n * @param schema The OpenAPI schema to convert.\n * @param spec The OpenAPI specification that contains the schema.\n * @returns The JSON schema representation of the OpenAPI schema.\n */\nexport function convertOpenAPISchemaToJSONSchema(\n schema: OpenAPIV3_1.SchemaObject,\n spec: OpenAPISpec\n): JsonSchema7Type {\n if (schema.type === \"object\") {\n return Object.keys(schema.properties ?? {}).reduce(\n (jsonSchema: JsonSchema7ObjectType, propertyName) => {\n if (!schema.properties) {\n return jsonSchema;\n }\n const openAPIProperty = spec.getSchema(schema.properties[propertyName]);\n if (openAPIProperty.type === undefined) {\n return jsonSchema;\n }\n jsonSchema.properties[propertyName] = convertOpenAPISchemaToJSONSchema(\n openAPIProperty,\n spec\n );\n if (\n schema.required?.includes(propertyName) &&\n jsonSchema.required !== undefined\n ) {\n jsonSchema.required.push(propertyName);\n }\n return jsonSchema;\n },\n {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: {},\n }\n );\n }\n if (schema.type === \"array\") {\n const openAPIItems = spec.getSchema(schema.items ?? {});\n return {\n type: \"array\",\n items: convertOpenAPISchemaToJSONSchema(openAPIItems, spec),\n minItems: schema.minItems,\n maxItems: schema.maxItems,\n } as JsonSchema7ArrayType;\n }\n return {\n type: schema.type ?? \"string\",\n } as JsonSchema7Type;\n}\n\n/**\n * Converts an OpenAPI specification to OpenAI functions.\n * @param spec The OpenAPI specification to convert.\n * @returns An object containing the OpenAI functions derived from the OpenAPI specification and a default execution method.\n */\nexport function convertOpenAPISpecToOpenAIFunctions(spec: OpenAPISpec): {\n openAIFunctions: OpenAIClient.Chat.ChatCompletionCreateParams.Function[];\n defaultExecutionMethod?: OpenAPIExecutionMethod;\n} {\n if (!spec.document.paths) {\n return { openAIFunctions: [] };\n }\n const openAIFunctions = [];\n const nameToCallMap: Record<string, { method: string; url: string }> = {};\n for (const path of Object.keys(spec.document.paths)) {\n const pathParameters = spec.getParametersForPath(path);\n for (const method of spec.getMethodsForPath(path)) {\n const operation = spec.getOperation(path, method);\n if (!operation) {\n return { openAIFunctions: [] };\n }\n const operationParametersByLocation = pathParameters\n .concat(spec.getParametersForOperation(operation))\n .reduce(\n (\n operationParams: Record<string, OpenAPIV3_1.ParameterObject[]>,\n param\n ) => {\n if (!operationParams[param.in]) {\n operationParams[param.in] = [];\n }\n operationParams[param.in].push(param);\n return operationParams;\n },\n {}\n );\n const paramLocationToRequestArgNameMap: Record<string, string> = {\n query: \"params\",\n header: \"headers\",\n cookie: \"cookies\",\n path: \"path_params\",\n };\n const requestArgsSchema: Record<string, JsonSchema7ObjectType> & {\n data?:\n | JsonSchema7ObjectType\n | {\n anyOf?: JsonSchema7ObjectType[];\n };\n } = {};\n for (const paramLocation of Object.keys(\n paramLocationToRequestArgNameMap\n )) {\n if (operationParametersByLocation[paramLocation]) {\n requestArgsSchema[paramLocationToRequestArgNameMap[paramLocation]] =\n convertOpenAPIParamsToJSONSchema(\n operationParametersByLocation[paramLocation],\n spec\n );\n }\n }\n const requestBody = spec.getRequestBodyForOperation(operation);\n if (requestBody?.content !== undefined) {\n const requestBodySchemas: Record<string, JsonSchema7ObjectType> = {};\n for (const [mediaType, mediaTypeObject] of Object.entries(\n requestBody.content\n )) {\n if (mediaTypeObject.schema !== undefined) {\n const schema = spec.getSchema(mediaTypeObject.schema);\n requestBodySchemas[mediaType] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n ) as JsonSchema7ObjectType;\n }\n }\n const mediaTypes = Object.keys(requestBodySchemas);\n if (mediaTypes.length === 1) {\n requestArgsSchema.data = requestBodySchemas[mediaTypes[0]];\n } else if (mediaTypes.length > 1) {\n requestArgsSchema.data = {\n anyOf: Object.values(requestBodySchemas),\n };\n }\n }\n const openAIFunction: OpenAIClient.Chat.ChatCompletionCreateParams.Function =\n {\n name: OpenAPISpec.getCleanedOperationId(operation, path, method),\n description: operation.description ?? operation.summary ?? \"\",\n parameters: {\n type: \"object\",\n properties: requestArgsSchema,\n // All remaining top-level parameters are required\n required: Object.keys(requestArgsSchema),\n },\n };\n\n openAIFunctions.push(openAIFunction);\n const baseUrl = (spec.baseUrl ?? \"\").endsWith(\"/\")\n ? (spec.baseUrl ?? \"\").slice(0, -1)\n : spec.baseUrl ?? \"\";\n nameToCallMap[openAIFunction.name] = {\n method,\n url: baseUrl + path,\n };\n }\n }\n return {\n openAIFunctions,\n defaultExecutionMethod: async (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>,\n options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }\n ) => {\n const {\n headers: customHeaders,\n params: customParams,\n ...rest\n } = options ?? {};\n const { method, url } = nameToCallMap[name];\n const requestParams = requestArgs.params ?? {};\n const nonEmptyParams = Object.keys(requestParams).reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (filteredArgs: Record<string, any>, argName) => {\n if (\n requestParams[argName] !== \"\" &&\n requestParams[argName] !== null &&\n requestParams[argName] !== undefined\n ) {\n filteredArgs[argName] = requestParams[argName];\n }\n return filteredArgs;\n },\n {}\n );\n const queryString = new URLSearchParams({\n ...nonEmptyParams,\n ...customParams,\n }).toString();\n const pathParams = requestArgs.path_params;\n const formattedUrl =\n formatURL(url, pathParams) +\n (queryString.length ? `?${queryString}` : \"\");\n const headers: Record<string, string> = {};\n let body;\n if (requestArgs.data !== undefined) {\n let contentType = \"text/plain\";\n if (typeof requestArgs.data !== \"string\") {\n if (typeof requestArgs.data === \"object\") {\n contentType = \"application/json\";\n }\n body = JSON.stringify(requestArgs.data);\n } else {\n body = requestArgs.data;\n }\n headers[\"content-type\"] = contentType;\n }\n const response = await fetch(formattedUrl, {\n ...requestArgs,\n method,\n headers: {\n ...headers,\n ...requestArgs.headers,\n ...customHeaders,\n },\n body,\n ...rest,\n });\n let output;\n if (response.status < 200 || response.status > 299) {\n output = `${response.status}: ${\n response.statusText\n } for ${name} called with ${JSON.stringify(queryString)}`;\n } else {\n output = await response.text();\n }\n return output;\n },\n };\n}\n\n/**\n * Type representing a function for executing simple requests.\n */\ntype SimpleRequestChainExecutionMethod = (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>\n) => Promise<string>;\n\n/**\n * A chain for making simple API requests.\n */\nclass SimpleRequestChain extends BaseChain {\n static lc_name() {\n return \"SimpleRequestChain\";\n }\n\n private requestMethod: SimpleRequestChainExecutionMethod;\n\n inputKey = \"function\";\n\n outputKey = \"response\";\n\n constructor(config: { requestMethod: SimpleRequestChainExecutionMethod }) {\n super();\n this.requestMethod = config.requestMethod;\n }\n\n get inputKeys() {\n return [this.inputKey];\n }\n\n get outputKeys() {\n return [this.outputKey];\n }\n\n _chainType() {\n return \"simple_request_chain\" as const;\n }\n\n /** @ignore */\n async _call(\n values: ChainValues,\n _runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const inputKeyValue = values[this.inputKey];\n const methodName = inputKeyValue.name;\n const args = inputKeyValue.arguments;\n const response = await this.requestMethod(methodName, args);\n return { [this.outputKey]: response };\n }\n}\n\n/**\n * Type representing the options for creating an OpenAPI chain.\n */\nexport type OpenAPIChainOptions = {\n llm?: BaseChatModel<BaseFunctionCallOptions>;\n prompt?: BasePromptTemplate;\n requestChain?: BaseChain;\n llmChainInputs?: LLMChainInput;\n headers?: Record<string, string>;\n params?: Record<string, string>;\n verbose?: boolean;\n};\n\n/**\n * Create a chain for querying an API from a OpenAPI spec.\n * @param spec OpenAPISpec or url/file/text string corresponding to one.\n * @param options Custom options passed into the chain\n * @returns OpenAPIChain\n */\nexport async function createOpenAPIChain(\n spec: OpenAPIV3_1.Document | string,\n options: OpenAPIChainOptions = {}\n) {\n let convertedSpec;\n if (typeof spec === \"string\") {\n try {\n convertedSpec = await OpenAPISpec.fromURL(spec);\n } catch {\n try {\n convertedSpec = OpenAPISpec.fromString(spec);\n } catch {\n throw new Error(`Unable to parse spec from source ${spec}.`);\n }\n }\n } else {\n convertedSpec = OpenAPISpec.fromObject(spec);\n }\n const { openAIFunctions, defaultExecutionMethod } =\n convertOpenAPISpecToOpenAIFunctions(convertedSpec);\n if (defaultExecutionMethod === undefined) {\n throw new Error(\n `Could not parse any valid operations from the provided spec.`\n );\n }\n\n if (!options.llm) {\n throw new Error(\"`llm` option is required\");\n }\n\n const {\n llm = options.llm,\n prompt = ChatPromptTemplate.fromMessages([\n HumanMessagePromptTemplate.fromTemplate(\n \"Use the provided API's to respond to this user query:\\n\\n{query}\"\n ),\n ]),\n requestChain = new SimpleRequestChain({\n requestMethod: async (name, args) =>\n defaultExecutionMethod(name, args, {\n headers: options.headers,\n params: options.params,\n }),\n }),\n llmChainInputs = {},\n verbose,\n ...rest\n } = options;\n const formatChain = new LLMChain({\n llm,\n prompt,\n outputParser: new JsonOutputFunctionsParser({ argsOnly: false }),\n outputKey: \"function\",\n llmKwargs: { functions: openAIFunctions },\n ...llmChainInputs,\n });\n return new SequentialChain({\n chains: [formatChain, requestChain],\n outputVariables: [\"response\"],\n inputVariables: formatChain.inputKeys,\n verbose,\n ...rest,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,SAAS,UAAUA,KAAaC,YAA4C;CAC1E,MAAM,yBAAyB,CAAC,GAAG,IAAI,SAAS,WAAW,AAAC,EAAC,IAC3D,CAAC,UAAU,MAAM,GAClB;CACD,MAAMC,YAAoC,CAAE;AAC5C,MAAK,MAAM,aAAa,wBAAwB;EAC9C,MAAM,iBAAiB,UAAU,QAAQ,QAAQ,GAAG,CAAC,QAAQ,OAAO,GAAG;EACvE,MAAM,QAAQ,WAAW;EACzB,IAAI;AACJ,MAAI,MAAM,QAAQ,MAAM,CACtB,KAAI,UAAU,WAAW,IAAI,EAAE;GAC7B,MAAM,YAAY,UAAU,SAAS,IAAI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AM,EAAE,iBAAiB,wBAAwB,GAC/C,oCAAoC,cAAc;AACpD,KAAI,2BAA2B,OAC7B,OAAM,IAAI,MACR,CAAC,4DAA4D,CAAC;AAIlE,KAAI,CAAC,QAAQ,IACX,OAAM,IAAI,MAAM;CAGlB,MAAM,EACJ,MAAM,QAAQ,KACd,SAASY,4CAAmB,aAAa,CACvCC,oDAA2B,aACzB,mEACD,AACF,EAAC,EACF,eAAe,IAAI,mBAAmB,EACpC,eAAe,OAAO,MAAM,SAC1B,uBAAuB,MAAM,MAAM;EACjC,SAAS,QAAQ;EACjB,QAAQ,QAAQ;CACjB,EAAC,CACL,IACD,iBAAiB,CAAE,GACnB,QACA,GAAG,MACJ,GAAG;CACJ,MAAM,cAAc,IAAIC,2BAAS;EAC/B;EACA;EACA,cAAc,IAAIC,mDAA0B,EAAE,UAAU,MAAO;EAC/D,WAAW;EACX,WAAW,EAAE,WAAW,gBAAiB;EACzC,GAAG;CACJ;AACD,QAAO,IAAIC,yCAAgB;EACzB,QAAQ,CAAC,aAAa,YAAa;EACnC,iBAAiB,CAAC,UAAW;EAC7B,gBAAgB,YAAY;EAC5B;EACA,GAAG;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"openapi.cjs","names":["schema: OpenAPIV3_1.SchemaObject","url: string","pathParams: Record<string, string>","newParams: Record<string, string>","params: OpenAPIV3_1.ParameterObject[]","spec: OpenAPISpec","jsonSchema: JsonSchema7ObjectType","nameToCallMap: Record<string, { method: string; url: string }>","operationParams: Record<string, OpenAPIV3_1.ParameterObject[]>","paramLocationToRequestArgNameMap: Record<string, string>","requestArgsSchema: Record<string, JsonSchema7ObjectType> & {\n data?:\n | JsonSchema7ObjectType\n | {\n anyOf?: JsonSchema7ObjectType[];\n };\n }","requestBodySchemas: Record<string, JsonSchema7ObjectType>","openAIFunction: OpenAIClient.Chat.ChatCompletionCreateParams.Function","OpenAPISpec","name: string","requestArgs: Record<string, any>","options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }","filteredArgs: Record<string, any>","headers: Record<string, string>","BaseChain","config: { requestMethod: SimpleRequestChainExecutionMethod }","values: ChainValues","_runManager?: CallbackManagerForChainRun","spec: OpenAPIV3_1.Document | string","options: OpenAPIChainOptions","ChatPromptTemplate","HumanMessagePromptTemplate","LLMChain","JsonOutputFunctionsParser","SequentialChain"],"sources":["../../../src/chains/openai_functions/openapi.ts"],"sourcesContent":["import type { OpenAIClient } from \"@langchain/openai\";\nimport {\n type JsonSchema7ObjectType,\n type JsonSchema7ArrayType,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport type { OpenAPIV3_1 } from \"openapi-types\";\n\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { BaseFunctionCallOptions } from \"@langchain/core/language_models/base\";\nimport {\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n BasePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { OpenAPISpec } from \"../../util/openapi.js\";\nimport { BaseChain } from \"../base.js\";\nimport { LLMChain, LLMChainInput } from \"../llm_chain.js\";\nimport { SequentialChain } from \"../sequential_chain.js\";\nimport { JsonOutputFunctionsParser } from \"../../output_parsers/openai_functions.js\";\n\n/**\n * Type representing a function for executing OpenAPI requests.\n */\ntype OpenAPIExecutionMethod = (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>,\n options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }\n) => Promise<string>;\n\n/**\n * Type representing the composition types of a schema.\n */\ntype CompositionType = \"anyOf\" | \"allOf\" | \"oneOf\";\n\n/**\n * Gets the composition type of a schema if it exists.\n * @param schema\n * @returns The composition type of the schema if it exists.\n */\nfunction getCompositionType(\n schema: OpenAPIV3_1.SchemaObject\n): CompositionType | undefined {\n if (schema.anyOf !== undefined) {\n return \"anyOf\";\n }\n if (schema.allOf !== undefined) {\n return \"allOf\";\n }\n if (schema.oneOf !== undefined) {\n return \"oneOf\";\n }\n return undefined;\n}\n\n/**\n * Formats a URL by replacing path parameters with their corresponding\n * values.\n * @param url The URL to format.\n * @param pathParams The path parameters to replace in the URL.\n * @returns The formatted URL.\n */\nfunction formatURL(url: string, pathParams: Record<string, string>): string {\n const expectedPathParamNames = [...url.matchAll(/{(.*?)}/g)].map(\n (match) => match[1]\n );\n const newParams: Record<string, string> = {};\n for (const paramName of expectedPathParamNames) {\n const cleanParamName = paramName.replace(/^\\.;/, \"\").replace(/\\*$/, \"\");\n const value = pathParams[cleanParamName];\n let formattedValue;\n if (Array.isArray(value)) {\n if (paramName.startsWith(\".\")) {\n const separator = paramName.endsWith(\"*\") ? \".\" : \",\";\n formattedValue = `.${value.join(separator)}`;\n } else if (paramName.startsWith(\",\")) {\n const separator = paramName.endsWith(\"*\") ? `${cleanParamName}=` : \",\";\n formattedValue = `${cleanParamName}=${value.join(separator)}`;\n } else {\n formattedValue = value.join(\",\");\n }\n } else if (typeof value === \"object\") {\n const kvSeparator = paramName.endsWith(\"*\") ? \"=\" : \",\";\n const kvStrings = Object.entries(value).map(\n ([k, v]) => k + kvSeparator + v\n );\n let entrySeparator;\n if (paramName.startsWith(\".\")) {\n entrySeparator = \".\";\n formattedValue = \".\";\n } else if (paramName.startsWith(\";\")) {\n entrySeparator = \";\";\n formattedValue = \";\";\n } else {\n entrySeparator = \",\";\n formattedValue = \"\";\n }\n formattedValue += kvStrings.join(entrySeparator);\n } else {\n if (paramName.startsWith(\".\")) {\n formattedValue = `.${value}`;\n } else if (paramName.startsWith(\";\")) {\n formattedValue = `;${cleanParamName}=${value}`;\n } else {\n formattedValue = value;\n }\n }\n newParams[paramName] = formattedValue;\n }\n let formattedUrl = url;\n for (const [key, newValue] of Object.entries(newParams)) {\n formattedUrl = formattedUrl.replace(`{${key}}`, newValue);\n }\n return formattedUrl;\n}\n\n/**\n * Converts OpenAPI parameters to JSON schema format.\n * @param params The OpenAPI parameters to convert.\n * @param spec The OpenAPI specification that contains the parameters.\n * @returns The JSON schema representation of the OpenAPI parameters.\n */\nfunction convertOpenAPIParamsToJSONSchema(\n params: OpenAPIV3_1.ParameterObject[],\n spec: OpenAPISpec\n) {\n return params.reduce(\n (jsonSchema: JsonSchema7ObjectType, param) => {\n let schema;\n if (param.schema) {\n schema = spec.getSchema(param.schema);\n jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n );\n } else if (param.content) {\n const mediaTypeSchema = Object.values(param.content)[0].schema;\n if (mediaTypeSchema) {\n schema = spec.getSchema(mediaTypeSchema);\n }\n if (!schema) {\n return jsonSchema;\n }\n if (schema.description === undefined) {\n schema.description = param.description ?? \"\";\n }\n jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n );\n } else {\n return jsonSchema;\n }\n if (param.required && Array.isArray(jsonSchema.required)) {\n jsonSchema.required.push(param.name);\n }\n return jsonSchema;\n },\n {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: {},\n }\n );\n}\n\n// OpenAI throws errors on extraneous schema properties, e.g. if \"required\" is set on individual ones\n/**\n * Converts OpenAPI schemas to JSON schema format.\n * @param schema The OpenAPI schema to convert.\n * @param spec The OpenAPI specification that contains the schema.\n * @returns The JSON schema representation of the OpenAPI schema.\n */\nexport function convertOpenAPISchemaToJSONSchema(\n schema: OpenAPIV3_1.SchemaObject,\n spec: OpenAPISpec\n): JsonSchema7Type {\n const compositionType = getCompositionType(schema);\n if (compositionType !== undefined && schema[compositionType] !== undefined) {\n return {\n [compositionType]: schema[compositionType].map((s) =>\n convertOpenAPISchemaToJSONSchema(spec.getSchema(s), spec)\n ),\n } as JsonSchema7Type;\n }\n\n if (schema.type === \"object\") {\n return Object.keys(schema.properties ?? {}).reduce(\n (jsonSchema: JsonSchema7ObjectType, propertyName) => {\n if (!schema.properties) {\n return jsonSchema;\n }\n const openAPIProperty = spec.getSchema(schema.properties[propertyName]);\n if (openAPIProperty.type === undefined) {\n return jsonSchema;\n }\n jsonSchema.properties[propertyName] = convertOpenAPISchemaToJSONSchema(\n openAPIProperty,\n spec\n );\n if (\n schema.required?.includes(propertyName) &&\n jsonSchema.required !== undefined\n ) {\n jsonSchema.required.push(propertyName);\n }\n return jsonSchema;\n },\n {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: {},\n }\n );\n }\n\n if (schema.type === \"array\") {\n const openAPIItems = spec.getSchema(schema.items ?? {});\n return {\n type: \"array\",\n items: convertOpenAPISchemaToJSONSchema(openAPIItems, spec),\n minItems: schema.minItems,\n maxItems: schema.maxItems,\n } as JsonSchema7ArrayType;\n }\n return {\n type: schema.type ?? \"string\",\n } as JsonSchema7Type;\n}\n\n/**\n * Converts an OpenAPI specification to OpenAI functions.\n * @param spec The OpenAPI specification to convert.\n * @returns An object containing the OpenAI functions derived from the OpenAPI specification and a default execution method.\n */\nexport function convertOpenAPISpecToOpenAIFunctions(spec: OpenAPISpec): {\n openAIFunctions: OpenAIClient.Chat.ChatCompletionCreateParams.Function[];\n defaultExecutionMethod?: OpenAPIExecutionMethod;\n} {\n if (!spec.document.paths) {\n return { openAIFunctions: [] };\n }\n const openAIFunctions = [];\n const nameToCallMap: Record<string, { method: string; url: string }> = {};\n for (const path of Object.keys(spec.document.paths)) {\n const pathParameters = spec.getParametersForPath(path);\n for (const method of spec.getMethodsForPath(path)) {\n const operation = spec.getOperation(path, method);\n if (!operation) {\n return { openAIFunctions: [] };\n }\n const operationParametersByLocation = pathParameters\n .concat(spec.getParametersForOperation(operation))\n .reduce(\n (\n operationParams: Record<string, OpenAPIV3_1.ParameterObject[]>,\n param\n ) => {\n if (!operationParams[param.in]) {\n operationParams[param.in] = [];\n }\n operationParams[param.in].push(param);\n return operationParams;\n },\n {}\n );\n const paramLocationToRequestArgNameMap: Record<string, string> = {\n query: \"params\",\n header: \"headers\",\n cookie: \"cookies\",\n path: \"path_params\",\n };\n const requestArgsSchema: Record<string, JsonSchema7ObjectType> & {\n data?:\n | JsonSchema7ObjectType\n | {\n anyOf?: JsonSchema7ObjectType[];\n };\n } = {};\n for (const paramLocation of Object.keys(\n paramLocationToRequestArgNameMap\n )) {\n if (operationParametersByLocation[paramLocation]) {\n requestArgsSchema[paramLocationToRequestArgNameMap[paramLocation]] =\n convertOpenAPIParamsToJSONSchema(\n operationParametersByLocation[paramLocation],\n spec\n );\n }\n }\n const requestBody = spec.getRequestBodyForOperation(operation);\n if (requestBody?.content !== undefined) {\n const requestBodySchemas: Record<string, JsonSchema7ObjectType> = {};\n for (const [mediaType, mediaTypeObject] of Object.entries(\n requestBody.content\n )) {\n if (mediaTypeObject.schema !== undefined) {\n const schema = spec.getSchema(mediaTypeObject.schema);\n requestBodySchemas[mediaType] = convertOpenAPISchemaToJSONSchema(\n schema,\n spec\n ) as JsonSchema7ObjectType;\n }\n }\n const mediaTypes = Object.keys(requestBodySchemas);\n if (mediaTypes.length === 1) {\n requestArgsSchema.data = requestBodySchemas[mediaTypes[0]];\n } else if (mediaTypes.length > 1) {\n requestArgsSchema.data = {\n anyOf: Object.values(requestBodySchemas),\n };\n }\n }\n const openAIFunction: OpenAIClient.Chat.ChatCompletionCreateParams.Function =\n {\n name: OpenAPISpec.getCleanedOperationId(operation, path, method),\n description: operation.description ?? operation.summary ?? \"\",\n parameters: {\n type: \"object\",\n properties: requestArgsSchema,\n // All remaining top-level parameters are required\n required: Object.keys(requestArgsSchema),\n },\n };\n\n openAIFunctions.push(openAIFunction);\n const baseUrl = (spec.baseUrl ?? \"\").endsWith(\"/\")\n ? (spec.baseUrl ?? \"\").slice(0, -1)\n : spec.baseUrl ?? \"\";\n nameToCallMap[openAIFunction.name] = {\n method,\n url: baseUrl + path,\n };\n }\n }\n return {\n openAIFunctions,\n defaultExecutionMethod: async (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>,\n options?: {\n headers?: Record<string, string>;\n params?: Record<string, string>;\n }\n ) => {\n const {\n headers: customHeaders,\n params: customParams,\n ...rest\n } = options ?? {};\n const { method, url } = nameToCallMap[name];\n const requestParams = requestArgs.params ?? {};\n const nonEmptyParams = Object.keys(requestParams).reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (filteredArgs: Record<string, any>, argName) => {\n if (\n requestParams[argName] !== \"\" &&\n requestParams[argName] !== null &&\n requestParams[argName] !== undefined\n ) {\n filteredArgs[argName] = requestParams[argName];\n }\n return filteredArgs;\n },\n {}\n );\n const queryString = new URLSearchParams({\n ...nonEmptyParams,\n ...customParams,\n }).toString();\n const pathParams = requestArgs.path_params;\n const formattedUrl =\n formatURL(url, pathParams) +\n (queryString.length ? `?${queryString}` : \"\");\n const headers: Record<string, string> = {};\n let body;\n if (requestArgs.data !== undefined) {\n let contentType = \"text/plain\";\n if (typeof requestArgs.data !== \"string\") {\n if (typeof requestArgs.data === \"object\") {\n contentType = \"application/json\";\n }\n body = JSON.stringify(requestArgs.data);\n } else {\n body = requestArgs.data;\n }\n headers[\"content-type\"] = contentType;\n }\n const response = await fetch(formattedUrl, {\n ...requestArgs,\n method,\n headers: {\n ...headers,\n ...requestArgs.headers,\n ...customHeaders,\n },\n body,\n ...rest,\n });\n let output;\n if (response.status < 200 || response.status > 299) {\n output = `${response.status}: ${\n response.statusText\n } for ${name} called with ${JSON.stringify(queryString)}`;\n } else {\n output = await response.text();\n }\n return output;\n },\n };\n}\n\n/**\n * Type representing a function for executing simple requests.\n */\ntype SimpleRequestChainExecutionMethod = (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n requestArgs: Record<string, any>\n) => Promise<string>;\n\n/**\n * A chain for making simple API requests.\n */\nclass SimpleRequestChain extends BaseChain {\n static lc_name() {\n return \"SimpleRequestChain\";\n }\n\n private requestMethod: SimpleRequestChainExecutionMethod;\n\n inputKey = \"function\";\n\n outputKey = \"response\";\n\n constructor(config: { requestMethod: SimpleRequestChainExecutionMethod }) {\n super();\n this.requestMethod = config.requestMethod;\n }\n\n get inputKeys() {\n return [this.inputKey];\n }\n\n get outputKeys() {\n return [this.outputKey];\n }\n\n _chainType() {\n return \"simple_request_chain\" as const;\n }\n\n /** @ignore */\n async _call(\n values: ChainValues,\n _runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n const inputKeyValue = values[this.inputKey];\n const methodName = inputKeyValue.name;\n const args = inputKeyValue.arguments;\n const response = await this.requestMethod(methodName, args);\n return { [this.outputKey]: response };\n }\n}\n\n/**\n * Type representing the options for creating an OpenAPI chain.\n */\nexport type OpenAPIChainOptions = {\n llm?: BaseChatModel<BaseFunctionCallOptions>;\n prompt?: BasePromptTemplate;\n requestChain?: BaseChain;\n llmChainInputs?: LLMChainInput;\n headers?: Record<string, string>;\n params?: Record<string, string>;\n verbose?: boolean;\n};\n\n/**\n * Create a chain for querying an API from a OpenAPI spec.\n * @param spec OpenAPISpec or url/file/text string corresponding to one.\n * @param options Custom options passed into the chain\n * @returns OpenAPIChain\n */\nexport async function createOpenAPIChain(\n spec: OpenAPIV3_1.Document | string,\n options: OpenAPIChainOptions = {}\n) {\n let convertedSpec;\n if (typeof spec === \"string\") {\n try {\n convertedSpec = await OpenAPISpec.fromURL(spec);\n } catch {\n try {\n convertedSpec = OpenAPISpec.fromString(spec);\n } catch {\n throw new Error(`Unable to parse spec from source ${spec}.`);\n }\n }\n } else {\n convertedSpec = OpenAPISpec.fromObject(spec);\n }\n const { openAIFunctions, defaultExecutionMethod } =\n convertOpenAPISpecToOpenAIFunctions(convertedSpec);\n if (defaultExecutionMethod === undefined) {\n throw new Error(\n `Could not parse any valid operations from the provided spec.`\n );\n }\n\n if (!options.llm) {\n throw new Error(\"`llm` option is required\");\n }\n\n const {\n llm = options.llm,\n prompt = ChatPromptTemplate.fromMessages([\n HumanMessagePromptTemplate.fromTemplate(\n \"Use the provided API's to respond to this user query:\\n\\n{query}\"\n ),\n ]),\n requestChain = new SimpleRequestChain({\n requestMethod: async (name, args) =>\n defaultExecutionMethod(name, args, {\n headers: options.headers,\n params: options.params,\n }),\n }),\n llmChainInputs = {},\n verbose,\n ...rest\n } = options;\n const formatChain = new LLMChain({\n llm,\n prompt,\n outputParser: new JsonOutputFunctionsParser({ argsOnly: false }),\n outputKey: \"function\",\n llmKwargs: { functions: openAIFunctions },\n ...llmChainInputs,\n });\n return new SequentialChain({\n chains: [formatChain, requestChain],\n outputVariables: [\"response\"],\n inputVariables: formatChain.inputKeys,\n verbose,\n ...rest,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,mBACPA,QAC6B;AAC7B,KAAI,OAAO,UAAU,OACnB,QAAO;AAET,KAAI,OAAO,UAAU,OACnB,QAAO;AAET,KAAI,OAAO,UAAU,OACnB,QAAO;AAET,QAAO;AACR;;;;;;;;AASD,SAAS,UAAUC,KAAaC,YAA4C;CAC1E,MAAM,yBAAyB,CAAC,GAAG,IAAI,SAAS,WAAW,AAAC,EAAC,IAC3D,CAAC,UAAU,MAAM,GAClB;CACD,MAAMC,YAAoC,CAAE;AAC5C,MAAK,MAAM,aAAa,wBAAwB;EAC9C,MAAM,iBAAiB,UAAU,QAAQ,QAAQ,GAAG,CAAC,QAAQ,OAAO,GAAG;EACvE,MAAM,QAAQ,WAAW;EACzB,IAAI;AACJ,MAAI,MAAM,QAAQ,MAAM,CACtB,KAAI,UAAU,WAAW,IAAI,EAAE;GAC7B,MAAM,YAAY,UAAU,SAAS,IAAI,GAAG,MAAM;GAClD,iBAAiB,CAAC,CAAC,EAAE,MAAM,KAAK,UAAU,EAAE;EAC7C,WAAU,UAAU,WAAW,IAAI,EAAE;GACpC,MAAM,YAAY,UAAU,SAAS,IAAI,GAAG,GAAG,eAAe,CAAC,CAAC,GAAG;GACnE,iBAAiB,GAAG,eAAe,CAAC,EAAE,MAAM,KAAK,UAAU,EAAE;EAC9D,OACC,iBAAiB,MAAM,KAAK,IAAI;WAEzB,OAAO,UAAU,UAAU;GACpC,MAAM,cAAc,UAAU,SAAS,IAAI,GAAG,MAAM;GACpD,MA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