@langchain/classic 1.0.14 → 1.0.16
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 +24 -0
- package/dist/agents/chat/outputParser.d.ts +2 -2
- package/dist/agents/chat/outputParser.d.ts.map +1 -1
- package/dist/agents/openai_tools/index.d.cts +2 -2
- package/dist/agents/openai_tools/index.d.cts.map +1 -1
- package/dist/agents/openai_tools/index.d.ts +2 -2
- package/dist/agents/openai_tools/index.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.cts +2 -2
- package/dist/agents/structured_chat/index.d.cts.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.ts +2 -2
- package/dist/agents/tool_calling/index.d.ts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.cts +2 -2
- 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 -5
- package/dist/agents/toolkits/conversational_retrieval/tool.d.cts.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.d.ts +1 -5
- package/dist/agents/toolkits/conversational_retrieval/tool.d.ts.map +1 -1
- package/dist/chains/base.cjs.map +1 -1
- package/dist/chains/base.js.map +1 -1
- package/dist/chains/llm_chain.cjs.map +1 -1
- package/dist/chains/llm_chain.js.map +1 -1
- package/dist/chains/openai_moderation.cjs.map +1 -1
- package/dist/chains/openai_moderation.js.map +1 -1
- package/dist/chat_models/universal.cjs +12 -6
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts +4 -2
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +4 -2
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +12 -6
- package/dist/chat_models/universal.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/criteria/criteria.d.cts +3 -3
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/experimental/autogpt/prompt.cjs +1 -1
- package/dist/experimental/autogpt/prompt.cjs.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/experimental/autogpt/prompt.js +1 -1
- package/dist/experimental/autogpt/prompt.js.map +1 -1
- package/dist/experimental/babyagi/agent.cjs.map +1 -1
- package/dist/experimental/babyagi/agent.js.map +1 -1
- package/dist/experimental/prompts/custom_format.d.ts.map +1 -1
- package/dist/experimental/prompts/handlebars.d.ts.map +1 -1
- package/dist/hub/node.cjs +27 -1
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.d.cts +10 -1
- package/dist/hub/node.d.cts.map +1 -1
- package/dist/hub/node.d.ts +10 -1
- package/dist/hub/node.d.ts.map +1 -1
- package/dist/hub/node.js +27 -2
- package/dist/hub/node.js.map +1 -1
- package/dist/memory/buffer_token_memory.cjs.map +1 -1
- package/dist/memory/buffer_token_memory.js.map +1 -1
- package/dist/memory/summary.cjs.map +1 -1
- package/dist/memory/summary.js.map +1 -1
- package/dist/memory/summary_buffer.cjs.map +1 -1
- package/dist/memory/summary_buffer.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/retrievers/self_query/index.cjs.map +1 -1
- package/dist/retrievers/self_query/index.js.map +1 -1
- package/dist/retrievers/time_weighted.cjs.map +1 -1
- package/dist/retrievers/time_weighted.js.map +1 -1
- package/dist/smith/runner_utils.cjs.map +1 -1
- package/dist/smith/runner_utils.js.map +1 -1
- package/package.json +19 -19
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ObjectTool } from "./schema.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as _langchain_core_messages0 from "@langchain/core/messages";
|
|
3
3
|
import { BaseMessage } from "@langchain/core/messages";
|
|
4
4
|
import { PartialValues } from "@langchain/core/utils/types";
|
|
5
5
|
import { BaseChatPromptTemplate, SerializedBasePromptTemplate } from "@langchain/core/prompts";
|
|
@@ -54,7 +54,7 @@ declare class AutoGPTPrompt extends BaseChatPromptTemplate implements AutoGPTPro
|
|
|
54
54
|
memory: VectorStoreRetrieverInterface;
|
|
55
55
|
messages: BaseMessage[];
|
|
56
56
|
user_input: string;
|
|
57
|
-
}): Promise<BaseMessage<
|
|
57
|
+
}): Promise<BaseMessage<_langchain_core_messages0.MessageStructure<_langchain_core_messages0.MessageToolSet>, _langchain_core_messages0.MessageType>[]>;
|
|
58
58
|
/**
|
|
59
59
|
* This method is not implemented in the AutoGPTPrompt class and will
|
|
60
60
|
* throw an error if called.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.d.cts","names":["VectorStoreRetrieverInterface","BaseChatPromptTemplate","SerializedBasePromptTemplate","BaseMessage","PartialValues","ObjectTool","AutoGPTPromptInput","Promise","AutoGPTPrompt","goals","memory","previousMessages","user_input","
|
|
1
|
+
{"version":3,"file":"prompt.d.cts","names":["VectorStoreRetrieverInterface","BaseChatPromptTemplate","SerializedBasePromptTemplate","BaseMessage","PartialValues","ObjectTool","AutoGPTPromptInput","Promise","AutoGPTPrompt","goals","memory","previousMessages","user_input","_langchain_core_messages0","MessageToolSet","MessageStructure","MessageType"],"sources":["../../../src/experimental/autogpt/prompt.d.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport { BaseChatPromptTemplate, SerializedBasePromptTemplate } from \"@langchain/core/prompts\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { PartialValues } from \"@langchain/core/utils/types\";\nimport { ObjectTool } from \"./schema.js\";\n/**\n * Interface for the input parameters of the AutoGPTPrompt class.\n */\nexport interface AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit?: number;\n}\n/**\n * Class used to generate prompts for the AutoGPT model. It takes into\n * account the AI's name, role, tools, token counter, and send token\n * limit. The class also handles the formatting of messages and the\n * construction of the full prompt.\n */\nexport declare class AutoGPTPrompt extends BaseChatPromptTemplate implements AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit: number;\n constructor(fields: AutoGPTPromptInput);\n _getPromptType(): \"autogpt\";\n /**\n * Constructs the full prompt based on the provided goals.\n * @param goals An array of goals.\n * @returns The full prompt as a string.\n */\n constructFullPrompt(goals: string[]): string;\n /**\n * Formats the messages based on the provided parameters.\n * @param goals An array of goals.\n * @param memory A VectorStoreRetriever instance.\n * @param messages An array of previous messages.\n * @param user_input The user's input.\n * @returns An array of formatted messages.\n */\n formatMessages({ goals, memory, messages: previousMessages, user_input }: {\n goals: string[];\n memory: VectorStoreRetrieverInterface;\n messages: BaseMessage[];\n user_input: string;\n }): Promise<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[]>;\n /**\n * This method is not implemented in the AutoGPTPrompt class and will\n * throw an error if called.\n * @param _values Partial values.\n * @returns Throws an error.\n */\n partial(_values: PartialValues): Promise<BaseChatPromptTemplate>;\n serialize(): SerializedBasePromptTemplate;\n}\n//# sourceMappingURL=prompt.d.ts.map"],"mappings":";;;;;;;;;;;AAQiBM,UAAAA,kBAAAA,CAAkB;EAadE,MAAAA,EAAAA,MAAAA;EAGVH,MAAAA,EAAAA,MAAAA;EACyBE,KAAAA,EAdzBF,UAcyBE,EAAAA;EAEZD,YAAAA,EAAAA,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,GAfYC,OAeZD,CAAAA,MAAAA,CAAAA;EAgBHG,cAAAA,CAAAA,EAAAA,MAAAA;;;;;;;;AAK0DI,cA3B1DL,aAAAA,SAAsBP,sBAAAA,YAAkCK,kBA2B0FU,CAAAA;EAAvJb,MAAAA,EAAAA,MAAAA;EAARI,MAAAA,EAAAA,MAAAA;EAOaH,KAAAA,EA/BVC,UA+BUD,EAAAA;EAAwBH,YAAAA,EAAAA,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,GA9BTM,OA8BSN,CAAAA,MAAAA,CAAAA;EAARM,cAAAA,EAAAA,MAAAA;EACpBL,WAAAA,CAAAA,MAAAA,EA7BOI,kBA6BPJ;EAnC0BD,cAAAA,CAAAA,CAAAA,EAAAA,SAAAA;EAAkCK;AAAkB;;;;;;;;;;;;;;;;cAsBjDK;;;;YAE9BX;cACEG;;MAEVI,QAAQJ,YAAiHU,yBAAAA,CAAlEE,iBAFlCF,yBAAAA,CAEsFC,cAAAA,GAApCD,yBAAAA,CAAwFG,WAAAA;;;;;;;mBAOlJZ,gBAAgBG,QAAQN;eAC5BC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ObjectTool } from "./schema.js";
|
|
2
2
|
import { BaseChatPromptTemplate, SerializedBasePromptTemplate } from "@langchain/core/prompts";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _langchain_core_messages0 from "@langchain/core/messages";
|
|
4
4
|
import { BaseMessage } from "@langchain/core/messages";
|
|
5
5
|
import { PartialValues } from "@langchain/core/utils/types";
|
|
6
6
|
import { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores";
|
|
@@ -54,7 +54,7 @@ declare class AutoGPTPrompt extends BaseChatPromptTemplate implements AutoGPTPro
|
|
|
54
54
|
memory: VectorStoreRetrieverInterface;
|
|
55
55
|
messages: BaseMessage[];
|
|
56
56
|
user_input: string;
|
|
57
|
-
}): Promise<BaseMessage<
|
|
57
|
+
}): Promise<BaseMessage<_langchain_core_messages0.MessageStructure<_langchain_core_messages0.MessageToolSet>, _langchain_core_messages0.MessageType>[]>;
|
|
58
58
|
/**
|
|
59
59
|
* This method is not implemented in the AutoGPTPrompt class and will
|
|
60
60
|
* throw an error if called.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.d.ts","names":["VectorStoreRetrieverInterface","BaseChatPromptTemplate","SerializedBasePromptTemplate","BaseMessage","PartialValues","ObjectTool","AutoGPTPromptInput","Promise","AutoGPTPrompt","goals","memory","previousMessages","user_input","
|
|
1
|
+
{"version":3,"file":"prompt.d.ts","names":["VectorStoreRetrieverInterface","BaseChatPromptTemplate","SerializedBasePromptTemplate","BaseMessage","PartialValues","ObjectTool","AutoGPTPromptInput","Promise","AutoGPTPrompt","goals","memory","previousMessages","user_input","_langchain_core_messages0","MessageToolSet","MessageStructure","MessageType"],"sources":["../../../src/experimental/autogpt/prompt.d.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport { BaseChatPromptTemplate, SerializedBasePromptTemplate } from \"@langchain/core/prompts\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { PartialValues } from \"@langchain/core/utils/types\";\nimport { ObjectTool } from \"./schema.js\";\n/**\n * Interface for the input parameters of the AutoGPTPrompt class.\n */\nexport interface AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit?: number;\n}\n/**\n * Class used to generate prompts for the AutoGPT model. It takes into\n * account the AI's name, role, tools, token counter, and send token\n * limit. The class also handles the formatting of messages and the\n * construction of the full prompt.\n */\nexport declare class AutoGPTPrompt extends BaseChatPromptTemplate implements AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit: number;\n constructor(fields: AutoGPTPromptInput);\n _getPromptType(): \"autogpt\";\n /**\n * Constructs the full prompt based on the provided goals.\n * @param goals An array of goals.\n * @returns The full prompt as a string.\n */\n constructFullPrompt(goals: string[]): string;\n /**\n * Formats the messages based on the provided parameters.\n * @param goals An array of goals.\n * @param memory A VectorStoreRetriever instance.\n * @param messages An array of previous messages.\n * @param user_input The user's input.\n * @returns An array of formatted messages.\n */\n formatMessages({ goals, memory, messages: previousMessages, user_input }: {\n goals: string[];\n memory: VectorStoreRetrieverInterface;\n messages: BaseMessage[];\n user_input: string;\n }): Promise<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[]>;\n /**\n * This method is not implemented in the AutoGPTPrompt class and will\n * throw an error if called.\n * @param _values Partial values.\n * @returns Throws an error.\n */\n partial(_values: PartialValues): Promise<BaseChatPromptTemplate>;\n serialize(): SerializedBasePromptTemplate;\n}\n//# sourceMappingURL=prompt.d.ts.map"],"mappings":";;;;;;;;;;;AAQiBM,UAAAA,kBAAAA,CAAkB;EAadE,MAAAA,EAAAA,MAAAA;EAGVH,MAAAA,EAAAA,MAAAA;EACyBE,KAAAA,EAdzBF,UAcyBE,EAAAA;EAEZD,YAAAA,EAAAA,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,GAfYC,OAeZD,CAAAA,MAAAA,CAAAA;EAgBHG,cAAAA,CAAAA,EAAAA,MAAAA;;;;;;;;AAK0DI,cA3B1DL,aAAAA,SAAsBP,sBAAAA,YAAkCK,kBA2B0FU,CAAAA;EAAvJb,MAAAA,EAAAA,MAAAA;EAARI,MAAAA,EAAAA,MAAAA;EAOaH,KAAAA,EA/BVC,UA+BUD,EAAAA;EAAwBH,YAAAA,EAAAA,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,GA9BTM,OA8BSN,CAAAA,MAAAA,CAAAA;EAARM,cAAAA,EAAAA,MAAAA;EACpBL,WAAAA,CAAAA,MAAAA,EA7BOI,kBA6BPJ;EAnC0BD,cAAAA,CAAAA,CAAAA,EAAAA,SAAAA;EAAkCK;AAAkB;;;;;;;;;;;;;;;;cAsBjDK;;;;YAE9BX;cACEG;;MAEVI,QAAQJ,YAAiHU,yBAAAA,CAAlEE,iBAFlCF,yBAAAA,CAEsFC,cAAAA,GAApCD,yBAAAA,CAAwFG,WAAAA;;;;;;;mBAOlJZ,gBAAgBG,QAAQN;eAC5BC"}
|
|
@@ -59,7 +59,7 @@ var AutoGPTPrompt = class extends BaseChatPromptTemplate {
|
|
|
59
59
|
*/
|
|
60
60
|
async formatMessages({ goals, memory, messages: previousMessages, user_input }) {
|
|
61
61
|
const basePrompt = new SystemMessage(this.constructFullPrompt(goals));
|
|
62
|
-
const timePrompt = new SystemMessage(`The current time and date is ${(/* @__PURE__ */ new Date()).toLocaleString()}`);
|
|
62
|
+
const timePrompt = new SystemMessage(`The current time and date is ${(/* @__PURE__ */ new Date()).toLocaleString("en-US")}`);
|
|
63
63
|
if (typeof basePrompt.content !== "string" || typeof timePrompt.content !== "string") throw new Error("Non-string message content is not supported.");
|
|
64
64
|
const usedTokens = await this.tokenCounter(basePrompt.content) + await this.tokenCounter(timePrompt.content);
|
|
65
65
|
const relevantDocs = await memory.invoke(JSON.stringify(previousMessages.slice(-10)));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","names":["fields: AutoGPTPromptInput","goals: string[]","d: { pageContent: string }","acc: Promise<number>","doc: string","historicalMessages: BaseMessage[]","messages: BaseMessage[]","_values: PartialValues"],"sources":["../../../src/experimental/autogpt/prompt.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport {\n BaseChatPromptTemplate,\n SerializedBasePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport {\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { PartialValues } from \"@langchain/core/utils/types\";\nimport { getPrompt } from \"./prompt_generator.js\";\nimport { ObjectTool } from \"./schema.js\";\n\n/**\n * Interface for the input parameters of the AutoGPTPrompt class.\n */\nexport interface AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit?: number;\n}\n\n/**\n * Class used to generate prompts for the AutoGPT model. It takes into\n * account the AI's name, role, tools, token counter, and send token\n * limit. The class also handles the formatting of messages and the\n * construction of the full prompt.\n */\nexport class AutoGPTPrompt\n extends BaseChatPromptTemplate\n implements AutoGPTPromptInput\n{\n aiName: string;\n\n aiRole: string;\n\n tools: ObjectTool[];\n\n tokenCounter: (text: string) => Promise<number>;\n\n sendTokenLimit: number;\n\n constructor(fields: AutoGPTPromptInput) {\n super({ inputVariables: [\"goals\", \"memory\", \"messages\", \"user_input\"] });\n this.aiName = fields.aiName;\n this.aiRole = fields.aiRole;\n this.tools = fields.tools;\n this.tokenCounter = fields.tokenCounter;\n this.sendTokenLimit = fields.sendTokenLimit || 4196;\n }\n\n _getPromptType() {\n return \"autogpt\" as const;\n }\n\n /**\n * Constructs the full prompt based on the provided goals.\n * @param goals An array of goals.\n * @returns The full prompt as a string.\n */\n constructFullPrompt(goals: string[]): string {\n const promptStart = `Your decisions must always be made independently\n without seeking user assistance. Play to your strengths\n as an LLM and pursue simple strategies with no legal complications.\n If you have completed all your tasks,\n make sure to use the \"finish\" command.`;\n\n let fullPrompt = `You are ${this.aiName}, ${this.aiRole}\\n${promptStart}\\n\\nGOALS:\\n\\n`;\n goals.forEach((goal, index) => {\n fullPrompt += `${index + 1}. ${goal}\\n`;\n });\n\n fullPrompt += `\\n\\n${getPrompt(this.tools)}`;\n return fullPrompt;\n }\n\n /**\n * Formats the messages based on the provided parameters.\n * @param goals An array of goals.\n * @param memory A VectorStoreRetriever instance.\n * @param messages An array of previous messages.\n * @param user_input The user's input.\n * @returns An array of formatted messages.\n */\n async formatMessages({\n goals,\n memory,\n messages: previousMessages,\n user_input,\n }: {\n goals: string[];\n memory: VectorStoreRetrieverInterface;\n messages: BaseMessage[];\n user_input: string;\n }) {\n const basePrompt = new SystemMessage(this.constructFullPrompt(goals));\n const timePrompt = new SystemMessage(\n `The current time and date is ${new Date().toLocaleString()}`\n );\n if (\n typeof basePrompt.content !== \"string\" ||\n typeof timePrompt.content !== \"string\"\n ) {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const usedTokens =\n (await this.tokenCounter(basePrompt.content)) +\n (await this.tokenCounter(timePrompt.content));\n const relevantDocs = await memory.invoke(\n JSON.stringify(previousMessages.slice(-10))\n );\n const relevantMemory = relevantDocs.map(\n (d: { pageContent: string }) => d.pageContent\n );\n let relevantMemoryTokens = await relevantMemory.reduce(\n async (acc: Promise<number>, doc: string) =>\n (await acc) + (await this.tokenCounter(doc)),\n Promise.resolve(0)\n );\n\n while (usedTokens + relevantMemoryTokens > 2500) {\n relevantMemory.pop();\n relevantMemoryTokens = await relevantMemory.reduce(\n async (acc: Promise<number>, doc: string) =>\n (await acc) + (await this.tokenCounter(doc)),\n Promise.resolve(0)\n );\n }\n\n const contentFormat = `This reminds you of these events from your past:\\n${relevantMemory.join(\n \"\\n\"\n )}\\n\\n`;\n const memoryMessage = new SystemMessage(contentFormat);\n if (typeof memoryMessage.content !== \"string\") {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const usedTokensWithMemory =\n usedTokens + (await this.tokenCounter(memoryMessage.content));\n const historicalMessages: BaseMessage[] = [];\n\n for (const message of previousMessages.slice(-10).reverse()) {\n if (typeof message.content !== \"string\") {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const messageTokens = await this.tokenCounter(message.content);\n if (usedTokensWithMemory + messageTokens > this.sendTokenLimit - 1000) {\n break;\n }\n historicalMessages.unshift(message);\n }\n\n const inputMessage = new HumanMessage(user_input);\n const messages: BaseMessage[] = [\n basePrompt,\n timePrompt,\n memoryMessage,\n ...historicalMessages,\n inputMessage,\n ];\n return messages;\n }\n\n /**\n * This method is not implemented in the AutoGPTPrompt class and will\n * throw an error if called.\n * @param _values Partial values.\n * @returns Throws an error.\n */\n async partial(_values: PartialValues): Promise<BaseChatPromptTemplate> {\n throw new Error(\"Method not implemented.\");\n }\n\n serialize(): SerializedBasePromptTemplate {\n throw new Error(\"Method not implemented.\");\n }\n}\n"],"mappings":";;;;;;;;;;;AA+BA,IAAa,gBAAb,cACU,uBAEV;CACE;CAEA;CAEA;CAEA;CAEA;CAEA,YAAYA,QAA4B;EACtC,MAAM,EAAE,gBAAgB;GAAC;GAAS;GAAU;GAAY;EAAa,EAAE,EAAC;EACxE,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS,OAAO;EACrB,KAAK,QAAQ,OAAO;EACpB,KAAK,eAAe,OAAO;EAC3B,KAAK,iBAAiB,OAAO,kBAAkB;CAChD;CAED,iBAAiB;AACf,SAAO;CACR;;;;;;CAOD,oBAAoBC,OAAyB;EAC3C,MAAM,cAAc,CAAC;;;;kDAIyB,CAAC;EAE/C,IAAI,aAAa,CAAC,QAAQ,EAAE,KAAK,OAAO,EAAE,EAAE,KAAK,OAAO,EAAE,EAAE,YAAY,cAAc,CAAC;EACvF,MAAM,QAAQ,CAAC,MAAM,UAAU;GAC7B,cAAc,GAAG,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;EACxC,EAAC;EAEF,cAAc,CAAC,IAAI,EAAE,UAAU,KAAK,MAAM,EAAE;AAC5C,SAAO;CACR;;;;;;;;;CAUD,MAAM,eAAe,EACnB,OACA,QACA,UAAU,kBACV,YAMD,EAAE;EACD,MAAM,aAAa,IAAI,cAAc,KAAK,oBAAoB,MAAM;EACpE,MAAM,aAAa,IAAI,cACrB,CAAC,6BAA6B,mBAAE,IAAI,QAAO,
|
|
1
|
+
{"version":3,"file":"prompt.js","names":["fields: AutoGPTPromptInput","goals: string[]","d: { pageContent: string }","acc: Promise<number>","doc: string","historicalMessages: BaseMessage[]","messages: BaseMessage[]","_values: PartialValues"],"sources":["../../../src/experimental/autogpt/prompt.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport {\n BaseChatPromptTemplate,\n SerializedBasePromptTemplate,\n} from \"@langchain/core/prompts\";\nimport {\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { PartialValues } from \"@langchain/core/utils/types\";\nimport { getPrompt } from \"./prompt_generator.js\";\nimport { ObjectTool } from \"./schema.js\";\n\n/**\n * Interface for the input parameters of the AutoGPTPrompt class.\n */\nexport interface AutoGPTPromptInput {\n aiName: string;\n aiRole: string;\n tools: ObjectTool[];\n tokenCounter: (text: string) => Promise<number>;\n sendTokenLimit?: number;\n}\n\n/**\n * Class used to generate prompts for the AutoGPT model. It takes into\n * account the AI's name, role, tools, token counter, and send token\n * limit. The class also handles the formatting of messages and the\n * construction of the full prompt.\n */\nexport class AutoGPTPrompt\n extends BaseChatPromptTemplate\n implements AutoGPTPromptInput\n{\n aiName: string;\n\n aiRole: string;\n\n tools: ObjectTool[];\n\n tokenCounter: (text: string) => Promise<number>;\n\n sendTokenLimit: number;\n\n constructor(fields: AutoGPTPromptInput) {\n super({ inputVariables: [\"goals\", \"memory\", \"messages\", \"user_input\"] });\n this.aiName = fields.aiName;\n this.aiRole = fields.aiRole;\n this.tools = fields.tools;\n this.tokenCounter = fields.tokenCounter;\n this.sendTokenLimit = fields.sendTokenLimit || 4196;\n }\n\n _getPromptType() {\n return \"autogpt\" as const;\n }\n\n /**\n * Constructs the full prompt based on the provided goals.\n * @param goals An array of goals.\n * @returns The full prompt as a string.\n */\n constructFullPrompt(goals: string[]): string {\n const promptStart = `Your decisions must always be made independently\n without seeking user assistance. Play to your strengths\n as an LLM and pursue simple strategies with no legal complications.\n If you have completed all your tasks,\n make sure to use the \"finish\" command.`;\n\n let fullPrompt = `You are ${this.aiName}, ${this.aiRole}\\n${promptStart}\\n\\nGOALS:\\n\\n`;\n goals.forEach((goal, index) => {\n fullPrompt += `${index + 1}. ${goal}\\n`;\n });\n\n fullPrompt += `\\n\\n${getPrompt(this.tools)}`;\n return fullPrompt;\n }\n\n /**\n * Formats the messages based on the provided parameters.\n * @param goals An array of goals.\n * @param memory A VectorStoreRetriever instance.\n * @param messages An array of previous messages.\n * @param user_input The user's input.\n * @returns An array of formatted messages.\n */\n async formatMessages({\n goals,\n memory,\n messages: previousMessages,\n user_input,\n }: {\n goals: string[];\n memory: VectorStoreRetrieverInterface;\n messages: BaseMessage[];\n user_input: string;\n }) {\n const basePrompt = new SystemMessage(this.constructFullPrompt(goals));\n const timePrompt = new SystemMessage(\n `The current time and date is ${new Date().toLocaleString(\"en-US\")}`\n );\n if (\n typeof basePrompt.content !== \"string\" ||\n typeof timePrompt.content !== \"string\"\n ) {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const usedTokens =\n (await this.tokenCounter(basePrompt.content)) +\n (await this.tokenCounter(timePrompt.content));\n const relevantDocs = await memory.invoke(\n JSON.stringify(previousMessages.slice(-10))\n );\n const relevantMemory = relevantDocs.map(\n (d: { pageContent: string }) => d.pageContent\n );\n let relevantMemoryTokens = await relevantMemory.reduce(\n async (acc: Promise<number>, doc: string) =>\n (await acc) + (await this.tokenCounter(doc)),\n Promise.resolve(0)\n );\n\n while (usedTokens + relevantMemoryTokens > 2500) {\n relevantMemory.pop();\n relevantMemoryTokens = await relevantMemory.reduce(\n async (acc: Promise<number>, doc: string) =>\n (await acc) + (await this.tokenCounter(doc)),\n Promise.resolve(0)\n );\n }\n\n const contentFormat = `This reminds you of these events from your past:\\n${relevantMemory.join(\n \"\\n\"\n )}\\n\\n`;\n const memoryMessage = new SystemMessage(contentFormat);\n if (typeof memoryMessage.content !== \"string\") {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const usedTokensWithMemory =\n usedTokens + (await this.tokenCounter(memoryMessage.content));\n const historicalMessages: BaseMessage[] = [];\n\n for (const message of previousMessages.slice(-10).reverse()) {\n if (typeof message.content !== \"string\") {\n throw new Error(\"Non-string message content is not supported.\");\n }\n const messageTokens = await this.tokenCounter(message.content);\n if (usedTokensWithMemory + messageTokens > this.sendTokenLimit - 1000) {\n break;\n }\n historicalMessages.unshift(message);\n }\n\n const inputMessage = new HumanMessage(user_input);\n const messages: BaseMessage[] = [\n basePrompt,\n timePrompt,\n memoryMessage,\n ...historicalMessages,\n inputMessage,\n ];\n return messages;\n }\n\n /**\n * This method is not implemented in the AutoGPTPrompt class and will\n * throw an error if called.\n * @param _values Partial values.\n * @returns Throws an error.\n */\n async partial(_values: PartialValues): Promise<BaseChatPromptTemplate> {\n throw new Error(\"Method not implemented.\");\n }\n\n serialize(): SerializedBasePromptTemplate {\n throw new Error(\"Method not implemented.\");\n }\n}\n"],"mappings":";;;;;;;;;;;AA+BA,IAAa,gBAAb,cACU,uBAEV;CACE;CAEA;CAEA;CAEA;CAEA;CAEA,YAAYA,QAA4B;EACtC,MAAM,EAAE,gBAAgB;GAAC;GAAS;GAAU;GAAY;EAAa,EAAE,EAAC;EACxE,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS,OAAO;EACrB,KAAK,QAAQ,OAAO;EACpB,KAAK,eAAe,OAAO;EAC3B,KAAK,iBAAiB,OAAO,kBAAkB;CAChD;CAED,iBAAiB;AACf,SAAO;CACR;;;;;;CAOD,oBAAoBC,OAAyB;EAC3C,MAAM,cAAc,CAAC;;;;kDAIyB,CAAC;EAE/C,IAAI,aAAa,CAAC,QAAQ,EAAE,KAAK,OAAO,EAAE,EAAE,KAAK,OAAO,EAAE,EAAE,YAAY,cAAc,CAAC;EACvF,MAAM,QAAQ,CAAC,MAAM,UAAU;GAC7B,cAAc,GAAG,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;EACxC,EAAC;EAEF,cAAc,CAAC,IAAI,EAAE,UAAU,KAAK,MAAM,EAAE;AAC5C,SAAO;CACR;;;;;;;;;CAUD,MAAM,e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uBAAuB,gBAAgB,KAAK,iBAAiB,IAC/D;GAEF,mBAAmB,QAAQ,QAAQ;EACpC;EAED,MAAM,eAAe,IAAI,aAAa;EACtC,MAAMC,WAA0B;GAC9B;GACA;GACA;GACA,GAAG;GACH;EACD;AACD,SAAO;CACR;;;;;;;CAQD,MAAM,QAAQC,SAAyD;AACrE,QAAM,IAAI,MAAM;CACjB;CAED,YAA0C;AACxC,QAAM,IAAI,MAAM;CACjB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.cjs","names":["BaseChain","task: Task","result: string","task_description: string","objective: string","runManager?: CallbackManagerForChainRun","thisTaskID: number","query: string","task: string","Document","TaskCreationChain","TaskPrioritizationChain","TaskExecutionChain"],"sources":["../../../src/experimental/babyagi/agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { VectorStoreInterface } from \"@langchain/core/vectorstores\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { BaseChain, ChainInputs } from \"../../chains/base.js\";\nimport { SerializedBaseChain } from \"../../chains/serde.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { TaskCreationChain } from \"./task_creation.js\";\nimport { TaskExecutionChain } from \"./task_execution.js\";\nimport { TaskPrioritizationChain } from \"./task_prioritization.js\";\n\n/**\n * Interface defining the structure of a task. A task has a `taskID` and a\n * `taskName`.\n */\nexport interface Task {\n taskID: string;\n taskName: string;\n}\n\n/**\n * Interface defining the structure of the inputs for the `BabyAGI` class.\n * It extends the `ChainInputs` interface, omitting the 'memory' and\n * 'callbackManager' properties, and adds properties specific to\n * `BabyAGI`.\n */\nexport interface BabyAGIInputs\n extends Omit<ChainInputs, \"memory\" | \"callbackManager\"> {\n creationChain: BaseChain;\n prioritizationChain: BaseChain;\n executionChain: BaseChain;\n vectorstore: VectorStoreInterface;\n maxIterations?: number;\n}\n\n/**\n * Class responsible for managing tasks, including their creation,\n * prioritization, and execution. It uses three chains for these\n * operations: `creationChain`, `prioritizationChain`, and\n * `executionChain`.\n * @example\n * ```typescript\n * const babyAGI = BabyAGI.fromLLM({\n * llm: new OpenAI({ temperature: 0 }),\n * vectorstore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * maxIterations: 3,\n * });\n *\n * const result = await babyAGI.call({\n * objective: \"Write a weather report for SF today\",\n * });\n * ```\n */\nexport class BabyAGI extends BaseChain implements BabyAGIInputs {\n static lc_name() {\n return \"BabyAGI\";\n }\n\n taskList: Task[];\n\n creationChain: BaseChain;\n\n prioritizationChain: BaseChain;\n\n executionChain: BaseChain;\n\n taskIDCounter: number;\n\n vectorstore: VectorStoreInterface;\n\n maxIterations: number;\n\n constructor({\n creationChain,\n prioritizationChain,\n executionChain,\n vectorstore,\n maxIterations = 100,\n verbose,\n callbacks,\n }: BabyAGIInputs) {\n super(undefined, verbose, callbacks);\n this.taskList = [];\n this.creationChain = creationChain;\n this.prioritizationChain = prioritizationChain;\n this.executionChain = executionChain;\n this.taskIDCounter = 1;\n this.vectorstore = vectorstore;\n this.maxIterations = maxIterations;\n }\n\n _chainType() {\n return \"BabyAGI\" as const;\n }\n\n get inputKeys() {\n return [\"objective\", \"firstTask\"];\n }\n\n get outputKeys() {\n return [];\n }\n\n /**\n * Adds a task to the task list.\n * @param task The task to be added.\n * @returns Promise resolving to void.\n */\n async addTask(task: Task) {\n this.taskList.push(task);\n }\n\n /**\n * Prints the current task list to the console.\n * @returns void\n */\n printTaskList() {\n console.log(\"\\x1b[95m\\x1b[1m\\n*****TASK LIST*****\\n\\x1b[0m\\x1b[0m\");\n for (const t of this.taskList) {\n console.log(`${t.taskID}: ${t.taskName}`);\n }\n }\n\n /**\n * Prints the next task to the console.\n * @param task The next task to be printed.\n * @returns void\n */\n printNextTask(task: Task) {\n console.log(\"\\x1b[92m\\x1b[1m\\n*****NEXT TASK*****\\n\\x1b[0m\\x1b[0m\");\n console.log(`${task.taskID}: ${task.taskName}`);\n }\n\n /**\n * Prints the result of a task to the console.\n * @param result The result of the task.\n * @returns void\n */\n printTaskResult(result: string) {\n console.log(\"\\x1b[93m\\x1b[1m\\n*****TASK RESULT*****\\n\\x1b[0m\\x1b[0m\");\n console.log(result.trim());\n }\n\n /**\n * Generates the next tasks based on the result of the previous task, the\n * task description, and the objective.\n * @param result The result of the previous task.\n * @param task_description The description of the task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of tasks without taskID.\n */\n async getNextTasks(\n result: string,\n task_description: string,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<Optional<Task, \"taskID\">[]> {\n const taskNames = this.taskList.map((t) => t.taskName);\n const incomplete_tasks = taskNames.join(\", \");\n const { [this.creationChain.outputKeys[0]]: text } =\n await this.creationChain.call(\n {\n result,\n task_description,\n incomplete_tasks,\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).split(\"\\n\");\n return newTasks\n .filter((taskName) => taskName.trim())\n .map((taskName) => ({ taskName }));\n }\n\n /**\n * Prioritizes the tasks based on the current task ID and the objective.\n * @param thisTaskID The ID of the current task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of prioritized tasks.\n */\n async prioritizeTasks(\n thisTaskID: number,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const taskNames = this.taskList.map((t) => t.taskName);\n const nextTaskID = thisTaskID + 1;\n const { [this.prioritizationChain.outputKeys[0]]: text } =\n await this.prioritizationChain.call(\n {\n task_names: taskNames.join(\", \"),\n next_task_id: String(nextTaskID),\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).trim().split(\"\\n\");\n const prioritizedTaskList = [];\n for (const taskString of newTasks) {\n const taskParts = taskString.trim().split(\".\", 2);\n if (taskParts.length === 2) {\n const taskID = taskParts[0].trim();\n const taskName = taskParts[1].trim();\n prioritizedTaskList.push({ taskID, taskName });\n }\n }\n return prioritizedTaskList;\n }\n\n /**\n * Retrieves the top tasks that are most similar to the given query.\n * @param query The query to search for.\n * @param k The number of top tasks to retrieve.\n * @returns Promise resolving to an array of top tasks.\n */\n async getTopTasks(query: string, k = 5) {\n const results = await this.vectorstore.similaritySearch(query, k);\n if (!results) {\n return [];\n }\n return results.map((item) => String(item.metadata.task));\n }\n\n /**\n * Executes a task based on the objective and the task description.\n * @param objective The objective of the task.\n * @param task The task to be executed.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to the result of the task execution as a string.\n */\n async executeTask(\n objective: string,\n task: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const context = await this.getTopTasks(objective);\n const { [this.executionChain.outputKeys[0]]: text } =\n await this.executionChain.call(\n {\n objective,\n context: context.join(\"\\n\"),\n task,\n },\n runManager?.getChild()\n );\n return text as string;\n }\n\n async _call(\n { objective, firstTask = \"Make a todo list\" }: ChainValues,\n runManager?: CallbackManagerForChainRun\n ) {\n this.taskList = [];\n this.taskIDCounter = 1;\n await this.addTask({ taskID: \"1\", taskName: firstTask });\n\n let numIters = 0;\n while (numIters < this.maxIterations && this.taskList.length > 0) {\n this.printTaskList();\n\n const task = this.taskList.shift()!;\n this.printNextTask(task);\n\n const result = await this.executeTask(\n objective,\n task.taskName,\n runManager\n );\n const thisTaskID = parseInt(task.taskID, 10);\n this.printTaskResult(result);\n\n await this.vectorstore.addDocuments([\n new Document({\n pageContent: result,\n metadata: { task: task.taskName },\n }),\n ]);\n\n const newTasks = await this.getNextTasks(\n result,\n task.taskName,\n objective,\n runManager\n );\n for (const newTask of newTasks) {\n this.taskIDCounter += 1;\n newTask.taskID = this.taskIDCounter.toFixed();\n await this.addTask(newTask as Task);\n }\n this.taskList = await this.prioritizeTasks(\n thisTaskID,\n objective,\n runManager\n );\n\n numIters += 1;\n }\n return {};\n }\n\n serialize(): SerializedBaseChain {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Static method to create a new BabyAGI instance from a\n * BaseLanguageModel.\n * @param llm BaseLanguageModel instance used to generate a new BabyAGI instance.\n * @param vectorstore VectorStore instance used to store and retrieve vectors.\n * @param executionChain Optional BaseChain instance used to execute tasks.\n * @param verbose Optional boolean indicating whether to log verbose output.\n * @param callbacks Optional callbacks to be used during the execution of tasks.\n * @param rest Optional additional parameters.\n * @returns A new instance of BabyAGI.\n */\n static fromLLM({\n llm,\n vectorstore,\n executionChain,\n verbose,\n callbacks,\n ...rest\n }: Optional<\n BabyAGIInputs,\n \"executionChain\" | \"creationChain\" | \"prioritizationChain\"\n > & { llm: BaseLanguageModelInterface }) {\n const creationChain = TaskCreationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n const prioritizationChain = TaskPrioritizationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n return new BabyAGI({\n creationChain,\n prioritizationChain,\n executionChain:\n executionChain ||\n TaskExecutionChain.fromLLM({ llm, verbose, callbacks }),\n vectorstore,\n verbose,\n callbacks,\n ...rest,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,UAAb,MAAa,gBAAgBA,uBAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,WACc,EAAE;EAChB,MAAM,QAAW,SAAS,UAAU;EACpC,KAAK,WAAW,CAAE;EAClB,KAAK,gBAAgB;EACrB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,gBAAgB;CACtB;CAED,aAAa;AACX,SAAO;CACR;CAED,IAAI,YAAY;AACd,SAAO,CAAC,aAAa,WAAY;CAClC;CAED,IAAI,aAAa;AACf,SAAO,CAAE;CACV;;;;;;CAOD,MAAM,QAAQC,MAAY;EACxB,KAAK,SAAS,KAAK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ACF,EAAC;GAEF,MAAM,WAAW,MAAM,KAAK,aAC1B,QACA,KAAK,UACL,WACA,WACD;AACD,QAAK,MAAM,WAAW,UAAU;IAC9B,KAAK,iBAAiB;IACtB,QAAQ,SAAS,KAAK,cAAc,SAAS;IAC7C,MAAM,KAAK,QAAQ,QAAgB;GACpC;GACD,KAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;GAED,YAAY;EACb;AACD,SAAO,CAAE;CACV;CAED,YAAiC;AAC/B,QAAM,IAAI,MAAM;CACjB;;;;;;;;;;;;CAaD,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,UACA,GAAG,MAIkC,EAAE;EACvC,MAAM,gBAAgBC,wCAAkB,QAAQ;GAC9C;GACA;GACA;EACD,EAAC;EACF,MAAM,sBAAsBC,oDAAwB,QAAQ;GAC1D;GACA;GACA;EACD,EAAC;AACF,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,gBACE,kBACAC,0CAAmB,QAAQ;IAAE;IAAK;IAAS;GAAW,EAAC;GACzD;GACA;GACA;GACA,GAAG;EACJ;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"agent.cjs","names":["BaseChain","task: Task","result: string","task_description: string","objective: string","runManager?: CallbackManagerForChainRun","thisTaskID: number","query: string","task: string","Document","TaskCreationChain","TaskPrioritizationChain","TaskExecutionChain"],"sources":["../../../src/experimental/babyagi/agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { VectorStoreInterface } from \"@langchain/core/vectorstores\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { BaseChain, ChainInputs } from \"../../chains/base.js\";\nimport { SerializedBaseChain } from \"../../chains/serde.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { TaskCreationChain } from \"./task_creation.js\";\nimport { TaskExecutionChain } from \"./task_execution.js\";\nimport { TaskPrioritizationChain } from \"./task_prioritization.js\";\n\n/**\n * Interface defining the structure of a task. A task has a `taskID` and a\n * `taskName`.\n */\nexport interface Task {\n taskID: string;\n taskName: string;\n}\n\n/**\n * Interface defining the structure of the inputs for the `BabyAGI` class.\n * It extends the `ChainInputs` interface, omitting the 'memory' and\n * 'callbackManager' properties, and adds properties specific to\n * `BabyAGI`.\n */\nexport interface BabyAGIInputs extends Omit<\n ChainInputs,\n \"memory\" | \"callbackManager\"\n> {\n creationChain: BaseChain;\n prioritizationChain: BaseChain;\n executionChain: BaseChain;\n vectorstore: VectorStoreInterface;\n maxIterations?: number;\n}\n\n/**\n * Class responsible for managing tasks, including their creation,\n * prioritization, and execution. It uses three chains for these\n * operations: `creationChain`, `prioritizationChain`, and\n * `executionChain`.\n * @example\n * ```typescript\n * const babyAGI = BabyAGI.fromLLM({\n * llm: new OpenAI({ temperature: 0 }),\n * vectorstore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * maxIterations: 3,\n * });\n *\n * const result = await babyAGI.call({\n * objective: \"Write a weather report for SF today\",\n * });\n * ```\n */\nexport class BabyAGI extends BaseChain implements BabyAGIInputs {\n static lc_name() {\n return \"BabyAGI\";\n }\n\n taskList: Task[];\n\n creationChain: BaseChain;\n\n prioritizationChain: BaseChain;\n\n executionChain: BaseChain;\n\n taskIDCounter: number;\n\n vectorstore: VectorStoreInterface;\n\n maxIterations: number;\n\n constructor({\n creationChain,\n prioritizationChain,\n executionChain,\n vectorstore,\n maxIterations = 100,\n verbose,\n callbacks,\n }: BabyAGIInputs) {\n super(undefined, verbose, callbacks);\n this.taskList = [];\n this.creationChain = creationChain;\n this.prioritizationChain = prioritizationChain;\n this.executionChain = executionChain;\n this.taskIDCounter = 1;\n this.vectorstore = vectorstore;\n this.maxIterations = maxIterations;\n }\n\n _chainType() {\n return \"BabyAGI\" as const;\n }\n\n get inputKeys() {\n return [\"objective\", \"firstTask\"];\n }\n\n get outputKeys() {\n return [];\n }\n\n /**\n * Adds a task to the task list.\n * @param task The task to be added.\n * @returns Promise resolving to void.\n */\n async addTask(task: Task) {\n this.taskList.push(task);\n }\n\n /**\n * Prints the current task list to the console.\n * @returns void\n */\n printTaskList() {\n console.log(\"\\x1b[95m\\x1b[1m\\n*****TASK LIST*****\\n\\x1b[0m\\x1b[0m\");\n for (const t of this.taskList) {\n console.log(`${t.taskID}: ${t.taskName}`);\n }\n }\n\n /**\n * Prints the next task to the console.\n * @param task The next task to be printed.\n * @returns void\n */\n printNextTask(task: Task) {\n console.log(\"\\x1b[92m\\x1b[1m\\n*****NEXT TASK*****\\n\\x1b[0m\\x1b[0m\");\n console.log(`${task.taskID}: ${task.taskName}`);\n }\n\n /**\n * Prints the result of a task to the console.\n * @param result The result of the task.\n * @returns void\n */\n printTaskResult(result: string) {\n console.log(\"\\x1b[93m\\x1b[1m\\n*****TASK RESULT*****\\n\\x1b[0m\\x1b[0m\");\n console.log(result.trim());\n }\n\n /**\n * Generates the next tasks based on the result of the previous task, the\n * task description, and the objective.\n * @param result The result of the previous task.\n * @param task_description The description of the task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of tasks without taskID.\n */\n async getNextTasks(\n result: string,\n task_description: string,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<Optional<Task, \"taskID\">[]> {\n const taskNames = this.taskList.map((t) => t.taskName);\n const incomplete_tasks = taskNames.join(\", \");\n const { [this.creationChain.outputKeys[0]]: text } =\n await this.creationChain.call(\n {\n result,\n task_description,\n incomplete_tasks,\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).split(\"\\n\");\n return newTasks\n .filter((taskName) => taskName.trim())\n .map((taskName) => ({ taskName }));\n }\n\n /**\n * Prioritizes the tasks based on the current task ID and the objective.\n * @param thisTaskID The ID of the current task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of prioritized tasks.\n */\n async prioritizeTasks(\n thisTaskID: number,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const taskNames = this.taskList.map((t) => t.taskName);\n const nextTaskID = thisTaskID + 1;\n const { [this.prioritizationChain.outputKeys[0]]: text } =\n await this.prioritizationChain.call(\n {\n task_names: taskNames.join(\", \"),\n next_task_id: String(nextTaskID),\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).trim().split(\"\\n\");\n const prioritizedTaskList = [];\n for (const taskString of newTasks) {\n const taskParts = taskString.trim().split(\".\", 2);\n if (taskParts.length === 2) {\n const taskID = taskParts[0].trim();\n const taskName = taskParts[1].trim();\n prioritizedTaskList.push({ taskID, taskName });\n }\n }\n return prioritizedTaskList;\n }\n\n /**\n * Retrieves the top tasks that are most similar to the given query.\n * @param query The query to search for.\n * @param k The number of top tasks to retrieve.\n * @returns Promise resolving to an array of top tasks.\n */\n async getTopTasks(query: string, k = 5) {\n const results = await this.vectorstore.similaritySearch(query, k);\n if (!results) {\n return [];\n }\n return results.map((item) => String(item.metadata.task));\n }\n\n /**\n * Executes a task based on the objective and the task description.\n * @param objective The objective of the task.\n * @param task The task to be executed.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to the result of the task execution as a string.\n */\n async executeTask(\n objective: string,\n task: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const context = await this.getTopTasks(objective);\n const { [this.executionChain.outputKeys[0]]: text } =\n await this.executionChain.call(\n {\n objective,\n context: context.join(\"\\n\"),\n task,\n },\n runManager?.getChild()\n );\n return text as string;\n }\n\n async _call(\n { objective, firstTask = \"Make a todo list\" }: ChainValues,\n runManager?: CallbackManagerForChainRun\n ) {\n this.taskList = [];\n this.taskIDCounter = 1;\n await this.addTask({ taskID: \"1\", taskName: firstTask });\n\n let numIters = 0;\n while (numIters < this.maxIterations && this.taskList.length > 0) {\n this.printTaskList();\n\n const task = this.taskList.shift()!;\n this.printNextTask(task);\n\n const result = await this.executeTask(\n objective,\n task.taskName,\n runManager\n );\n const thisTaskID = parseInt(task.taskID, 10);\n this.printTaskResult(result);\n\n await this.vectorstore.addDocuments([\n new Document({\n pageContent: result,\n metadata: { task: task.taskName },\n }),\n ]);\n\n const newTasks = await this.getNextTasks(\n result,\n task.taskName,\n objective,\n runManager\n );\n for (const newTask of newTasks) {\n this.taskIDCounter += 1;\n newTask.taskID = this.taskIDCounter.toFixed();\n await this.addTask(newTask as Task);\n }\n this.taskList = await this.prioritizeTasks(\n thisTaskID,\n objective,\n runManager\n );\n\n numIters += 1;\n }\n return {};\n }\n\n serialize(): SerializedBaseChain {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Static method to create a new BabyAGI instance from a\n * BaseLanguageModel.\n * @param llm BaseLanguageModel instance used to generate a new BabyAGI instance.\n * @param vectorstore VectorStore instance used to store and retrieve vectors.\n * @param executionChain Optional BaseChain instance used to execute tasks.\n * @param verbose Optional boolean indicating whether to log verbose output.\n * @param callbacks Optional callbacks to be used during the execution of tasks.\n * @param rest Optional additional parameters.\n * @returns A new instance of BabyAGI.\n */\n static fromLLM({\n llm,\n vectorstore,\n executionChain,\n verbose,\n callbacks,\n ...rest\n }: Optional<\n BabyAGIInputs,\n \"executionChain\" | \"creationChain\" | \"prioritizationChain\"\n > & { llm: BaseLanguageModelInterface }) {\n const creationChain = TaskCreationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n const prioritizationChain = TaskPrioritizationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n return new BabyAGI({\n creationChain,\n prioritizationChain,\n executionChain:\n executionChain ||\n TaskExecutionChain.fromLLM({ llm, verbose, callbacks }),\n vectorstore,\n verbose,\n callbacks,\n ...rest,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,UAAb,MAAa,gBAAgBA,uBAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBA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D,IAAI,WAAW;AACf,SAAO,WAAW,KAAK,iBAAiB,KAAK,SAAS,SAAS,GAAG;GAChE,KAAK,eAAe;GAEpB,MAAM,OAAO,KAAK,SAAS,OAAO;GAClC,KAAK,cAAc,KAAK;GAExB,MAAM,SAAS,MAAM,KAAK,YACxB,WACA,KAAK,UACL,WACD;GACD,MAAM,aAAa,SAAS,KAAK,QAAQ,GAAG;GAC5C,KAAK,gBAAgB,OAAO;GAE5B,MAAM,KAAK,YAAY,aAAa,CAClC,IAAII,oCAAS;IACX,aAAa;IACb,UAAU,EAAE,MAAM,KAAK,SAAU;GAClC,EACF,EAAC;GAEF,MAAM,WAAW,MAAM,KAAK,aAC1B,QACA,KAAK,UACL,WACA,WACD;AACD,QAAK,MAAM,WAAW,UAAU;IAC9B,KAAK,iBAAiB;IACtB,QAAQ,SAAS,KAAK,cAAc,SAAS;IAC7C,MAAM,KAAK,QAAQ,QAAgB;GACpC;GACD,KAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;GAED,YAAY;EACb;AACD,SAAO,CAAE;CACV;CAED,YAAiC;AAC/B,QAAM,IAAI,MAAM;CACjB;;;;;;;;;;;;CAaD,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,UACA,GAAG,MAIkC,EAAE;EACvC,MAAM,gBAAgBC,wCAAkB,QAAQ;GAC9C;GACA;GACA;EACD,EAAC;EACF,MAAM,sBAAsBC,oDAAwB,QAAQ;GAC1D;GACA;GACA;EACD,EAAC;AACF,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,gBACE,kBACAC,0CAAmB,QAAQ;IAAE;IAAK;IAAS;GAAW,EAAC;GACzD;GACA;GACA;GACA,GAAG;EACJ;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":["task: Task","result: string","task_description: string","objective: string","runManager?: CallbackManagerForChainRun","thisTaskID: number","query: string","task: string"],"sources":["../../../src/experimental/babyagi/agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { VectorStoreInterface } from \"@langchain/core/vectorstores\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { BaseChain, ChainInputs } from \"../../chains/base.js\";\nimport { SerializedBaseChain } from \"../../chains/serde.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { TaskCreationChain } from \"./task_creation.js\";\nimport { TaskExecutionChain } from \"./task_execution.js\";\nimport { TaskPrioritizationChain } from \"./task_prioritization.js\";\n\n/**\n * Interface defining the structure of a task. A task has a `taskID` and a\n * `taskName`.\n */\nexport interface Task {\n taskID: string;\n taskName: string;\n}\n\n/**\n * Interface defining the structure of the inputs for the `BabyAGI` class.\n * It extends the `ChainInputs` interface, omitting the 'memory' and\n * 'callbackManager' properties, and adds properties specific to\n * `BabyAGI`.\n */\nexport interface BabyAGIInputs\n extends Omit<ChainInputs, \"memory\" | \"callbackManager\"> {\n creationChain: BaseChain;\n prioritizationChain: BaseChain;\n executionChain: BaseChain;\n vectorstore: VectorStoreInterface;\n maxIterations?: number;\n}\n\n/**\n * Class responsible for managing tasks, including their creation,\n * prioritization, and execution. It uses three chains for these\n * operations: `creationChain`, `prioritizationChain`, and\n * `executionChain`.\n * @example\n * ```typescript\n * const babyAGI = BabyAGI.fromLLM({\n * llm: new OpenAI({ temperature: 0 }),\n * vectorstore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * maxIterations: 3,\n * });\n *\n * const result = await babyAGI.call({\n * objective: \"Write a weather report for SF today\",\n * });\n * ```\n */\nexport class BabyAGI extends BaseChain implements BabyAGIInputs {\n static lc_name() {\n return \"BabyAGI\";\n }\n\n taskList: Task[];\n\n creationChain: BaseChain;\n\n prioritizationChain: BaseChain;\n\n executionChain: BaseChain;\n\n taskIDCounter: number;\n\n vectorstore: VectorStoreInterface;\n\n maxIterations: number;\n\n constructor({\n creationChain,\n prioritizationChain,\n executionChain,\n vectorstore,\n maxIterations = 100,\n verbose,\n callbacks,\n }: BabyAGIInputs) {\n super(undefined, verbose, callbacks);\n this.taskList = [];\n this.creationChain = creationChain;\n this.prioritizationChain = prioritizationChain;\n this.executionChain = executionChain;\n this.taskIDCounter = 1;\n this.vectorstore = vectorstore;\n this.maxIterations = maxIterations;\n }\n\n _chainType() {\n return \"BabyAGI\" as const;\n }\n\n get inputKeys() {\n return [\"objective\", \"firstTask\"];\n }\n\n get outputKeys() {\n return [];\n }\n\n /**\n * Adds a task to the task list.\n * @param task The task to be added.\n * @returns Promise resolving to void.\n */\n async addTask(task: Task) {\n this.taskList.push(task);\n }\n\n /**\n * Prints the current task list to the console.\n * @returns void\n */\n printTaskList() {\n console.log(\"\\x1b[95m\\x1b[1m\\n*****TASK LIST*****\\n\\x1b[0m\\x1b[0m\");\n for (const t of this.taskList) {\n console.log(`${t.taskID}: ${t.taskName}`);\n }\n }\n\n /**\n * Prints the next task to the console.\n * @param task The next task to be printed.\n * @returns void\n */\n printNextTask(task: Task) {\n console.log(\"\\x1b[92m\\x1b[1m\\n*****NEXT TASK*****\\n\\x1b[0m\\x1b[0m\");\n console.log(`${task.taskID}: ${task.taskName}`);\n }\n\n /**\n * Prints the result of a task to the console.\n * @param result The result of the task.\n * @returns void\n */\n printTaskResult(result: string) {\n console.log(\"\\x1b[93m\\x1b[1m\\n*****TASK RESULT*****\\n\\x1b[0m\\x1b[0m\");\n console.log(result.trim());\n }\n\n /**\n * Generates the next tasks based on the result of the previous task, the\n * task description, and the objective.\n * @param result The result of the previous task.\n * @param task_description The description of the task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of tasks without taskID.\n */\n async getNextTasks(\n result: string,\n task_description: string,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<Optional<Task, \"taskID\">[]> {\n const taskNames = this.taskList.map((t) => t.taskName);\n const incomplete_tasks = taskNames.join(\", \");\n const { [this.creationChain.outputKeys[0]]: text } =\n await this.creationChain.call(\n {\n result,\n task_description,\n incomplete_tasks,\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).split(\"\\n\");\n return newTasks\n .filter((taskName) => taskName.trim())\n .map((taskName) => ({ taskName }));\n }\n\n /**\n * Prioritizes the tasks based on the current task ID and the objective.\n * @param thisTaskID The ID of the current task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of prioritized tasks.\n */\n async prioritizeTasks(\n thisTaskID: number,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const taskNames = this.taskList.map((t) => t.taskName);\n const nextTaskID = thisTaskID + 1;\n const { [this.prioritizationChain.outputKeys[0]]: text } =\n await this.prioritizationChain.call(\n {\n task_names: taskNames.join(\", \"),\n next_task_id: String(nextTaskID),\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).trim().split(\"\\n\");\n const prioritizedTaskList = [];\n for (const taskString of newTasks) {\n const taskParts = taskString.trim().split(\".\", 2);\n if (taskParts.length === 2) {\n const taskID = taskParts[0].trim();\n const taskName = taskParts[1].trim();\n prioritizedTaskList.push({ taskID, taskName });\n }\n }\n return prioritizedTaskList;\n }\n\n /**\n * Retrieves the top tasks that are most similar to the given query.\n * @param query The query to search for.\n * @param k The number of top tasks to retrieve.\n * @returns Promise resolving to an array of top tasks.\n */\n async getTopTasks(query: string, k = 5) {\n const results = await this.vectorstore.similaritySearch(query, k);\n if (!results) {\n return [];\n }\n return results.map((item) => String(item.metadata.task));\n }\n\n /**\n * Executes a task based on the objective and the task description.\n * @param objective The objective of the task.\n * @param task The task to be executed.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to the result of the task execution as a string.\n */\n async executeTask(\n objective: string,\n task: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const context = await this.getTopTasks(objective);\n const { [this.executionChain.outputKeys[0]]: text } =\n await this.executionChain.call(\n {\n objective,\n context: context.join(\"\\n\"),\n task,\n },\n runManager?.getChild()\n );\n return text as string;\n }\n\n async _call(\n { objective, firstTask = \"Make a todo list\" }: ChainValues,\n runManager?: CallbackManagerForChainRun\n ) {\n this.taskList = [];\n this.taskIDCounter = 1;\n await this.addTask({ taskID: \"1\", taskName: firstTask });\n\n let numIters = 0;\n while (numIters < this.maxIterations && this.taskList.length > 0) {\n this.printTaskList();\n\n const task = this.taskList.shift()!;\n this.printNextTask(task);\n\n const result = await this.executeTask(\n objective,\n task.taskName,\n runManager\n );\n const thisTaskID = parseInt(task.taskID, 10);\n this.printTaskResult(result);\n\n await this.vectorstore.addDocuments([\n new Document({\n pageContent: result,\n metadata: { task: task.taskName },\n }),\n ]);\n\n const newTasks = await this.getNextTasks(\n result,\n task.taskName,\n objective,\n runManager\n );\n for (const newTask of newTasks) {\n this.taskIDCounter += 1;\n newTask.taskID = this.taskIDCounter.toFixed();\n await this.addTask(newTask as Task);\n }\n this.taskList = await this.prioritizeTasks(\n thisTaskID,\n objective,\n runManager\n );\n\n numIters += 1;\n }\n return {};\n }\n\n serialize(): SerializedBaseChain {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Static method to create a new BabyAGI instance from a\n * BaseLanguageModel.\n * @param llm BaseLanguageModel instance used to generate a new BabyAGI instance.\n * @param vectorstore VectorStore instance used to store and retrieve vectors.\n * @param executionChain Optional BaseChain instance used to execute tasks.\n * @param verbose Optional boolean indicating whether to log verbose output.\n * @param callbacks Optional callbacks to be used during the execution of tasks.\n * @param rest Optional additional parameters.\n * @returns A new instance of BabyAGI.\n */\n static fromLLM({\n llm,\n vectorstore,\n executionChain,\n verbose,\n callbacks,\n ...rest\n }: Optional<\n BabyAGIInputs,\n \"executionChain\" | \"creationChain\" | \"prioritizationChain\"\n > & { llm: BaseLanguageModelInterface }) {\n const creationChain = TaskCreationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n const prioritizationChain = TaskPrioritizationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n return new BabyAGI({\n creationChain,\n prioritizationChain,\n executionChain:\n executionChain ||\n TaskExecutionChain.fromLLM({ llm, verbose, callbacks }),\n vectorstore,\n verbose,\n callbacks,\n ...rest,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,UAAb,MAAa,gBAAgB,UAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,WACc,EAAE;EAChB,MAAM,QAAW,SAAS,UAAU;EACpC,KAAK,WAAW,CAAE;EAClB,KAAK,gBAAgB;EACrB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,gBAAgB;CACtB;CAED,aAAa;AACX,SAAO;CACR;CAED,IAAI,YAAY;AACd,SAAO,CAAC,aAAa,WAAY;CAClC;CAED,IAAI,aAAa;AACf,SAAO,CAAE;CACV;;;;;;CAOD,MAAM,QAAQA,MAAY;EACxB,KAAK,SAAS,KAAK,KAAK;CACzB;;;;;CAMD,gBAAgB;EACd,QAAQ,IAAI,uDAAuD;AACnE,OAAK,MAAM,KAAK,KAAK,UACnB,QAAQ,IAAI,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,CAAC;CAE5C;;;;;;CAOD,cAAcA,MAAY;EACxB,QAAQ,IAAI,uDAAuD;EACnE,QAAQ,IAAI,GAAG,KAAK,OAAO,EAAE,EAAE,KAAK,UAAU,CAAC;CAChD;;;;;;CAOD,gBAAgBC,QAAgB;EAC9B,QAAQ,IAAI,yDAAyD;EACrE,QAAQ,IAAI,OAAO,MAAM,CAAC;CAC3B;;;;;;;;;;CAWD,MAAM,aACJA,QACAC,kBACAC,WACAC,YACqC;EACrC,MAAM,YAAY,KAAK,SAAS,IAAI,CAAC,MAAM,EAAE,SAAS;EACtD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AC1D;GACA;GACA;EACD,EAAC;AACF,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,gBACE,kBACA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;GAAW,EAAC;GACzD;GACA;GACA;GACA,GAAG;EACJ;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"agent.js","names":["task: Task","result: string","task_description: string","objective: string","runManager?: CallbackManagerForChainRun","thisTaskID: number","query: string","task: string"],"sources":["../../../src/experimental/babyagi/agent.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { VectorStoreInterface } from \"@langchain/core/vectorstores\";\nimport { Document } from \"@langchain/core/documents\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { BaseChain, ChainInputs } from \"../../chains/base.js\";\nimport { SerializedBaseChain } from \"../../chains/serde.js\";\nimport { Optional } from \"../../types/type-utils.js\";\nimport { TaskCreationChain } from \"./task_creation.js\";\nimport { TaskExecutionChain } from \"./task_execution.js\";\nimport { TaskPrioritizationChain } from \"./task_prioritization.js\";\n\n/**\n * Interface defining the structure of a task. A task has a `taskID` and a\n * `taskName`.\n */\nexport interface Task {\n taskID: string;\n taskName: string;\n}\n\n/**\n * Interface defining the structure of the inputs for the `BabyAGI` class.\n * It extends the `ChainInputs` interface, omitting the 'memory' and\n * 'callbackManager' properties, and adds properties specific to\n * `BabyAGI`.\n */\nexport interface BabyAGIInputs extends Omit<\n ChainInputs,\n \"memory\" | \"callbackManager\"\n> {\n creationChain: BaseChain;\n prioritizationChain: BaseChain;\n executionChain: BaseChain;\n vectorstore: VectorStoreInterface;\n maxIterations?: number;\n}\n\n/**\n * Class responsible for managing tasks, including their creation,\n * prioritization, and execution. It uses three chains for these\n * operations: `creationChain`, `prioritizationChain`, and\n * `executionChain`.\n * @example\n * ```typescript\n * const babyAGI = BabyAGI.fromLLM({\n * llm: new OpenAI({ temperature: 0 }),\n * vectorstore: new MemoryVectorStore(new OpenAIEmbeddings()),\n * maxIterations: 3,\n * });\n *\n * const result = await babyAGI.call({\n * objective: \"Write a weather report for SF today\",\n * });\n * ```\n */\nexport class BabyAGI extends BaseChain implements BabyAGIInputs {\n static lc_name() {\n return \"BabyAGI\";\n }\n\n taskList: Task[];\n\n creationChain: BaseChain;\n\n prioritizationChain: BaseChain;\n\n executionChain: BaseChain;\n\n taskIDCounter: number;\n\n vectorstore: VectorStoreInterface;\n\n maxIterations: number;\n\n constructor({\n creationChain,\n prioritizationChain,\n executionChain,\n vectorstore,\n maxIterations = 100,\n verbose,\n callbacks,\n }: BabyAGIInputs) {\n super(undefined, verbose, callbacks);\n this.taskList = [];\n this.creationChain = creationChain;\n this.prioritizationChain = prioritizationChain;\n this.executionChain = executionChain;\n this.taskIDCounter = 1;\n this.vectorstore = vectorstore;\n this.maxIterations = maxIterations;\n }\n\n _chainType() {\n return \"BabyAGI\" as const;\n }\n\n get inputKeys() {\n return [\"objective\", \"firstTask\"];\n }\n\n get outputKeys() {\n return [];\n }\n\n /**\n * Adds a task to the task list.\n * @param task The task to be added.\n * @returns Promise resolving to void.\n */\n async addTask(task: Task) {\n this.taskList.push(task);\n }\n\n /**\n * Prints the current task list to the console.\n * @returns void\n */\n printTaskList() {\n console.log(\"\\x1b[95m\\x1b[1m\\n*****TASK LIST*****\\n\\x1b[0m\\x1b[0m\");\n for (const t of this.taskList) {\n console.log(`${t.taskID}: ${t.taskName}`);\n }\n }\n\n /**\n * Prints the next task to the console.\n * @param task The next task to be printed.\n * @returns void\n */\n printNextTask(task: Task) {\n console.log(\"\\x1b[92m\\x1b[1m\\n*****NEXT TASK*****\\n\\x1b[0m\\x1b[0m\");\n console.log(`${task.taskID}: ${task.taskName}`);\n }\n\n /**\n * Prints the result of a task to the console.\n * @param result The result of the task.\n * @returns void\n */\n printTaskResult(result: string) {\n console.log(\"\\x1b[93m\\x1b[1m\\n*****TASK RESULT*****\\n\\x1b[0m\\x1b[0m\");\n console.log(result.trim());\n }\n\n /**\n * Generates the next tasks based on the result of the previous task, the\n * task description, and the objective.\n * @param result The result of the previous task.\n * @param task_description The description of the task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of tasks without taskID.\n */\n async getNextTasks(\n result: string,\n task_description: string,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ): Promise<Optional<Task, \"taskID\">[]> {\n const taskNames = this.taskList.map((t) => t.taskName);\n const incomplete_tasks = taskNames.join(\", \");\n const { [this.creationChain.outputKeys[0]]: text } =\n await this.creationChain.call(\n {\n result,\n task_description,\n incomplete_tasks,\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).split(\"\\n\");\n return newTasks\n .filter((taskName) => taskName.trim())\n .map((taskName) => ({ taskName }));\n }\n\n /**\n * Prioritizes the tasks based on the current task ID and the objective.\n * @param thisTaskID The ID of the current task.\n * @param objective The objective of the task.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to an array of prioritized tasks.\n */\n async prioritizeTasks(\n thisTaskID: number,\n objective: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const taskNames = this.taskList.map((t) => t.taskName);\n const nextTaskID = thisTaskID + 1;\n const { [this.prioritizationChain.outputKeys[0]]: text } =\n await this.prioritizationChain.call(\n {\n task_names: taskNames.join(\", \"),\n next_task_id: String(nextTaskID),\n objective,\n },\n runManager?.getChild()\n );\n const newTasks = (text as string).trim().split(\"\\n\");\n const prioritizedTaskList = [];\n for (const taskString of newTasks) {\n const taskParts = taskString.trim().split(\".\", 2);\n if (taskParts.length === 2) {\n const taskID = taskParts[0].trim();\n const taskName = taskParts[1].trim();\n prioritizedTaskList.push({ taskID, taskName });\n }\n }\n return prioritizedTaskList;\n }\n\n /**\n * Retrieves the top tasks that are most similar to the given query.\n * @param query The query to search for.\n * @param k The number of top tasks to retrieve.\n * @returns Promise resolving to an array of top tasks.\n */\n async getTopTasks(query: string, k = 5) {\n const results = await this.vectorstore.similaritySearch(query, k);\n if (!results) {\n return [];\n }\n return results.map((item) => String(item.metadata.task));\n }\n\n /**\n * Executes a task based on the objective and the task description.\n * @param objective The objective of the task.\n * @param task The task to be executed.\n * @param runManager Optional CallbackManagerForChainRun instance.\n * @returns Promise resolving to the result of the task execution as a string.\n */\n async executeTask(\n objective: string,\n task: string,\n runManager?: CallbackManagerForChainRun\n ) {\n const context = await this.getTopTasks(objective);\n const { [this.executionChain.outputKeys[0]]: text } =\n await this.executionChain.call(\n {\n objective,\n context: context.join(\"\\n\"),\n task,\n },\n runManager?.getChild()\n );\n return text as string;\n }\n\n async _call(\n { objective, firstTask = \"Make a todo list\" }: ChainValues,\n runManager?: CallbackManagerForChainRun\n ) {\n this.taskList = [];\n this.taskIDCounter = 1;\n await this.addTask({ taskID: \"1\", taskName: firstTask });\n\n let numIters = 0;\n while (numIters < this.maxIterations && this.taskList.length > 0) {\n this.printTaskList();\n\n const task = this.taskList.shift()!;\n this.printNextTask(task);\n\n const result = await this.executeTask(\n objective,\n task.taskName,\n runManager\n );\n const thisTaskID = parseInt(task.taskID, 10);\n this.printTaskResult(result);\n\n await this.vectorstore.addDocuments([\n new Document({\n pageContent: result,\n metadata: { task: task.taskName },\n }),\n ]);\n\n const newTasks = await this.getNextTasks(\n result,\n task.taskName,\n objective,\n runManager\n );\n for (const newTask of newTasks) {\n this.taskIDCounter += 1;\n newTask.taskID = this.taskIDCounter.toFixed();\n await this.addTask(newTask as Task);\n }\n this.taskList = await this.prioritizeTasks(\n thisTaskID,\n objective,\n runManager\n );\n\n numIters += 1;\n }\n return {};\n }\n\n serialize(): SerializedBaseChain {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Static method to create a new BabyAGI instance from a\n * BaseLanguageModel.\n * @param llm BaseLanguageModel instance used to generate a new BabyAGI instance.\n * @param vectorstore VectorStore instance used to store and retrieve vectors.\n * @param executionChain Optional BaseChain instance used to execute tasks.\n * @param verbose Optional boolean indicating whether to log verbose output.\n * @param callbacks Optional callbacks to be used during the execution of tasks.\n * @param rest Optional additional parameters.\n * @returns A new instance of BabyAGI.\n */\n static fromLLM({\n llm,\n vectorstore,\n executionChain,\n verbose,\n callbacks,\n ...rest\n }: Optional<\n BabyAGIInputs,\n \"executionChain\" | \"creationChain\" | \"prioritizationChain\"\n > & { llm: BaseLanguageModelInterface }) {\n const creationChain = TaskCreationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n const prioritizationChain = TaskPrioritizationChain.fromLLM({\n llm,\n verbose,\n callbacks,\n });\n return new BabyAGI({\n creationChain,\n prioritizationChain,\n executionChain:\n executionChain ||\n TaskExecutionChain.fromLLM({ llm, verbose, callbacks }),\n vectorstore,\n verbose,\n callbacks,\n ...rest,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,UAAb,MAAa,gBAAgB,UAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,WACc,EAAE;EAChB,MAAM,QAAW,SAAS,UAAU;EACpC,KAAK,WAAW,CAAE;EAClB,KAAK,gBAAgB;EACrB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,gBAAgB;EACrB,KAAK,cAAc;EACnB,KAAK,gBAAgB;CACtB;CAED,aAAa;AACX,SAAO;CACR;CAED,IAAI,YAAY;AACd,SAAO,CAAC,aAAa,WAAY;CAClC;CAED,IAAI,aAAa;AACf,SAAO,CAAE;CACV;;;;;;CAOD,MAAM,QAAQA,MAAY;EACxB,KAAK,SAAS,KAAK,KAAK;CACzB;;;;;CAMD,gBAAgB;EACd,QAAQ,IAAI,uDAAuD;AACnE,OAAK,MAAM,KAAK,KAAK,UACnB,QAAQ,IAAI,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,CAAC;CAE5C;;;;;;CAOD,cAAcA,MAAY;EAC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;GACpC;GACD,KAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;GAED,YAAY;EACb;AACD,SAAO,CAAE;CACV;CAED,YAAiC;AAC/B,QAAM,IAAI,MAAM;CACjB;;;;;;;;;;;;CAaD,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,UACA,GAAG,MAIkC,EAAE;EACvC,MAAM,gBAAgB,kBAAkB,QAAQ;GAC9C;GACA;GACA;EACD,EAAC;EACF,MAAM,sBAAsB,wBAAwB,QAAQ;GAC1D;GACA;GACA;EACD,EAAC;AACF,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,gBACE,kBACA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;GAAW,EAAC;GACzD;GACA;GACA;GACA,GAAG;EACJ;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom_format.d.ts","names":["InputValues","ParsedFStringNode","PromptTemplate","PromptTemplateInput","TypedPromptInputValues","CustomFormatPromptTemplateInput","RunInput","Omit","CustomFormatPromptTemplate","PartialVariableName","Record","customParser","Symbol","Promise"],"sources":["../../../src/experimental/prompts/custom_format.d.ts"],"sourcesContent":["import type { InputValues } from \"@langchain/core/utils/types\";\nimport { type ParsedFStringNode, PromptTemplate, type PromptTemplateInput, TypedPromptInputValues } from \"@langchain/core/prompts\";\nexport type CustomFormatPromptTemplateInput<RunInput extends InputValues> = Omit<PromptTemplateInput<RunInput, string>, \"templateFormat\"> & {\n customParser: (template: string) => ParsedFStringNode[];\n templateValidator?: (template: string, inputVariables: string[]) => boolean;\n renderer: (template: string, values: InputValues) => string;\n};\nexport declare class CustomFormatPromptTemplate<RunInput extends InputValues = any, PartialVariableName extends string = any> extends PromptTemplate<RunInput, PartialVariableName> {\n static lc_name(): string;\n lc_serializable: boolean;\n templateValidator?: (template: string, inputVariables: string[]) => boolean;\n renderer: (template: string, values: InputValues) => string;\n constructor(input: CustomFormatPromptTemplateInput<RunInput>);\n /**\n * Load prompt template from a template\n */\n static fromTemplate<RunInput extends InputValues = Record<string, any>>(template: string, { customParser, ...rest }: Omit<CustomFormatPromptTemplateInput<RunInput>, \"template\" | \"inputVariables\">): CustomFormatPromptTemplate<RunInput extends Symbol ? never : RunInput, any>;\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n format(values: TypedPromptInputValues<RunInput>): Promise<string>;\n}\n//# sourceMappingURL=custom_format.d.ts.map"],"mappings":";;;;KAEYK,iDAAiDL,eAAeO,KAAKJ,oBAAoBG;sCAC7DL;EAD5BI,iBAAAA,CAAAA,EAAAA,CAAAA,QAAAA,EAAAA,MAA+B,
|
|
1
|
+
{"version":3,"file":"custom_format.d.ts","names":["InputValues","ParsedFStringNode","PromptTemplate","PromptTemplateInput","TypedPromptInputValues","CustomFormatPromptTemplateInput","RunInput","Omit","CustomFormatPromptTemplate","PartialVariableName","Record","customParser","Symbol","Promise"],"sources":["../../../src/experimental/prompts/custom_format.d.ts"],"sourcesContent":["import type { InputValues } from \"@langchain/core/utils/types\";\nimport { type ParsedFStringNode, PromptTemplate, type PromptTemplateInput, TypedPromptInputValues } from \"@langchain/core/prompts\";\nexport type CustomFormatPromptTemplateInput<RunInput extends InputValues> = Omit<PromptTemplateInput<RunInput, string>, \"templateFormat\"> & {\n customParser: (template: string) => ParsedFStringNode[];\n templateValidator?: (template: string, inputVariables: string[]) => boolean;\n renderer: (template: string, values: InputValues) => string;\n};\nexport declare class CustomFormatPromptTemplate<RunInput extends InputValues = any, PartialVariableName extends string = any> extends PromptTemplate<RunInput, PartialVariableName> {\n static lc_name(): string;\n lc_serializable: boolean;\n templateValidator?: (template: string, inputVariables: string[]) => boolean;\n renderer: (template: string, values: InputValues) => string;\n constructor(input: CustomFormatPromptTemplateInput<RunInput>);\n /**\n * Load prompt template from a template\n */\n static fromTemplate<RunInput extends InputValues = Record<string, any>>(template: string, { customParser, ...rest }: Omit<CustomFormatPromptTemplateInput<RunInput>, \"template\" | \"inputVariables\">): CustomFormatPromptTemplate<RunInput extends Symbol ? never : RunInput, any>;\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n format(values: TypedPromptInputValues<RunInput>): Promise<string>;\n}\n//# sourceMappingURL=custom_format.d.ts.map"],"mappings":";;;;KAEYK,iDAAiDL,eAAeO,KAAKJ,oBAAoBG;sCAC7DL;EAD5BI,iBAAAA,CAAAA,EAAAA,CAAAA,QAAAA,EAAAA,MAA+B,EAAAC,cAAA,EAAA,MAAA,EAAA,EAAA,GAAA,OAAA;EAAkBN,QAAAA,EAAAA,CAAAA,QAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAGpBA,WAHoBA,EAAAA,GAAAA,MAAAA;CAAwCM;AAApBH,cAK5DK,0BAL4DL,CAAAA,iBAKhBH,WALgBG,GAAAA,GAAAA,EAAAA,4BAAAA,MAAAA,GAAAA,GAAAA,CAAAA,SAKqDD,cALrDC,CAKoEG,QALpEH,EAK8EM,mBAL9EN,CAAAA,CAAAA;EAALI,OAAAA,OAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EACpCN,eAAAA,EAAAA,OAAAA;EAECD,iBAAAA,CAAAA,EAAAA,CAAAA,QAAAA,EAAAA,MAAAA,EAAAA,cAAAA,EAAAA,MAAAA,EAAAA,EAAAA,GAAAA,OAAAA;EAAW,QAAA,EAAA,CAAA,QAAA,EAAA,MAAA,EAAA,MAAA,EAMXA,WANW,EAAA,GAAA,MAAA;EAE/BQ,WAAAA,CAAAA,KAAAA,EAKEH,+BALwBI,CAKQH,QALRG,CAAAA;EAAkBT;;;EAIxBA,OAAAA,YAAAA,CAAAA,iBAKAA,WALAA,GAKcU,MALdV,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,CAAAA,CAAAA,QAAAA,EAAAA,MAAAA,EAAAA;IAAAA,YAAAA;IAAAA,GAAAA;EAAAA,CAAAA,EAKgFO,IALhFP,CAKqFK,+BALrFL,CAKqHM,QALrHN,CAAAA,EAAAA,UAAAA,GAAAA,gBAAAA,CAAAA,CAAAA,EAKiKQ,0BALjKR,CAK4LM,QAL5LN,SAK6MY,MAL7MZ,GAAAA,KAAAA,GAK8NM,QAL9NN,EAAAA,GAAAA,CAAAA;EACcM;;;;;EAIuGA,MAAAA,CAAAA,MAAAA,EAM3IF,sBAN2IE,CAMpHA,QANoHA,CAAAA,CAAAA,EAMxGO,OANwGP,CAAAA,MAAAA,CAAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlebars.d.ts","names":["InputValues","CustomFormatPromptTemplate","CustomFormatPromptTemplateInput","parseHandlebars","_langchain_core_prompts0","ParsedTemplateNode","interpolateHandlebars","HandlebarsPromptTemplateInput","RunInput","HandlebarsPromptTemplate","Record","Omit","Symbol"],"sources":["../../../src/experimental/prompts/handlebars.d.ts"],"sourcesContent":["import type { InputValues } from \"@langchain/core/utils/types\";\nimport { CustomFormatPromptTemplate, CustomFormatPromptTemplateInput } from \"./custom_format.js\";\nexport declare const parseHandlebars: (template: string) => import(\"@langchain/core/prompts\").ParsedTemplateNode[];\nexport declare const interpolateHandlebars: (template: string, values: InputValues) => string;\nexport type HandlebarsPromptTemplateInput<RunInput extends InputValues> = CustomFormatPromptTemplateInput<RunInput>;\nexport declare class HandlebarsPromptTemplate<RunInput extends InputValues = any> extends CustomFormatPromptTemplate<RunInput> {\n static lc_name(): string;\n /**\n * Load prompt template from a template\n */\n static fromTemplate<RunInput extends InputValues = Record<string, any>>(template: string, params?: Omit<HandlebarsPromptTemplateInput<RunInput>, \"template\" | \"inputVariables\" | \"customParser\" | \"templateValidator\" | \"renderer\">): CustomFormatPromptTemplate<RunInput extends Symbol ? never : RunInput, any>;\n}\n//# sourceMappingURL=handlebars.d.ts.map"],"mappings":";;;;;cAEqBG,uCAA6FC,wBAAAA,CAApBC,kBAAkB;cAC3FC,kDAAkDN;KAC3DO,+CAA+CP,eAAeE,gCAAgCM;AAFrFL,cAGAM,wBAH6FL,CAAAA,iBAGnDJ,WAH+BK,
|
|
1
|
+
{"version":3,"file":"handlebars.d.ts","names":["InputValues","CustomFormatPromptTemplate","CustomFormatPromptTemplateInput","parseHandlebars","_langchain_core_prompts0","ParsedTemplateNode","interpolateHandlebars","HandlebarsPromptTemplateInput","RunInput","HandlebarsPromptTemplate","Record","Omit","Symbol"],"sources":["../../../src/experimental/prompts/handlebars.d.ts"],"sourcesContent":["import type { InputValues } from \"@langchain/core/utils/types\";\nimport { CustomFormatPromptTemplate, CustomFormatPromptTemplateInput } from \"./custom_format.js\";\nexport declare const parseHandlebars: (template: string) => import(\"@langchain/core/prompts\").ParsedTemplateNode[];\nexport declare const interpolateHandlebars: (template: string, values: InputValues) => string;\nexport type HandlebarsPromptTemplateInput<RunInput extends InputValues> = CustomFormatPromptTemplateInput<RunInput>;\nexport declare class HandlebarsPromptTemplate<RunInput extends InputValues = any> extends CustomFormatPromptTemplate<RunInput> {\n static lc_name(): string;\n /**\n * Load prompt template from a template\n */\n static fromTemplate<RunInput extends InputValues = Record<string, any>>(template: string, params?: Omit<HandlebarsPromptTemplateInput<RunInput>, \"template\" | \"inputVariables\" | \"customParser\" | \"templateValidator\" | \"renderer\">): CustomFormatPromptTemplate<RunInput extends Symbol ? never : RunInput, any>;\n}\n//# sourceMappingURL=handlebars.d.ts.map"],"mappings":";;;;;cAEqBG,uCAA6FC,wBAAAA,CAApBC,kBAAkB;cAC3FC,kDAAkDN;KAC3DO,+CAA+CP,eAAeE,gCAAgCM;AAFrFL,cAGAM,wBAH6FL,CAAAA,iBAGnDJ,WAH+BK,GAAkB,GAAA,CAAA,SAGtBJ,0BAHsB,CAGKO,QAHL,CAAA,CAAA;EAC3FF,OAAAA,OAAAA,CAAAA,CAAAA,EAAAA,MAAwE;EACjFC;;;EAA8DL,OAAAA,YAAAA,CAAAA,iBAMjCF,WANiCE,GAMnBQ,MANmBR,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,CAAAA,CAAAA,QAAAA,EAAAA,MAAAA,EAAAA,MAAAA,CAAAA,EAM6BS,IAN7BT,CAMkCK,6BANlCL,CAMgEM,QANhEN,CAAAA,EAAAA,UAAAA,GAAAA,gBAAAA,GAAAA,cAAAA,GAAAA,mBAAAA,GAAAA,UAAAA,CAAAA,CAAAA,EAMgKD,0BANhKC,CAM2LM,QAN3LN,SAM4MU,MAN5MV,GAAAA,KAAAA,GAM6NM,QAN7NN,EAAAA,GAAAA,CAAAA;AAA+B"}
|
package/dist/hub/node.cjs
CHANGED
|
@@ -23,6 +23,30 @@ function isRunnableBinding(a) {
|
|
|
23
23
|
return wellKnownIds.some((id) => _idEquals(a, id));
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
|
+
* Infer modelProvider from the id namespace to avoid className collisions.
|
|
27
|
+
* For non-langchain packages, extracts the provider name from the namespace.
|
|
28
|
+
* e.g., ["langchain", "chat_models", "vertexai", "ChatVertexAI"] -> "google-vertexai"
|
|
29
|
+
* e.g., ["langchain_deepseek", "chat_models", "ChatDeepSeek"] -> "deepseek"
|
|
30
|
+
* @param idArray The full id array from the manifest
|
|
31
|
+
* @returns The inferred modelProvider key or undefined
|
|
32
|
+
*/
|
|
33
|
+
function inferModelProviderFromNamespace(idArray) {
|
|
34
|
+
if (!Array.isArray(idArray) || idArray.length < 2) return void 0;
|
|
35
|
+
const namespace = idArray.slice(0, -1);
|
|
36
|
+
for (const part of namespace) {
|
|
37
|
+
if (part === "langchain" || part === "langchain_core" || part === "chat_models" || part === "runnables" || part === "schema") continue;
|
|
38
|
+
if (part.startsWith("langchain_")) {
|
|
39
|
+
const providerName = part.slice(10);
|
|
40
|
+
return providerName.replace(/_/g, "-");
|
|
41
|
+
}
|
|
42
|
+
if (part.includes("vertexai_web")) return "google-vertexai-web";
|
|
43
|
+
else if (part.includes("vertexai")) return "google-vertexai";
|
|
44
|
+
else if (part.includes("genai") || part.includes("google_genai")) return "google-genai";
|
|
45
|
+
if (!part.includes("langchain") && part !== "chat_models" && part !== "runnables") return part.replace(/_/g, "-");
|
|
46
|
+
}
|
|
47
|
+
return void 0;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
26
50
|
* Pull a prompt from the hub.
|
|
27
51
|
* @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.
|
|
28
52
|
* @param options.apiKey LangSmith API key to use when pulling the prompt
|
|
@@ -47,7 +71,8 @@ async function pull(ownerRepoCommit, options) {
|
|
|
47
71
|
if (Array.isArray(chatModelObject?.id)) {
|
|
48
72
|
const modelName = chatModelObject?.id.at(-1);
|
|
49
73
|
if (modelName) {
|
|
50
|
-
|
|
74
|
+
const modelProvider = inferModelProviderFromNamespace(chatModelObject.id);
|
|
75
|
+
modelClass = await require_chat_models_universal.getChatModelByClassName(modelName, modelProvider);
|
|
51
76
|
if (!modelClass) console.warn(`Received unknown model name from prompt hub: "${modelName}"`);
|
|
52
77
|
}
|
|
53
78
|
}
|
|
@@ -57,6 +82,7 @@ async function pull(ownerRepoCommit, options) {
|
|
|
57
82
|
}
|
|
58
83
|
|
|
59
84
|
//#endregion
|
|
85
|
+
exports.inferModelProviderFromNamespace = inferModelProviderFromNamespace;
|
|
60
86
|
exports.pull = pull;
|
|
61
87
|
exports.push = require_base.basePush;
|
|
62
88
|
//# sourceMappingURL=node.cjs.map
|
package/dist/hub/node.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","names":["a: string[]","b: string[]","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }","basePull","getChatModelByClassName","load","generateOptionalImportMap","generateModelImportMap","bindOutputSchema"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n modelClass = await getChatModelByClassName(modelName);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;;AAYA,SAAS,UAAUA,GAAaC,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;AACR;AAED,SAAS,kBAAkBD,GAAsB;CAC/C,MAAM,eAAe,CACnB;EAAC;EAAkB;EAAa;CAAkB,GAClD;EAAC;EAAa;EAAU;EAAY;CAAkB,CACvD;AACD,QAAO,aAAa,KAAK,CAAC,OAAO,UAAU,GAAG,GAAG,CAAC;AACnD;;;;;;;;;;;;;;;;;;AAmBD,eAAsB,
|
|
1
|
+
{"version":3,"file":"node.cjs","names":["a: string[]","b: string[]","idArray: string[]","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }","basePull","getChatModelByClassName","load","generateOptionalImportMap","generateModelImportMap","bindOutputSchema"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImport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AM,eAAe,MAAMC,sBAAS,iBAAiB,QAAQ;CAC7D,IAAI;AACJ,KAAI,SAAS,cAAc;EACzB,MAAM,kBAAkB,kBACtB,aAAa,SAAS,QAAQ,MAAM,GACrC,GACG,aAAa,SAAS,QAAQ,MAAM,QAAQ,QAC5C,aAAa,SAAS,QAAQ;AAElC,MAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;GACtC,MAAM,YAAY,iBAAiB,GAAG,GAAG,GAAG;AAE5C,OAAI,WAAW;IACb,MAAM,gBAAgB,gCACpB,gBAAgB,GACjB;IACD,aAAa,MAAMC,sDAAwB,WAAW,cAAc;AACpE,QAAI,CAAC,YACH,QAAQ,KACN,CAAC,8CAA8C,EAAE,UAAU,CAAC,CAAC,CAC9D;GAEJ;EACF;CACF;CACD,MAAM,eAAe,MAAMC,wBACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACTC,uCAA0B,WAAW,EACrCC,oCAAuB,WAAW,EAClC,SAAS,eACV;AACD,QAAOC,8BAAiB,aAAa;AACtC"}
|
package/dist/hub/node.d.cts
CHANGED
|
@@ -3,6 +3,15 @@ import { Runnable } from "@langchain/core/runnables";
|
|
|
3
3
|
|
|
4
4
|
//#region src/hub/node.d.ts
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Infer modelProvider from the id namespace to avoid className collisions.
|
|
8
|
+
* For non-langchain packages, extracts the provider name from the namespace.
|
|
9
|
+
* e.g., ["langchain", "chat_models", "vertexai", "ChatVertexAI"] -> "google-vertexai"
|
|
10
|
+
* e.g., ["langchain_deepseek", "chat_models", "ChatDeepSeek"] -> "deepseek"
|
|
11
|
+
* @param idArray The full id array from the manifest
|
|
12
|
+
* @returns The inferred modelProvider key or undefined
|
|
13
|
+
*/
|
|
14
|
+
declare function inferModelProviderFromNamespace(idArray: string[]): string | undefined;
|
|
6
15
|
/**
|
|
7
16
|
* Pull a prompt from the hub.
|
|
8
17
|
* @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.
|
|
@@ -28,5 +37,5 @@ declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
|
28
37
|
secretsFromEnv?: boolean;
|
|
29
38
|
}): Promise<T>;
|
|
30
39
|
//#endregion
|
|
31
|
-
export { pull, basePush as push };
|
|
40
|
+
export { inferModelProviderFromNamespace, pull, basePush as push };
|
|
32
41
|
//# sourceMappingURL=node.d.cts.map
|
package/dist/hub/node.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.cts","names":["Runnable","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/node.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nexport { basePush as push } from \"./base.js\";\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=node.d.ts.map"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"node.d.cts","names":["Runnable","basePush","push","inferModelProviderFromNamespace","pull","T","Record","Promise"],"sources":["../../src/hub/node.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nexport { basePush as push } from \"./base.js\";\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport declare function inferModelProviderFromNamespace(idArray: string[]): string | undefined;\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=node.d.ts.map"],"mappings":";;;;;;;AAUA;AAkBA;;;;;AAMW,iBAxBaG,+BAAAA,CAwBb,OAAA,EAAA,MAAA,EAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;;;;;;;;;;;;;;;;;iBANaC,eAAeJ;;;;YAIzBM;;IAEVC,QAAQF"}
|
package/dist/hub/node.d.ts
CHANGED
|
@@ -3,6 +3,15 @@ import { Runnable } from "@langchain/core/runnables";
|
|
|
3
3
|
|
|
4
4
|
//#region src/hub/node.d.ts
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Infer modelProvider from the id namespace to avoid className collisions.
|
|
8
|
+
* For non-langchain packages, extracts the provider name from the namespace.
|
|
9
|
+
* e.g., ["langchain", "chat_models", "vertexai", "ChatVertexAI"] -> "google-vertexai"
|
|
10
|
+
* e.g., ["langchain_deepseek", "chat_models", "ChatDeepSeek"] -> "deepseek"
|
|
11
|
+
* @param idArray The full id array from the manifest
|
|
12
|
+
* @returns The inferred modelProvider key or undefined
|
|
13
|
+
*/
|
|
14
|
+
declare function inferModelProviderFromNamespace(idArray: string[]): string | undefined;
|
|
6
15
|
/**
|
|
7
16
|
* Pull a prompt from the hub.
|
|
8
17
|
* @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.
|
|
@@ -28,5 +37,5 @@ declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
|
28
37
|
secretsFromEnv?: boolean;
|
|
29
38
|
}): Promise<T>;
|
|
30
39
|
//#endregion
|
|
31
|
-
export { pull, basePush as push };
|
|
40
|
+
export { inferModelProviderFromNamespace, pull, basePush as push };
|
|
32
41
|
//# sourceMappingURL=node.d.ts.map
|
package/dist/hub/node.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.ts","names":["Runnable","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/node.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nexport { basePush as push } from \"./base.js\";\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=node.d.ts.map"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"node.d.ts","names":["Runnable","basePush","push","inferModelProviderFromNamespace","pull","T","Record","Promise"],"sources":["../../src/hub/node.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nexport { basePush as push } from \"./base.js\";\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport declare function inferModelProviderFromNamespace(idArray: string[]): string | undefined;\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=node.d.ts.map"],"mappings":";;;;;;;AAUA;AAkBA;;;;;AAMW,iBAxBaG,+BAAAA,CAwBb,OAAA,EAAA,MAAA,EAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;;;;;;;;;;;;;;;;;iBANaC,eAAeJ;;;;YAIzBM;;IAEVC,QAAQF"}
|
package/dist/hub/node.js
CHANGED
|
@@ -23,6 +23,30 @@ function isRunnableBinding(a) {
|
|
|
23
23
|
return wellKnownIds.some((id) => _idEquals(a, id));
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
|
+
* Infer modelProvider from the id namespace to avoid className collisions.
|
|
27
|
+
* For non-langchain packages, extracts the provider name from the namespace.
|
|
28
|
+
* e.g., ["langchain", "chat_models", "vertexai", "ChatVertexAI"] -> "google-vertexai"
|
|
29
|
+
* e.g., ["langchain_deepseek", "chat_models", "ChatDeepSeek"] -> "deepseek"
|
|
30
|
+
* @param idArray The full id array from the manifest
|
|
31
|
+
* @returns The inferred modelProvider key or undefined
|
|
32
|
+
*/
|
|
33
|
+
function inferModelProviderFromNamespace(idArray) {
|
|
34
|
+
if (!Array.isArray(idArray) || idArray.length < 2) return void 0;
|
|
35
|
+
const namespace = idArray.slice(0, -1);
|
|
36
|
+
for (const part of namespace) {
|
|
37
|
+
if (part === "langchain" || part === "langchain_core" || part === "chat_models" || part === "runnables" || part === "schema") continue;
|
|
38
|
+
if (part.startsWith("langchain_")) {
|
|
39
|
+
const providerName = part.slice(10);
|
|
40
|
+
return providerName.replace(/_/g, "-");
|
|
41
|
+
}
|
|
42
|
+
if (part.includes("vertexai_web")) return "google-vertexai-web";
|
|
43
|
+
else if (part.includes("vertexai")) return "google-vertexai";
|
|
44
|
+
else if (part.includes("genai") || part.includes("google_genai")) return "google-genai";
|
|
45
|
+
if (!part.includes("langchain") && part !== "chat_models" && part !== "runnables") return part.replace(/_/g, "-");
|
|
46
|
+
}
|
|
47
|
+
return void 0;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
26
50
|
* Pull a prompt from the hub.
|
|
27
51
|
* @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.
|
|
28
52
|
* @param options.apiKey LangSmith API key to use when pulling the prompt
|
|
@@ -47,7 +71,8 @@ async function pull(ownerRepoCommit, options) {
|
|
|
47
71
|
if (Array.isArray(chatModelObject?.id)) {
|
|
48
72
|
const modelName = chatModelObject?.id.at(-1);
|
|
49
73
|
if (modelName) {
|
|
50
|
-
|
|
74
|
+
const modelProvider = inferModelProviderFromNamespace(chatModelObject.id);
|
|
75
|
+
modelClass = await getChatModelByClassName(modelName, modelProvider);
|
|
51
76
|
if (!modelClass) console.warn(`Received unknown model name from prompt hub: "${modelName}"`);
|
|
52
77
|
}
|
|
53
78
|
}
|
|
@@ -57,5 +82,5 @@ async function pull(ownerRepoCommit, options) {
|
|
|
57
82
|
}
|
|
58
83
|
|
|
59
84
|
//#endregion
|
|
60
|
-
export { pull, basePush as push };
|
|
85
|
+
export { inferModelProviderFromNamespace, pull, basePush as push };
|
|
61
86
|
//# sourceMappingURL=node.js.map
|
package/dist/hub/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":["a: string[]","b: string[]","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n modelClass = await getChatModelByClassName(modelName);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n}\n"],"mappings":";;;;;AAYA,SAAS,UAAUA,GAAaC,GAAsB;AACpD,KAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,QAAQ,EAAE,CACxC,QAAO;AAET,KAAI,EAAE,WAAW,EAAE,OACjB,QAAO;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,EAAE,OAAO,EAAE,GACb,QAAO;AAGX,QAAO;AACR;AAED,SAAS,kBAAkBD,GAAsB;CAC/C,MAAM,eAAe,CACnB;EAAC;EAAkB;EAAa;CAAkB,GAClD;EAAC;EAAa;EAAU;EAAY;CAAkB,CACvD;AACD,QAAO,aAAa,KAAK,CAAC,OAAO,UAAU,GAAG,GAAG,CAAC;AACnD;;;;;;;;;;;;;;;;;;AAmBD,eAAsB,
|
|
1
|
+
{"version":3,"file":"node.js","names":["a: string[]","b: string[]","idArray: string[]","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }"],"sources":["../../src/hub/node.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport {\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\nimport { load } from \"../load/index.js\";\nimport { getChatModelByClassName } from \"../chat_models/universal.js\";\n\nexport { basePush as push } from \"./base.js\";\n\nfunction _idEquals(a: string[], b: string[]): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction isRunnableBinding(a: string[]): boolean {\n const wellKnownIds = [\n [\"langchain_core\", \"runnables\", \"RunnableBinding\"],\n [\"langchain\", \"schema\", \"runnable\", \"RunnableBinding\"],\n ];\n return wellKnownIds.some((id) => _idEquals(a, id));\n}\n\n/**\n * Infer modelProvider from the id namespace to avoid className collisions.\n * For non-langchain packages, extracts the provider name from the namespace.\n * e.g., [\"langchain\", \"chat_models\", \"vertexai\", \"ChatVertexAI\"] -> \"google-vertexai\"\n * e.g., [\"langchain_deepseek\", \"chat_models\", \"ChatDeepSeek\"] -> \"deepseek\"\n * @param idArray The full id array from the manifest\n * @returns The inferred modelProvider key or undefined\n */\nexport function inferModelProviderFromNamespace(\n idArray: string[]\n): string | undefined {\n if (!Array.isArray(idArray) || idArray.length < 2) {\n return undefined;\n }\n\n // Check namespace parts (excluding the className at the end)\n const namespace = idArray.slice(0, -1);\n\n // Look for a part that looks like a provider package (not langchain/langchain_core)\n for (const part of namespace) {\n // Skip standard langchain packages\n if (\n part === \"langchain\" ||\n part === \"langchain_core\" ||\n part === \"chat_models\" ||\n part === \"runnables\" ||\n part === \"schema\"\n ) {\n continue;\n }\n\n // If it starts with \"langchain_\", extract the provider name\n // e.g., \"langchain_google_genai\" -> \"google-genai\"\n // e.g., \"langchain_deepseek\" -> \"deepseek\"\n if (part.startsWith(\"langchain_\")) {\n const providerName = part.slice(\"langchain_\".length);\n // Convert underscores to hyphens to match MODEL_PROVIDER_CONFIG keys\n return providerName.replace(/_/g, \"-\");\n }\n\n // Handle special cases for Google providers that need prefix\n if (part.includes(\"vertexai_web\")) {\n return \"google-vertexai-web\";\n } else if (part.includes(\"vertexai\")) {\n return \"google-vertexai\";\n } else if (part.includes(\"genai\") || part.includes(\"google_genai\")) {\n return \"google-genai\";\n }\n\n // For other provider-looking parts, use as-is with underscores converted to hyphens\n // e.g., \"openai\" -> \"openai\", \"anthropic\" -> \"anthropic\"\n if (\n !part.includes(\"langchain\") &&\n part !== \"chat_models\" &&\n part !== \"runnables\"\n ) {\n return part.replace(/_/g, \"-\");\n }\n }\n\n return undefined;\n}\n\n/**\n * Pull a prompt from the hub.\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. You must have the appropriate LangChain integration package installed.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n let modelClass;\n if (options?.includeModel) {\n const chatModelObject = isRunnableBinding(\n promptObject.manifest.kwargs?.last?.id\n )\n ? promptObject.manifest.kwargs?.last?.kwargs?.bound\n : promptObject.manifest.kwargs?.last;\n\n if (Array.isArray(chatModelObject?.id)) {\n const modelName = chatModelObject?.id.at(-1);\n\n if (modelName) {\n const modelProvider = inferModelProviderFromNamespace(\n chatModelObject.id\n );\n modelClass = await getChatModelByClassName(modelName, modelProvider);\n if (!modelClass) {\n console.warn(\n `Received unknown model name from prompt hub: \"${modelName}\"`\n );\n }\n }\n }\n }\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(modelClass),\n generateModelImportMap(modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPr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cAAc;EACzB,MAAM,kBAAkB,kBACtB,aAAa,SAAS,QAAQ,MAAM,GACrC,GACG,aAAa,SAAS,QAAQ,MAAM,QAAQ,QAC5C,aAAa,SAAS,QAAQ;AAElC,MAAI,MAAM,QAAQ,iBAAiB,GAAG,EAAE;GACtC,MAAM,YAAY,iBAAiB,GAAG,GAAG,GAAG;AAE5C,OAAI,WAAW;IACb,MAAM,gBAAgB,gCACpB,gBAAgB,GACjB;IACD,aAAa,MAAM,wBAAwB,WAAW,cAAc;AACpE,QAAI,CAAC,YACH,QAAQ,KACN,CAAC,8CAA8C,EAAE,UAAU,CAAC,CAAC,CAC9D;GAEJ;EACF;CACF;CACD,MAAM,eAAe,MAAM,KACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACT,0BAA0B,WAAW,EACrC,uBAAuB,WAAW,EAClC,SAAS,eACV;AACD,QAAO,iBAAiB,aAAa;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buffer_token_memory.cjs","names":["BaseChatMemory","fields: ConversationTokenBufferMemoryInput","_values: InputValues","result","inputValues: InputValues","outputValues: OutputValues"],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput
|
|
1
|
+
{"version":3,"file":"buffer_token_memory.cjs","names":["BaseChatMemory","fields: ConversationTokenBufferMemoryInput","_values: InputValues","result","inputValues: InputValues","outputValues: OutputValues"],"sources":["../../src/memory/buffer_token_memory.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport {\n InputValues,\n MemoryVariables,\n OutputValues,\n} from \"@langchain/core/memory\";\nimport { getBufferString } from \"@langchain/core/messages\";\nimport { BaseChatMemory, BaseChatMemoryInput } from \"./chat_memory.js\";\n\n/**\n * Interface for the input parameters of the `BufferTokenMemory` class.\n */\n\nexport interface ConversationTokenBufferMemoryInput extends BaseChatMemoryInput {\n /* Prefix for human messages in the buffer. */\n humanPrefix?: string;\n\n /* Prefix for AI messages in the buffer. */\n aiPrefix?: string;\n\n /* The LLM for this instance. */\n llm: BaseLanguageModelInterface;\n\n /* Memory key for buffer instance. */\n memoryKey?: string;\n\n /* Maximmum number of tokens allowed in the buffer. */\n maxTokenLimit?: number;\n}\n\n/**\n * Class that represents a conversation chat memory with a token buffer.\n * It extends the `BaseChatMemory` class and implements the\n * `ConversationTokenBufferMemoryInput` interface.\n * @example\n * ```typescript\n * const memory = new ConversationTokenBufferMemory({\n * llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n * maxTokenLimit: 10,\n * });\n *\n * // Save conversation context\n * await memory.saveContext({ input: \"hi\" }, { output: \"whats up\" });\n * await memory.saveContext({ input: \"not much you\" }, { output: \"not much\" });\n *\n * // Load memory variables\n * const result = await memory.loadMemoryVariables({});\n * console.log(result);\n * ```\n */\n\nexport class ConversationTokenBufferMemory\n extends BaseChatMemory\n implements ConversationTokenBufferMemoryInput\n{\n humanPrefix = \"Human\";\n\n aiPrefix = \"AI\";\n\n memoryKey = \"history\";\n\n maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden\n\n llm: BaseLanguageModelInterface;\n\n constructor(fields: ConversationTokenBufferMemoryInput) {\n super(fields);\n this.llm = fields.llm;\n this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;\n this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;\n this.memoryKey = fields?.memoryKey ?? this.memoryKey;\n this.maxTokenLimit = fields?.maxTokenLimit ?? this.maxTokenLimit;\n }\n\n get memoryKeys() {\n return [this.memoryKey];\n }\n\n /**\n * Loads the memory variables. It takes an `InputValues` object as a\n * parameter and returns a `Promise` that resolves with a\n * `MemoryVariables` object.\n * @param _values `InputValues` object.\n * @returns A `Promise` that resolves with a `MemoryVariables` object.\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n if (this.returnMessages) {\n const result = {\n [this.memoryKey]: messages,\n };\n return result;\n }\n const result = {\n [this.memoryKey]: getBufferString(\n messages,\n this.humanPrefix,\n this.aiPrefix\n ),\n };\n return result;\n }\n\n /**\n * Saves the context from this conversation to buffer. If the amount\n * of tokens required to save the buffer exceeds MAX_TOKEN_LIMIT,\n * prune it.\n */\n async saveContext(inputValues: InputValues, outputValues: OutputValues) {\n await super.saveContext(inputValues, outputValues);\n\n // Prune buffer if it exceeds the max token limit set for this instance.\n const buffer = await this.chatHistory.getMessages();\n let currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n\n if (currBufferLength > this.maxTokenLimit) {\n const prunedMemory = [];\n while (currBufferLength > this.maxTokenLimit) {\n prunedMemory.push(buffer.shift());\n currBufferLength = await this.llm.getNumTokens(\n getBufferString(buffer, this.humanPrefix, this.aiPrefix)\n );\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gCAAb,cACUA,0CAEV;CACE,cAAc;CAEd,WAAW;CAEX,YAAY;CAEZ,gBAAgB;CAEhB;CAEA,YAAYC,QAA4C;EACtD,MAAM,OAAO;EACb,KAAK,MAAM,OAAO;EAClB,KAAK,cAAc,QAAQ,eAAe,KAAK;EAC/C,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,YAAY,QAAQ,aAAa,KAAK;EAC3C,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;CACpD;CAED,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,SAAU;CACxB;;;;;;;;CASD,MAAM,oBAAoBC,SAAgD;EACxE,MAAM,WAAW,MAAM,KAAK,YAAY,aAAa;AACrD,MAAI,KAAK,gBAAgB;GACvB,MAAMC,WAAS,GACZ,KAAK,YAAY,SACnB;AACD,UAAOA;EACR;EACD,MAAM,SAAS,GACZ,KAAK,2DACJ,UACA,KAAK,aACL,KAAK,SACN,CACF;AACD,SAAO;CACR;;;;;;CAOD,MAAM,YAAYC,aAA0BC,cAA4B;EACtE,MAAM,MAAM,YAAY,aAAa,aAAa;EAGlD,MAAM,SAAS,MAAM,KAAK,YAAY,aAAa;EACnD,IAAI,mBAAmB,MAAM,KAAK,IAAI,4DACpB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD;AAED,MAAI,mBAAmB,KAAK,eAAe;GACzC,MAAM,eAAe,CAAE;AACvB,UAAO,mBAAmB,KAAK,eAAe;IAC5C,aAAa,KAAK,OAAO,OAAO,CAAC;IACjC,mBAAmB,MAAM,KAAK,IAAI,4DAChB,QAAQ,KAAK,aAAa,KAAK,SAAS,CACzD;GACF;EACF;CACF;AACF"}
|