@langchain/classic 1.0.34 → 1.0.36
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 +14 -0
- package/dist/agents/chat/index.cjs.map +1 -1
- package/dist/agents/chat/index.js.map +1 -1
- package/dist/agents/chat/outputParser.cjs.map +1 -1
- package/dist/agents/chat/outputParser.js.map +1 -1
- package/dist/agents/chat_convo/index.cjs.map +1 -1
- package/dist/agents/chat_convo/index.js.map +1 -1
- package/dist/agents/chat_convo/outputParser.cjs.map +1 -1
- package/dist/agents/chat_convo/outputParser.js.map +1 -1
- package/dist/agents/executor.cjs.map +1 -1
- package/dist/agents/executor.js.map +1 -1
- package/dist/agents/format_scratchpad/log.cjs.map +1 -1
- package/dist/agents/format_scratchpad/log.js.map +1 -1
- package/dist/agents/format_scratchpad/log_to_message.cjs.map +1 -1
- package/dist/agents/format_scratchpad/log_to_message.js.map +1 -1
- package/dist/agents/initialize.cjs.map +1 -1
- package/dist/agents/initialize.js.map +1 -1
- package/dist/agents/mrkl/index.cjs.map +1 -1
- package/dist/agents/mrkl/index.js.map +1 -1
- package/dist/agents/mrkl/outputParser.cjs.map +1 -1
- package/dist/agents/mrkl/outputParser.js.map +1 -1
- package/dist/agents/openai_functions/index.cjs.map +1 -1
- package/dist/agents/openai_functions/index.js.map +1 -1
- package/dist/agents/openai_tools/index.cjs.map +1 -1
- package/dist/agents/openai_tools/index.js.map +1 -1
- package/dist/agents/react/index.cjs.map +1 -1
- package/dist/agents/react/index.js.map +1 -1
- package/dist/agents/react/output_parser.cjs.map +1 -1
- package/dist/agents/react/output_parser.js.map +1 -1
- package/dist/agents/structured_chat/index.cjs.map +1 -1
- package/dist/agents/structured_chat/index.js.map +1 -1
- package/dist/agents/structured_chat/outputParser.cjs.map +1 -1
- package/dist/agents/structured_chat/outputParser.js.map +1 -1
- package/dist/agents/tool_calling/index.cjs.map +1 -1
- package/dist/agents/tool_calling/index.js.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/openai_functions.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/openai_functions.js.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.cjs.map +1 -1
- package/dist/agents/toolkits/conversational_retrieval/tool.js.map +1 -1
- package/dist/agents/toolkits/json/json.cjs.map +1 -1
- package/dist/agents/toolkits/json/json.js.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.cjs.map +1 -1
- package/dist/agents/toolkits/openapi/openapi.js.map +1 -1
- package/dist/agents/toolkits/sql/sql.cjs.map +1 -1
- package/dist/agents/toolkits/sql/sql.js.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.cjs.map +1 -1
- package/dist/agents/toolkits/vectorstore/vectorstore.js.map +1 -1
- package/dist/agents/xml/index.cjs.map +1 -1
- package/dist/agents/xml/index.js.map +1 -1
- package/dist/chains/analyze_documents_chain.cjs.map +1 -1
- package/dist/chains/analyze_documents_chain.js.map +1 -1
- package/dist/chains/api/api_chain.cjs.map +1 -1
- package/dist/chains/api/api_chain.js.map +1 -1
- package/dist/chains/api/prompts.js.map +1 -1
- package/dist/chains/base.cjs.map +1 -1
- package/dist/chains/base.js.map +1 -1
- package/dist/chains/chat_vector_db_chain.cjs.map +1 -1
- package/dist/chains/chat_vector_db_chain.js.map +1 -1
- package/dist/chains/combine_docs_chain.cjs.map +1 -1
- package/dist/chains/combine_docs_chain.js.map +1 -1
- package/dist/chains/combine_documents/base.cjs.map +1 -1
- package/dist/chains/combine_documents/base.js.map +1 -1
- package/dist/chains/combine_documents/reduce.cjs.map +1 -1
- package/dist/chains/combine_documents/reduce.js.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_prompts.cjs.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_prompts.js.map +1 -1
- package/dist/chains/conversational_retrieval_chain.cjs.map +1 -1
- package/dist/chains/conversational_retrieval_chain.js.map +1 -1
- package/dist/chains/graph_qa/cypher.cjs.map +1 -1
- package/dist/chains/graph_qa/cypher.js.map +1 -1
- package/dist/chains/graph_qa/prompts.cjs.map +1 -1
- package/dist/chains/graph_qa/prompts.js.map +1 -1
- package/dist/chains/history_aware_retriever.cjs.map +1 -1
- package/dist/chains/history_aware_retriever.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_functions/base.cjs.map +1 -1
- package/dist/chains/openai_functions/base.js.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/chains/query_constructor/index.cjs.map +1 -1
- package/dist/chains/query_constructor/index.js.map +1 -1
- package/dist/chains/query_constructor/parser.cjs.map +1 -1
- package/dist/chains/query_constructor/parser.js.map +1 -1
- package/dist/chains/query_constructor/prompt.cjs.map +1 -1
- package/dist/chains/query_constructor/prompt.js.map +1 -1
- package/dist/chains/question_answering/load.cjs.map +1 -1
- package/dist/chains/question_answering/load.js.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
- package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/refine_prompts.js.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
- package/dist/chains/retrieval.cjs.map +1 -1
- package/dist/chains/retrieval.js.map +1 -1
- package/dist/chains/router/multi_prompt.cjs.map +1 -1
- package/dist/chains/router/multi_prompt.js.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.cjs.map +1 -1
- package/dist/chains/sql_db/sql_db_chain.js.map +1 -1
- package/dist/chains/summarization/load.cjs.map +1 -1
- package/dist/chains/summarization/load.js.map +1 -1
- package/dist/chains/summarization/refine_prompts.cjs.map +1 -1
- package/dist/chains/summarization/refine_prompts.js.map +1 -1
- package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
- package/dist/chains/summarization/stuff_prompts.js.map +1 -1
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/document_loaders/fs/json.cjs.map +1 -1
- package/dist/document_loaders/fs/json.js.map +1 -1
- package/dist/document_loaders/fs/multi_file.cjs.map +1 -1
- package/dist/document_loaders/fs/multi_file.js.map +1 -1
- package/dist/document_transformers/openai_functions.cjs.map +1 -1
- package/dist/document_transformers/openai_functions.js.map +1 -1
- package/dist/evaluation/agents/prompt.cjs.map +1 -1
- package/dist/evaluation/agents/prompt.js.map +1 -1
- package/dist/evaluation/comparison/pairwise.cjs.map +1 -1
- package/dist/evaluation/comparison/pairwise.js.map +1 -1
- package/dist/evaluation/comparison/prompt.cjs.map +1 -1
- package/dist/evaluation/comparison/prompt.js.map +1 -1
- package/dist/evaluation/criteria/criteria.cjs.map +1 -1
- package/dist/evaluation/criteria/criteria.js.map +1 -1
- package/dist/evaluation/criteria/prompt.cjs.map +1 -1
- package/dist/evaluation/criteria/prompt.js.map +1 -1
- package/dist/evaluation/embedding_distance/base.cjs.map +1 -1
- package/dist/evaluation/embedding_distance/base.js.map +1 -1
- package/dist/evaluation/qa/eval_chain.cjs.map +1 -1
- package/dist/evaluation/qa/eval_chain.js.map +1 -1
- package/dist/evaluation/qa/prompt.cjs.map +1 -1
- package/dist/evaluation/qa/prompt.js.map +1 -1
- package/dist/experimental/autogpt/agent.cjs.map +1 -1
- package/dist/experimental/autogpt/agent.js.map +1 -1
- package/dist/experimental/autogpt/prompt.cjs.map +1 -1
- package/dist/experimental/autogpt/prompt.js.map +1 -1
- package/dist/experimental/autogpt/prompt_generator.cjs.map +1 -1
- package/dist/experimental/autogpt/prompt_generator.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/babyagi/task_creation.cjs.map +1 -1
- package/dist/experimental/babyagi/task_creation.js.map +1 -1
- package/dist/experimental/babyagi/task_execution.cjs.map +1 -1
- package/dist/experimental/babyagi/task_execution.js.map +1 -1
- package/dist/experimental/babyagi/task_prioritization.cjs.map +1 -1
- package/dist/experimental/babyagi/task_prioritization.js.map +1 -1
- package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.cjs.map +1 -1
- package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.js.map +1 -1
- package/dist/experimental/generative_agents/generative_agent.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent.js.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.cjs.map +1 -1
- package/dist/experimental/generative_agents/generative_agent_memory.js.map +1 -1
- package/dist/experimental/masking/regex_masking_transformer.cjs.map +1 -1
- package/dist/experimental/masking/regex_masking_transformer.js.map +1 -1
- package/dist/experimental/openai_assistant/index.cjs.map +1 -1
- package/dist/experimental/openai_assistant/index.js.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/agent_executor.js.map +1 -1
- package/dist/experimental/plan_and_execute/base.cjs.map +1 -1
- package/dist/experimental/plan_and_execute/base.js.map +1 -1
- package/dist/experimental/prompts/handlebars.cjs.map +1 -1
- package/dist/experimental/prompts/handlebars.js.map +1 -1
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.js.map +1 -1
- package/dist/memory/buffer_memory.cjs.map +1 -1
- package/dist/memory/buffer_memory.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/buffer_window_memory.cjs.map +1 -1
- package/dist/memory/buffer_window_memory.js.map +1 -1
- package/dist/memory/entity_memory.cjs.map +1 -1
- package/dist/memory/entity_memory.js.map +1 -1
- package/dist/memory/prompt.cjs.map +1 -1
- package/dist/memory/prompt.js.map +1 -1
- package/dist/memory/summary.cjs.map +1 -1
- package/dist/memory/summary.js.map +1 -1
- package/dist/output_parsers/expression.cjs.map +1 -1
- package/dist/output_parsers/expression.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/factory.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/factory.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/identifier_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/identifier_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/property_assignment_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/property_assignment_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/string_literal_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/string_literal_handler.js.map +1 -1
- package/dist/output_parsers/fix.cjs.map +1 -1
- package/dist/output_parsers/fix.js.map +1 -1
- package/dist/output_parsers/http_response.cjs.map +1 -1
- package/dist/output_parsers/http_response.js.map +1 -1
- package/dist/output_parsers/openai_functions.cjs.map +1 -1
- package/dist/output_parsers/openai_functions.js.map +1 -1
- package/dist/output_parsers/openai_tools.cjs.map +1 -1
- package/dist/output_parsers/openai_tools.js.map +1 -1
- package/dist/output_parsers/prompts.cjs.map +1 -1
- package/dist/output_parsers/prompts.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/contextual_compression.cjs.map +1 -1
- package/dist/retrievers/contextual_compression.js.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.cjs.map +1 -1
- package/dist/retrievers/document_compressors/chain_extract.js.map +1 -1
- package/dist/retrievers/ensemble.cjs.map +1 -1
- package/dist/retrievers/ensemble.js.map +1 -1
- package/dist/retrievers/hyde.cjs.map +1 -1
- package/dist/retrievers/hyde.js.map +1 -1
- package/dist/retrievers/multi_query.cjs.map +1 -1
- package/dist/retrievers/multi_query.js.map +1 -1
- package/dist/retrievers/multi_vector.cjs.map +1 -1
- package/dist/retrievers/multi_vector.js.map +1 -1
- package/dist/retrievers/parent_document.cjs.map +1 -1
- package/dist/retrievers/parent_document.js.map +1 -1
- package/dist/retrievers/score_threshold.cjs.map +1 -1
- package/dist/retrievers/score_threshold.js.map +1 -1
- package/dist/smith/runner_utils.cjs.map +1 -1
- package/dist/smith/runner_utils.js.map +1 -1
- package/dist/storage/encoder_backed.cjs.map +1 -1
- package/dist/storage/encoder_backed.js.map +1 -1
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.js.map +1 -1
- package/dist/tools/json.cjs.map +1 -1
- package/dist/tools/json.js.map +1 -1
- package/dist/tools/requests.cjs.map +1 -1
- package/dist/tools/requests.js.map +1 -1
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.js.map +1 -1
- package/dist/tools/sql.cjs.map +1 -1
- package/dist/tools/sql.js.map +1 -1
- package/dist/tools/webbrowser.cjs.map +1 -1
- package/dist/tools/webbrowser.js.map +1 -1
- package/dist/util/hub.cjs.map +1 -1
- package/dist/util/hub.js.map +1 -1
- package/dist/util/load.cjs.map +1 -1
- package/dist/util/load.js.map +1 -1
- package/dist/util/openapi.cjs.map +1 -1
- package/dist/util/openapi.js.map +1 -1
- package/dist/util/sql_utils.cjs.map +1 -1
- package/dist/util/sql_utils.js.map +1 -1
- package/dist/vectorstores/memory.cjs.map +1 -1
- package/dist/vectorstores/memory.js.map +1 -1
- package/package.json +47 -48
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":["TokenTextSplitter"],"sources":["../../../src/experimental/autogpt/agent.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport { Tool } from \"@langchain/core/tools\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport {\n getEmbeddingContextSize,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nimport { AutoGPTOutputParser } from \"./output_parser.js\";\nimport { AutoGPTPrompt } from \"./prompt.js\";\n// import { HumanInputRun } from \"./tools/human/tool\"; // TODO\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\nimport { TokenTextSplitter } from \"../../text_splitter.js\";\n\n/**\n * Interface for the input parameters of the AutoGPT class.\n */\nexport interface AutoGPTInput {\n aiName: string;\n aiRole: string;\n memory: VectorStoreRetrieverInterface;\n humanInTheLoop?: boolean;\n outputParser?: AutoGPTOutputParser;\n maxIterations?: number;\n}\n\n/**\n * Class representing the AutoGPT concept with LangChain primitives. It is\n * designed to be used with a set of tools such as a search tool,\n * write-file tool, and a read-file tool.\n * @example\n * ```typescript\n * const autogpt = AutoGPT.fromLLMAndTools(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * [\n * new ReadFileTool({ store: new InMemoryFileStore() }),\n * new WriteFileTool({ store: new InMemoryFileStore() }),\n * new SerpAPI(\"YOUR_SERPAPI_API_KEY\", {\n * location: \"San Francisco,California,United States\",\n * hl: \"en\",\n * gl: \"us\",\n * }),\n * ],\n * {\n * memory: new MemoryVectorStore(new OpenAIEmbeddings()).asRetriever(),\n * aiName: \"Tom\",\n * aiRole: \"Assistant\",\n * },\n * );\n * const result = await autogpt.run([\"write a weather report for SF today\"]);\n * ```\n */\nexport class AutoGPT {\n aiName: string;\n\n memory: VectorStoreRetrieverInterface;\n\n fullMessageHistory: BaseMessage[];\n\n nextActionCount: number;\n\n chain: LLMChain;\n\n outputParser: AutoGPTOutputParser;\n\n tools: ObjectTool[];\n\n feedbackTool?: Tool;\n\n maxIterations: number;\n\n // Currently not generic enough to support any text splitter.\n textSplitter: TokenTextSplitter;\n\n constructor({\n aiName,\n memory,\n chain,\n outputParser,\n tools,\n feedbackTool,\n maxIterations,\n }: Omit<Required<AutoGPTInput>, \"aiRole\" | \"humanInTheLoop\"> & {\n chain: LLMChain;\n tools: ObjectTool[];\n feedbackTool?: Tool;\n }) {\n this.aiName = aiName;\n this.memory = memory;\n this.fullMessageHistory = [];\n this.nextActionCount = 0;\n this.chain = chain;\n this.outputParser = outputParser;\n this.tools = tools;\n this.feedbackTool = feedbackTool;\n this.maxIterations = maxIterations;\n const chunkSize = getEmbeddingContextSize(\n \"modelName\" in memory.vectorStore.embeddings\n ? (memory.vectorStore.embeddings.modelName as string)\n : undefined\n );\n this.textSplitter = new TokenTextSplitter({\n chunkSize,\n chunkOverlap: Math.round(chunkSize / 10),\n });\n }\n\n /**\n * Creates a new AutoGPT instance from a given LLM and a set of tools.\n * @param llm A BaseChatModel object.\n * @param tools An array of ObjectTool objects.\n * @param options.aiName The name of the AI.\n * @param options.aiRole The role of the AI.\n * @param options.memory A VectorStoreRetriever object that represents the memory of the AI.\n * @param options.maxIterations The maximum number of iterations the AI can perform.\n * @param options.outputParser An AutoGPTOutputParser object that parses the output of the AI.\n * @returns A new instance of the AutoGPT class.\n */\n static fromLLMAndTools(\n llm: BaseChatModel,\n tools: ObjectTool[],\n {\n aiName,\n aiRole,\n memory,\n maxIterations = 100,\n // humanInTheLoop = false,\n outputParser = new AutoGPTOutputParser(),\n }: AutoGPTInput\n ): AutoGPT {\n const prompt = new AutoGPTPrompt({\n aiName,\n aiRole,\n tools,\n tokenCounter: llm.getNumTokens.bind(llm),\n sendTokenLimit: getModelContextSize(\n \"modelName\" in llm ? (llm.modelName as string) : \"gpt2\"\n ),\n });\n // const feedbackTool = humanInTheLoop ? new HumanInputRun() : null;\n const chain = new LLMChain({ llm, prompt });\n return new AutoGPT({\n aiName,\n memory,\n chain,\n outputParser,\n tools,\n // feedbackTool,\n maxIterations,\n });\n }\n\n /**\n * Runs the AI with a given set of goals.\n * @param goals An array of strings representing the goals.\n * @returns A string representing the result of the run or undefined if the maximum number of iterations is reached without a result.\n */\n async run(goals: string[]): Promise<string | undefined> {\n const user_input =\n \"Determine which next command to use, and respond using the format specified above:\";\n let loopCount = 0;\n while (loopCount < this.maxIterations) {\n loopCount += 1;\n\n const { text: assistantReply } = await this.chain.call({\n goals,\n user_input,\n memory: this.memory,\n messages: this.fullMessageHistory,\n });\n\n // Print the assistant reply\n console.log(assistantReply);\n this.fullMessageHistory.push(new HumanMessage(user_input));\n this.fullMessageHistory.push(new AIMessage(assistantReply));\n\n const action = await this.outputParser.parse(assistantReply);\n const tools = this.tools.reduce(\n (acc, tool) => ({ ...acc, [tool.name]: tool }),\n {} as { [key: string]: ObjectTool }\n );\n if (action.name === FINISH_NAME) {\n return action.args.response;\n }\n let result: string;\n if (action.name in tools) {\n const tool = tools[action.name];\n let observation;\n try {\n observation = await tool.call(action.args);\n } catch (e) {\n observation = `Error in args: ${e}`;\n }\n result = `Command ${tool.name} returned: ${observation}`;\n } else if (action.name === \"ERROR\") {\n result = `Error: ${action.args}. `;\n } else {\n result = `Unknown command '${action.name}'. Please refer to the 'COMMANDS' list for available commands and only respond in the specified JSON format.`;\n }\n\n let memoryToAdd = `Assistant Reply: ${assistantReply}\\nResult: ${result} `;\n if (this.feedbackTool) {\n const feedback = `\\n${await this.feedbackTool.call(\"Input: \")}`;\n if (feedback === \"q\" || feedback === \"stop\") {\n console.log(\"EXITING\");\n return \"EXITING\";\n }\n memoryToAdd += feedback;\n }\n\n const documents = await this.textSplitter.createDocuments([memoryToAdd]);\n await this.memory.addDocuments(documents);\n this.fullMessageHistory.push(new SystemMessage(result));\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAa,UAAb,MAAa,QAAQ;CACnB;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAGA;CAEA,YAAY,EACV,QACA,QACA,OACA,cACA,OACA,cACA,iBAKC;AACD,OAAK,SAAS;AACd,OAAK,SAAS;AACd,OAAK,qBAAqB,EAAE;AAC5B,OAAK,kBAAkB;AACvB,OAAK,QAAQ;AACb,OAAK,eAAe;AACpB,OAAK,QAAQ;AACb,OAAK,eAAe;AACpB,OAAK,gBAAgB;EACrB,MAAM,YAAY,wBAChB,eAAe,OAAO,YAAY,aAC7B,OAAO,YAAY,WAAW,YAC/B,KAAA,EACL;AACD,OAAK,eAAe,IAAIA,sBAAAA,kBAAkB;GACxC;GACA,cAAc,KAAK,MAAM,YAAY,GAAG;GACzC,CAAC;;;;;;;;;;;;;CAcJ,OAAO,gBACL,KACA,OACA,EACE,QACA,QACA,QACA,gBAAgB,KAEhB,eAAe,IAAI,qBAAqB,IAEjC;AAYT,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,
|
|
1
|
+
{"version":3,"file":"agent.js","names":["TokenTextSplitter"],"sources":["../../../src/experimental/autogpt/agent.ts"],"sourcesContent":["import type { VectorStoreRetrieverInterface } from \"@langchain/core/vectorstores\";\nimport { Tool } from \"@langchain/core/tools\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport {\n getEmbeddingContextSize,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport { LLMChain } from \"../../chains/llm_chain.js\";\n\nimport { AutoGPTOutputParser } from \"./output_parser.js\";\nimport { AutoGPTPrompt } from \"./prompt.js\";\n// import { HumanInputRun } from \"./tools/human/tool\"; // TODO\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\nimport { TokenTextSplitter } from \"../../text_splitter.js\";\n\n/**\n * Interface for the input parameters of the AutoGPT class.\n */\nexport interface AutoGPTInput {\n aiName: string;\n aiRole: string;\n memory: VectorStoreRetrieverInterface;\n humanInTheLoop?: boolean;\n outputParser?: AutoGPTOutputParser;\n maxIterations?: number;\n}\n\n/**\n * Class representing the AutoGPT concept with LangChain primitives. It is\n * designed to be used with a set of tools such as a search tool,\n * write-file tool, and a read-file tool.\n * @example\n * ```typescript\n * const autogpt = AutoGPT.fromLLMAndTools(\n * new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0 }),\n * [\n * new ReadFileTool({ store: new InMemoryFileStore() }),\n * new WriteFileTool({ store: new InMemoryFileStore() }),\n * new SerpAPI(\"YOUR_SERPAPI_API_KEY\", {\n * location: \"San Francisco,California,United States\",\n * hl: \"en\",\n * gl: \"us\",\n * }),\n * ],\n * {\n * memory: new MemoryVectorStore(new OpenAIEmbeddings()).asRetriever(),\n * aiName: \"Tom\",\n * aiRole: \"Assistant\",\n * },\n * );\n * const result = await autogpt.run([\"write a weather report for SF today\"]);\n * ```\n */\nexport class AutoGPT {\n aiName: string;\n\n memory: VectorStoreRetrieverInterface;\n\n fullMessageHistory: BaseMessage[];\n\n nextActionCount: number;\n\n chain: LLMChain;\n\n outputParser: AutoGPTOutputParser;\n\n tools: ObjectTool[];\n\n feedbackTool?: Tool;\n\n maxIterations: number;\n\n // Currently not generic enough to support any text splitter.\n textSplitter: TokenTextSplitter;\n\n constructor({\n aiName,\n memory,\n chain,\n outputParser,\n tools,\n feedbackTool,\n maxIterations,\n }: Omit<Required<AutoGPTInput>, \"aiRole\" | \"humanInTheLoop\"> & {\n chain: LLMChain;\n tools: ObjectTool[];\n feedbackTool?: Tool;\n }) {\n this.aiName = aiName;\n this.memory = memory;\n this.fullMessageHistory = [];\n this.nextActionCount = 0;\n this.chain = chain;\n this.outputParser = outputParser;\n this.tools = tools;\n this.feedbackTool = feedbackTool;\n this.maxIterations = maxIterations;\n const chunkSize = getEmbeddingContextSize(\n \"modelName\" in memory.vectorStore.embeddings\n ? (memory.vectorStore.embeddings.modelName as string)\n : undefined\n );\n this.textSplitter = new TokenTextSplitter({\n chunkSize,\n chunkOverlap: Math.round(chunkSize / 10),\n });\n }\n\n /**\n * Creates a new AutoGPT instance from a given LLM and a set of tools.\n * @param llm A BaseChatModel object.\n * @param tools An array of ObjectTool objects.\n * @param options.aiName The name of the AI.\n * @param options.aiRole The role of the AI.\n * @param options.memory A VectorStoreRetriever object that represents the memory of the AI.\n * @param options.maxIterations The maximum number of iterations the AI can perform.\n * @param options.outputParser An AutoGPTOutputParser object that parses the output of the AI.\n * @returns A new instance of the AutoGPT class.\n */\n static fromLLMAndTools(\n llm: BaseChatModel,\n tools: ObjectTool[],\n {\n aiName,\n aiRole,\n memory,\n maxIterations = 100,\n // humanInTheLoop = false,\n outputParser = new AutoGPTOutputParser(),\n }: AutoGPTInput\n ): AutoGPT {\n const prompt = new AutoGPTPrompt({\n aiName,\n aiRole,\n tools,\n tokenCounter: llm.getNumTokens.bind(llm),\n sendTokenLimit: getModelContextSize(\n \"modelName\" in llm ? (llm.modelName as string) : \"gpt2\"\n ),\n });\n // const feedbackTool = humanInTheLoop ? new HumanInputRun() : null;\n const chain = new LLMChain({ llm, prompt });\n return new AutoGPT({\n aiName,\n memory,\n chain,\n outputParser,\n tools,\n // feedbackTool,\n maxIterations,\n });\n }\n\n /**\n * Runs the AI with a given set of goals.\n * @param goals An array of strings representing the goals.\n * @returns A string representing the result of the run or undefined if the maximum number of iterations is reached without a result.\n */\n async run(goals: string[]): Promise<string | undefined> {\n const user_input =\n \"Determine which next command to use, and respond using the format specified above:\";\n let loopCount = 0;\n while (loopCount < this.maxIterations) {\n loopCount += 1;\n\n const { text: assistantReply } = await this.chain.call({\n goals,\n user_input,\n memory: this.memory,\n messages: this.fullMessageHistory,\n });\n\n // Print the assistant reply\n console.log(assistantReply);\n this.fullMessageHistory.push(new HumanMessage(user_input));\n this.fullMessageHistory.push(new AIMessage(assistantReply));\n\n const action = await this.outputParser.parse(assistantReply);\n const tools = this.tools.reduce(\n (acc, tool) => ({ ...acc, [tool.name]: tool }),\n {} as { [key: string]: ObjectTool }\n );\n if (action.name === FINISH_NAME) {\n return action.args.response;\n }\n let result: string;\n if (action.name in tools) {\n const tool = tools[action.name];\n let observation;\n try {\n observation = await tool.call(action.args);\n } catch (e) {\n observation = `Error in args: ${e}`;\n }\n result = `Command ${tool.name} returned: ${observation}`;\n } else if (action.name === \"ERROR\") {\n result = `Error: ${action.args}. `;\n } else {\n result = `Unknown command '${action.name}'. Please refer to the 'COMMANDS' list for available commands and only respond in the specified JSON format.`;\n }\n\n let memoryToAdd = `Assistant Reply: ${assistantReply}\\nResult: ${result} `;\n if (this.feedbackTool) {\n const feedback = `\\n${await this.feedbackTool.call(\"Input: \")}`;\n if (feedback === \"q\" || feedback === \"stop\") {\n console.log(\"EXITING\");\n return \"EXITING\";\n }\n memoryToAdd += feedback;\n }\n\n const documents = await this.textSplitter.createDocuments([memoryToAdd]);\n await this.memory.addDocuments(documents);\n this.fullMessageHistory.push(new SystemMessage(result));\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAa,UAAb,MAAa,QAAQ;CACnB;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAGA;CAEA,YAAY,EACV,QACA,QACA,OACA,cACA,OACA,cACA,iBAKC;AACD,OAAK,SAAS;AACd,OAAK,SAAS;AACd,OAAK,qBAAqB,EAAE;AAC5B,OAAK,kBAAkB;AACvB,OAAK,QAAQ;AACb,OAAK,eAAe;AACpB,OAAK,QAAQ;AACb,OAAK,eAAe;AACpB,OAAK,gBAAgB;EACrB,MAAM,YAAY,wBAChB,eAAe,OAAO,YAAY,aAC7B,OAAO,YAAY,WAAW,YAC/B,KAAA,EACL;AACD,OAAK,eAAe,IAAIA,sBAAAA,kBAAkB;GACxC;GACA,cAAc,KAAK,MAAM,YAAY,GAAG;GACzC,CAAC;;;;;;;;;;;;;CAcJ,OAAO,gBACL,KACA,OACA,EACE,QACA,QACA,QACA,gBAAgB,KAEhB,eAAe,IAAI,qBAAqB,IAEjC;AAYT,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,OAAA,IAJgB,SAAS;IAAE;I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BAAe;;GAGjB,MAAM,YAAY,MAAM,KAAK,aAAa,gBAAgB,CAAC,YAAY,CAAC;AACxE,SAAM,KAAK,OAAO,aAAa,UAAU;AACzC,QAAK,mBAAmB,KAAK,IAAI,cAAc,OAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","names":["BaseChatPromptTemplate","getPrompt","SystemMessage","HumanMessage"],"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,cACUA,wBAAAA,uBAEV;CACE;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,QAA4B;AACtC,QAAM,EAAE,gBAAgB;GAAC;GAAS;GAAU;GAAY;GAAa,EAAE,CAAC;AACxE,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS,OAAO;AACrB,OAAK,QAAQ,OAAO;AACpB,OAAK,eAAe,OAAO;AAC3B,OAAK,iBAAiB,OAAO,kBAAkB;;CAGjD,iBAAiB;AACf,SAAO;;;;;;;CAQT,oBAAoB,OAAyB;EAO3C,IAAI,aAAa,WAAW,KAAK,OAAO,IAAI,KAAK,OAAO;;;;;AACxD,QAAM,SAAS,MAAM,UAAU;AAC7B,iBAAc,GAAG,QAAQ,EAAE,IAAI,KAAK;IACpC;AAEF,gBAAc,OAAOC,yBAAAA,UAAU,KAAK,MAAM;AAC1C,SAAO;;;;;;;;;;CAWT,MAAM,eAAe,EACnB,OACA,QACA,UAAU,kBACV,cAMC;EACD,MAAM,aAAa,IAAIC,yBAAAA,cAAc,KAAK,oBAAoB,MAAM,CAAC;EACrE,MAAM,aAAa,IAAIA,yBAAAA,cACrB,iDAAgC,IAAI,MAAM,EAAC,eAAe,QAAQ,GACnE;AACD,MACE,OAAO,WAAW,YAAY,YAC9B,OAAO,WAAW,YAAY,SAE9B,OAAM,IAAI,MAAM,+CAA+C;EAEjE,MAAM,aACH,MAAM,KAAK,aAAa,WAAW,QAAQ,GAC3C,MAAM,KAAK,aAAa,WAAW,QAAQ;EAI9C,MAAM,
|
|
1
|
+
{"version":3,"file":"prompt.cjs","names":["BaseChatPromptTemplate","getPrompt","SystemMessage","HumanMessage"],"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,cACUA,wBAAAA,uBAEV;CACE;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,QAA4B;AACtC,QAAM,EAAE,gBAAgB;GAAC;GAAS;GAAU;GAAY;GAAa,EAAE,CAAC;AACxE,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS,OAAO;AACrB,OAAK,QAAQ,OAAO;AACpB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AY,SACnC,OAAM,IAAI,MAAM,+CAA+C;EAEjE,MAAM,uBACJ,aAAc,MAAM,KAAK,aAAa,cAAc,QAAQ;EAC9D,MAAM,qBAAoC,EAAE;AAE5C,OAAK,MAAM,WAAW,iBAAiB,MAAM,IAAI,CAAC,SAAS,EAAE;AAC3D,OAAI,OAAO,QAAQ,YAAY,SAC7B,OAAM,IAAI,MAAM,+CAA+C;AAGjE,OAAI,uBAAuB,MADC,KAAK,aAAa,QAAQ,QAAQ,GACnB,KAAK,iBAAiB,IAC/D;AAEF,sBAAmB,QAAQ,QAAQ;;EAGrC,MAAM,eAAe,IAAIC,yBAAAA,aAAa,WAAW;AAQjD,SAAO;GANL;GACA;GACA;GACA,GAAG;GACH;GAEa;;;;;;;;CASjB,MAAM,QAAQ,SAAyD;AACrE,QAAM,IAAI,MAAM,0BAA0B;;CAG5C,YAA0C;AACxC,QAAM,IAAI,MAAM,0BAA0B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","names":[],"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,YAAY,QAA4B;AACtC,QAAM,EAAE,gBAAgB;GAAC;GAAS;GAAU;GAAY;GAAa,EAAE,CAAC;AACxE,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS,OAAO;AACrB,OAAK,QAAQ,OAAO;AACpB,OAAK,eAAe,OAAO;AAC3B,OAAK,iBAAiB,OAAO,kBAAkB;;CAGjD,iBAAiB;AACf,SAAO;;;;;;;CAQT,oBAAoB,OAAyB;EAO3C,IAAI,aAAa,WAAW,KAAK,OAAO,IAAI,KAAK,OAAO;;;;;AACxD,QAAM,SAAS,MAAM,UAAU;AAC7B,iBAAc,GAAG,QAAQ,EAAE,IAAI,KAAK;IACpC;AAEF,gBAAc,OAAO,UAAU,KAAK,MAAM;AAC1C,SAAO;;;;;;;;;;CAWT,MAAM,eAAe,EACnB,OACA,QACA,UAAU,kBACV,cAMC;EACD,MAAM,aAAa,IAAI,cAAc,KAAK,oBAAoB,MAAM,CAAC;EACrE,MAAM,aAAa,IAAI,cACrB,iDAAgC,IAAI,MAAM,EAAC,eAAe,QAAQ,GACnE;AACD,MACE,OAAO,WAAW,YAAY,YAC9B,OAAO,WAAW,YAAY,SAE9B,OAAM,IAAI,MAAM,+CAA+C;EAEjE,MAAM,aACH,MAAM,KAAK,aAAa,WAAW,QAAQ,GAC3C,MAAM,KAAK,aAAa,WAAW,QAAQ;EAI9C,MAAM,
|
|
1
|
+
{"version":3,"file":"prompt.js","names":[],"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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AAC/C,kBAAe,KAAK;AACpB,0BAAuB,MAAM,eAAe,OAC1C,OAAO,KAAsB,QAC1B,MAAM,MAAQ,MAAM,KAAK,aAAa,IAAI,EAC7C,QAAQ,QAAQ,EAAE,CACnB;;EAMH,MAAM,gBAAgB,IAAI,cAAc,qDAHmC,eAAe,KACxF,KACD,CAAC,MACoD;AACtD,MAAI,OAAO,cAAc,YAAY,SACnC,OAAM,IAAI,MAAM,+CAA+C;EAEjE,MAAM,uBACJ,aAAc,MAAM,KAAK,aAAa,cAAc,QAAQ;EAC9D,MAAM,qBAAoC,EAAE;AAE5C,OAAK,MAAM,WAAW,iBAAiB,MAAM,IAAI,CAAC,SAAS,EAAE;AAC3D,OAAI,OAAO,QAAQ,YAAY,SAC7B,OAAM,IAAI,MAAM,+CAA+C;AAGjE,OAAI,uBAAuB,MADC,KAAK,aAAa,QAAQ,QAAQ,GACnB,KAAK,iBAAiB,IAC/D;AAEF,sBAAmB,QAAQ,QAAQ;;EAGrC,MAAM,eAAe,IAAI,aAAa,WAAW;AAQjD,SAAO;GANL;GACA;GACA;GACA,GAAG;GACH;GAEa;;;;;;;;CASjB,MAAM,QAAQ,SAAyD;AACrE,QAAM,IAAI,MAAM,0BAA0B;;CAG5C,YAA0C;AACxC,QAAM,IAAI,MAAM,0BAA0B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt_generator.cjs","names":["FINISH_NAME"],"sources":["../../../src/experimental/autogpt/prompt_generator.ts"],"sourcesContent":["import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\n\n/**\n * Class that generates prompts for generative agents. It maintains a list\n * of constraints, commands, resources, and performance evaluations.\n */\nexport class PromptGenerator {\n constraints: string[];\n\n commands: ObjectTool[];\n\n resources: string[];\n\n performance_evaluation: string[];\n\n response_format: object;\n\n constructor() {\n this.constraints = [];\n this.commands = [];\n this.resources = [];\n this.performance_evaluation = [];\n this.response_format = {\n thoughts: {\n text: \"thought\",\n reasoning: \"reasoning\",\n plan: \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n criticism: \"constructive self-criticism\",\n speak: \"thoughts summary to say to user\",\n },\n command: { name: \"command name\", args: { \"arg name\": \"value\" } },\n };\n }\n\n /**\n * Adds a constraint to the list of constraints.\n * @param constraint The constraint to add.\n * @returns void\n */\n add_constraint(constraint: string): void {\n this.constraints.push(constraint);\n }\n\n /**\n * Adds a tool to the list of commands.\n * @param tool The tool to add.\n * @returns void\n */\n add_tool(tool: ObjectTool): void {\n this.commands.push(tool);\n }\n\n _generate_command_string(tool: ObjectTool): string {\n let output = `\"${tool.name}\": ${tool.description}`;\n const jsonSchema = (\n isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n output += `, args json schema: ${JSON.stringify(jsonSchema?.properties)}`;\n return output;\n }\n\n /**\n * Adds a resource to the list of resources.\n * @param resource The resource to add.\n * @returns void\n */\n add_resource(resource: string): void {\n this.resources.push(resource);\n }\n\n /**\n * Adds a performance evaluation to the list of performance evaluations.\n * @param evaluation The performance evaluation to add.\n * @returns void\n */\n add_performance_evaluation(evaluation: string): void {\n this.performance_evaluation.push(evaluation);\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _generate_numbered_list(items: any[], item_type = \"list\"): string {\n if (item_type === \"command\") {\n const command_strings = items.map(\n (item, i) => `${i + 1}. ${this._generate_command_string(item)}`\n );\n const finish_description =\n \"use this to signal that you have finished all your objectives\";\n const finish_args =\n '\"response\": \"final response to let people know you have finished your objectives\"';\n const finish_string = `${\n items.length + 1\n }. ${FINISH_NAME}: ${finish_description}, args: ${finish_args}`;\n return command_strings.concat([finish_string]).join(\"\\n\");\n }\n\n return items.map((item, i) => `${i + 1}. ${item}`).join(\"\\n\");\n }\n\n /**\n * Generates a prompt string that includes the constraints, commands,\n * resources, performance evaluations, and response format.\n * @returns A string representing the prompt.\n */\n generate_prompt_string(): string {\n const formatted_response_format = JSON.stringify(\n this.response_format,\n null,\n 4\n );\n const prompt_string =\n `Constraints:\\n${this._generate_numbered_list(this.constraints)}\\n\\n` +\n `Commands:\\n${this._generate_numbered_list(\n this.commands,\n \"command\"\n )}\\n\\n` +\n `Resources:\\n${this._generate_numbered_list(this.resources)}\\n\\n` +\n `Performance Evaluation:\\n${this._generate_numbered_list(\n this.performance_evaluation\n )}\\n\\n` +\n `You should only respond in JSON format as described below ` +\n `\\nResponse Format: \\n${formatted_response_format} ` +\n `\\nEnsure the response can be parsed by Python json.loads`;\n\n return prompt_string;\n }\n}\n\n/**\n * Function that generates a prompt string for a given list of tools.\n */\nexport function getPrompt(tools: ObjectTool[]): string {\n const prompt_generator = new PromptGenerator();\n\n prompt_generator.add_constraint(\n \"~4000 word limit for short term memory. \" +\n \"Your short term memory is short, \" +\n \"so immediately save important information to files.\"\n );\n prompt_generator.add_constraint(\n \"If you are unsure how you previously did something \" +\n \"or want to recall past events, \" +\n \"thinking about similar events will help you remember.\"\n );\n prompt_generator.add_constraint(\"No user assistance\");\n prompt_generator.add_constraint(\n 'Exclusively use the commands listed in double quotes e.g. \"command name\"'\n );\n\n for (const tool of tools) {\n prompt_generator.add_tool(tool);\n }\n\n prompt_generator.add_resource(\n \"Internet access for searches and information gathering.\"\n );\n prompt_generator.add_resource(\"Long Term memory management.\");\n prompt_generator.add_resource(\n \"GPT-3.5 powered Agents for delegation of simple tasks.\"\n );\n prompt_generator.add_resource(\"File output.\");\n\n prompt_generator.add_performance_evaluation(\n \"Continuously review and analyze your actions \" +\n \"to ensure you are performing to the best of your abilities.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Constructively self-criticize your big-picture behavior constantly.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Reflect on past decisions and strategies to refine your approach.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Every command has a cost, so be smart and efficient. \" +\n \"Aim to complete tasks in the least number of steps.\"\n );\n\n const prompt_string = prompt_generator.generate_prompt_string();\n\n return prompt_string;\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,kBAAb,MAA6B;CAC3B;CAEA;CAEA;CAEA;CAEA;CAEA,cAAc;AACZ,OAAK,cAAc,EAAE;AACrB,OAAK,WAAW,EAAE;AAClB,OAAK,YAAY,EAAE;AACnB,OAAK,yBAAyB,EAAE;AAChC,OAAK,kBAAkB;GACrB,UAAU;IACR,MAAM;IACN,WAAW;IACX,MAAM;IACN,WAAW;IACX,OAAO;IACR;GACD,SAAS;IAAE,MAAM;IAAgB,MAAM,EAAE,YAAY,SAAS;IAAE;GACjE;;;;;;;CAQH,eAAe,YAA0B;AACvC,OAAK,YAAY,KAAK,WAAW;;;;;;;CAQnC,SAAS,MAAwB;AAC/B,OAAK,SAAS,KAAK,KAAK;;CAG1B,yBAAyB,MAA0B;EACjD,IAAI,SAAS,IAAI,KAAK,KAAK,KAAK,KAAK;EACrC,MAAM,cAAA,GAAA,4BAAA,oBACe,KAAK,OAAO,IAAA,GAAA,kCAAA,cAAgB,KAAK,OAAO,GAAG,KAAK;AAErE,YAAU,uBAAuB,KAAK,UAAU,YAAY,WAAW;AACvE,SAAO;;;;;;;CAQT,aAAa,UAAwB;AACnC,OAAK,UAAU,KAAK,SAAS;;;;;;;CAQ/B,2BAA2B,YAA0B;AACnD,OAAK,uBAAuB,KAAK,WAAW;;CAI9C,wBAAwB,OAAc,YAAY,QAAgB;AAChE,MAAI,cAAc,WAAW;GAC3B,MAAM,kBAAkB,MAAM,KAC3B,MAAM,MAAM,GAAG,IAAI,EAAE,IAAI,KAAK,yBAAyB,KAAK,GAC9D;GAKD,MAAM,gBAAgB,GACpB,MAAM,SAAS,EAChB,IAAIA,eAAAA,YAAY;AACjB,UAAO,gBAAgB,OAAO,CAAC,cAAc,CAAC,CAAC,KAAK,KAAK;;AAG3D,SAAO,MAAM,KAAK,MAAM,MAAM,GAAG,IAAI,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK;;;;;;;CAQ/D,yBAAiC;EAC/B,MAAM,4BAA4B,KAAK,UACrC,KAAK,iBACL,MACA,EACD;AAeD,
|
|
1
|
+
{"version":3,"file":"prompt_generator.cjs","names":["FINISH_NAME"],"sources":["../../../src/experimental/autogpt/prompt_generator.ts"],"sourcesContent":["import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\n\n/**\n * Class that generates prompts for generative agents. It maintains a list\n * of constraints, commands, resources, and performance evaluations.\n */\nexport class PromptGenerator {\n constraints: string[];\n\n commands: ObjectTool[];\n\n resources: string[];\n\n performance_evaluation: string[];\n\n response_format: object;\n\n constructor() {\n this.constraints = [];\n this.commands = [];\n this.resources = [];\n this.performance_evaluation = [];\n this.response_format = {\n thoughts: {\n text: \"thought\",\n reasoning: \"reasoning\",\n plan: \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n criticism: \"constructive self-criticism\",\n speak: \"thoughts summary to say to user\",\n },\n command: { name: \"command name\", args: { \"arg name\": \"value\" } },\n };\n }\n\n /**\n * Adds a constraint to the list of constraints.\n * @param constraint The constraint to add.\n * @returns void\n */\n add_constraint(constraint: string): void {\n this.constraints.push(constraint);\n }\n\n /**\n * Adds a tool to the list of commands.\n * @param tool The tool to add.\n * @returns void\n */\n add_tool(tool: ObjectTool): void {\n this.commands.push(tool);\n }\n\n _generate_command_string(tool: ObjectTool): string {\n let output = `\"${tool.name}\": ${tool.description}`;\n const jsonSchema = (\n isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n output += `, args json schema: ${JSON.stringify(jsonSchema?.properties)}`;\n return output;\n }\n\n /**\n * Adds a resource to the list of resources.\n * @param resource The resource to add.\n * @returns void\n */\n add_resource(resource: string): void {\n this.resources.push(resource);\n }\n\n /**\n * Adds a performance evaluation to the list of performance evaluations.\n * @param evaluation The performance evaluation to add.\n * @returns void\n */\n add_performance_evaluation(evaluation: string): void {\n this.performance_evaluation.push(evaluation);\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _generate_numbered_list(items: any[], item_type = \"list\"): string {\n if (item_type === \"command\") {\n const command_strings = items.map(\n (item, i) => `${i + 1}. ${this._generate_command_string(item)}`\n );\n const finish_description =\n \"use this to signal that you have finished all your objectives\";\n const finish_args =\n '\"response\": \"final response to let people know you have finished your objectives\"';\n const finish_string = `${\n items.length + 1\n }. ${FINISH_NAME}: ${finish_description}, args: ${finish_args}`;\n return command_strings.concat([finish_string]).join(\"\\n\");\n }\n\n return items.map((item, i) => `${i + 1}. ${item}`).join(\"\\n\");\n }\n\n /**\n * Generates a prompt string that includes the constraints, commands,\n * resources, performance evaluations, and response format.\n * @returns A string representing the prompt.\n */\n generate_prompt_string(): string {\n const formatted_response_format = JSON.stringify(\n this.response_format,\n null,\n 4\n );\n const prompt_string =\n `Constraints:\\n${this._generate_numbered_list(this.constraints)}\\n\\n` +\n `Commands:\\n${this._generate_numbered_list(\n this.commands,\n \"command\"\n )}\\n\\n` +\n `Resources:\\n${this._generate_numbered_list(this.resources)}\\n\\n` +\n `Performance Evaluation:\\n${this._generate_numbered_list(\n this.performance_evaluation\n )}\\n\\n` +\n `You should only respond in JSON format as described below ` +\n `\\nResponse Format: \\n${formatted_response_format} ` +\n `\\nEnsure the response can be parsed by Python json.loads`;\n\n return prompt_string;\n }\n}\n\n/**\n * Function that generates a prompt string for a given list of tools.\n */\nexport function getPrompt(tools: ObjectTool[]): string {\n const prompt_generator = new PromptGenerator();\n\n prompt_generator.add_constraint(\n \"~4000 word limit for short term memory. \" +\n \"Your short term memory is short, \" +\n \"so immediately save important information to files.\"\n );\n prompt_generator.add_constraint(\n \"If you are unsure how you previously did something \" +\n \"or want to recall past events, \" +\n \"thinking about similar events will help you remember.\"\n );\n prompt_generator.add_constraint(\"No user assistance\");\n prompt_generator.add_constraint(\n 'Exclusively use the commands listed in double quotes e.g. \"command name\"'\n );\n\n for (const tool of tools) {\n prompt_generator.add_tool(tool);\n }\n\n prompt_generator.add_resource(\n \"Internet access for searches and information gathering.\"\n );\n prompt_generator.add_resource(\"Long Term memory management.\");\n prompt_generator.add_resource(\n \"GPT-3.5 powered Agents for delegation of simple tasks.\"\n );\n prompt_generator.add_resource(\"File output.\");\n\n prompt_generator.add_performance_evaluation(\n \"Continuously review and analyze your actions \" +\n \"to ensure you are performing to the best of your abilities.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Constructively self-criticize your big-picture behavior constantly.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Reflect on past decisions and strategies to refine your approach.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Every command has a cost, so be smart and efficient. \" +\n \"Aim to complete tasks in the least number of steps.\"\n );\n\n const prompt_string = prompt_generator.generate_prompt_string();\n\n return prompt_string;\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,kBAAb,MAA6B;CAC3B;CAEA;CAEA;CAEA;CAEA;CAEA,cAAc;AACZ,OAAK,cAAc,EAAE;AACrB,OAAK,WAAW,EAAE;AAClB,OAAK,YAAY,EAAE;AACnB,OAAK,yBAAyB,EAAE;AAChC,OAAK,kBAAkB;GACrB,UAAU;IACR,MAAM;IACN,WAAW;IACX,MAAM;IACN,WAAW;IACX,OAAO;IACR;GACD,SAAS;IAAE,MAAM;IAAgB,MAAM,EAAE,YAAY,SAAS;IAAE;GACjE;;;;;;;CAQH,eAAe,YAA0B;AACvC,OAAK,YAAY,KAAK,WAAW;;;;;;;CAQnC,SAAS,MAAwB;AAC/B,OAAK,SAAS,KAAK,KAAK;;CAG1B,yBAAyB,MAA0B;EACjD,IAAI,SAAS,IAAI,KAAK,KAAK,KAAK,KAAK;EACrC,MAAM,cAAA,GAAA,4BAAA,oBACe,KAAK,OAAO,IAAA,GAAA,kCAAA,cAAgB,KAAK,OAA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ACf,oEACD;AACD,kBAAiB,2BACf,2GAED;AAID,QAFsB,iBAAiB,wBAEnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt_generator.js","names":[],"sources":["../../../src/experimental/autogpt/prompt_generator.ts"],"sourcesContent":["import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\n\n/**\n * Class that generates prompts for generative agents. It maintains a list\n * of constraints, commands, resources, and performance evaluations.\n */\nexport class PromptGenerator {\n constraints: string[];\n\n commands: ObjectTool[];\n\n resources: string[];\n\n performance_evaluation: string[];\n\n response_format: object;\n\n constructor() {\n this.constraints = [];\n this.commands = [];\n this.resources = [];\n this.performance_evaluation = [];\n this.response_format = {\n thoughts: {\n text: \"thought\",\n reasoning: \"reasoning\",\n plan: \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n criticism: \"constructive self-criticism\",\n speak: \"thoughts summary to say to user\",\n },\n command: { name: \"command name\", args: { \"arg name\": \"value\" } },\n };\n }\n\n /**\n * Adds a constraint to the list of constraints.\n * @param constraint The constraint to add.\n * @returns void\n */\n add_constraint(constraint: string): void {\n this.constraints.push(constraint);\n }\n\n /**\n * Adds a tool to the list of commands.\n * @param tool The tool to add.\n * @returns void\n */\n add_tool(tool: ObjectTool): void {\n this.commands.push(tool);\n }\n\n _generate_command_string(tool: ObjectTool): string {\n let output = `\"${tool.name}\": ${tool.description}`;\n const jsonSchema = (\n isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n output += `, args json schema: ${JSON.stringify(jsonSchema?.properties)}`;\n return output;\n }\n\n /**\n * Adds a resource to the list of resources.\n * @param resource The resource to add.\n * @returns void\n */\n add_resource(resource: string): void {\n this.resources.push(resource);\n }\n\n /**\n * Adds a performance evaluation to the list of performance evaluations.\n * @param evaluation The performance evaluation to add.\n * @returns void\n */\n add_performance_evaluation(evaluation: string): void {\n this.performance_evaluation.push(evaluation);\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _generate_numbered_list(items: any[], item_type = \"list\"): string {\n if (item_type === \"command\") {\n const command_strings = items.map(\n (item, i) => `${i + 1}. ${this._generate_command_string(item)}`\n );\n const finish_description =\n \"use this to signal that you have finished all your objectives\";\n const finish_args =\n '\"response\": \"final response to let people know you have finished your objectives\"';\n const finish_string = `${\n items.length + 1\n }. ${FINISH_NAME}: ${finish_description}, args: ${finish_args}`;\n return command_strings.concat([finish_string]).join(\"\\n\");\n }\n\n return items.map((item, i) => `${i + 1}. ${item}`).join(\"\\n\");\n }\n\n /**\n * Generates a prompt string that includes the constraints, commands,\n * resources, performance evaluations, and response format.\n * @returns A string representing the prompt.\n */\n generate_prompt_string(): string {\n const formatted_response_format = JSON.stringify(\n this.response_format,\n null,\n 4\n );\n const prompt_string =\n `Constraints:\\n${this._generate_numbered_list(this.constraints)}\\n\\n` +\n `Commands:\\n${this._generate_numbered_list(\n this.commands,\n \"command\"\n )}\\n\\n` +\n `Resources:\\n${this._generate_numbered_list(this.resources)}\\n\\n` +\n `Performance Evaluation:\\n${this._generate_numbered_list(\n this.performance_evaluation\n )}\\n\\n` +\n `You should only respond in JSON format as described below ` +\n `\\nResponse Format: \\n${formatted_response_format} ` +\n `\\nEnsure the response can be parsed by Python json.loads`;\n\n return prompt_string;\n }\n}\n\n/**\n * Function that generates a prompt string for a given list of tools.\n */\nexport function getPrompt(tools: ObjectTool[]): string {\n const prompt_generator = new PromptGenerator();\n\n prompt_generator.add_constraint(\n \"~4000 word limit for short term memory. \" +\n \"Your short term memory is short, \" +\n \"so immediately save important information to files.\"\n );\n prompt_generator.add_constraint(\n \"If you are unsure how you previously did something \" +\n \"or want to recall past events, \" +\n \"thinking about similar events will help you remember.\"\n );\n prompt_generator.add_constraint(\"No user assistance\");\n prompt_generator.add_constraint(\n 'Exclusively use the commands listed in double quotes e.g. \"command name\"'\n );\n\n for (const tool of tools) {\n prompt_generator.add_tool(tool);\n }\n\n prompt_generator.add_resource(\n \"Internet access for searches and information gathering.\"\n );\n prompt_generator.add_resource(\"Long Term memory management.\");\n prompt_generator.add_resource(\n \"GPT-3.5 powered Agents for delegation of simple tasks.\"\n );\n prompt_generator.add_resource(\"File output.\");\n\n prompt_generator.add_performance_evaluation(\n \"Continuously review and analyze your actions \" +\n \"to ensure you are performing to the best of your abilities.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Constructively self-criticize your big-picture behavior constantly.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Reflect on past decisions and strategies to refine your approach.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Every command has a cost, so be smart and efficient. \" +\n \"Aim to complete tasks in the least number of steps.\"\n );\n\n const prompt_string = prompt_generator.generate_prompt_string();\n\n return prompt_string;\n}\n"],"mappings":";;;;;;;;AAWA,IAAa,kBAAb,MAA6B;CAC3B;CAEA;CAEA;CAEA;CAEA;CAEA,cAAc;AACZ,OAAK,cAAc,EAAE;AACrB,OAAK,WAAW,EAAE;AAClB,OAAK,YAAY,EAAE;AACnB,OAAK,yBAAyB,EAAE;AAChC,OAAK,kBAAkB;GACrB,UAAU;IACR,MAAM;IACN,WAAW;IACX,MAAM;IACN,WAAW;IACX,OAAO;IACR;GACD,SAAS;IAAE,MAAM;IAAgB,MAAM,EAAE,YAAY,SAAS;IAAE;GACjE;;;;;;;CAQH,eAAe,YAA0B;AACvC,OAAK,YAAY,KAAK,WAAW;;;;;;;CAQnC,SAAS,MAAwB;AAC/B,OAAK,SAAS,KAAK,KAAK;;CAG1B,yBAAyB,MAA0B;EACjD,IAAI,SAAS,IAAI,KAAK,KAAK,KAAK,KAAK;EACrC,MAAM,aACJ,mBAAmB,KAAK,OAAO,GAAG,aAAa,KAAK,OAAO,GAAG,KAAK;AAErE,YAAU,uBAAuB,KAAK,UAAU,YAAY,WAAW;AACvE,SAAO;;;;;;;CAQT,aAAa,UAAwB;AACnC,OAAK,UAAU,KAAK,SAAS;;;;;;;CAQ/B,2BAA2B,YAA0B;AACnD,OAAK,uBAAuB,KAAK,WAAW;;CAI9C,wBAAwB,OAAc,YAAY,QAAgB;AAChE,MAAI,cAAc,WAAW;GAC3B,MAAM,kBAAkB,MAAM,KAC3B,MAAM,MAAM,GAAG,IAAI,EAAE,IAAI,KAAK,yBAAyB,KAAK,GAC9D;GAKD,MAAM,gBAAgB,GACpB,MAAM,SAAS,EAChB,IAAI,YAAY;AACjB,UAAO,gBAAgB,OAAO,CAAC,cAAc,CAAC,CAAC,KAAK,KAAK;;AAG3D,SAAO,MAAM,KAAK,MAAM,MAAM,GAAG,IAAI,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK;;;;;;;CAQ/D,yBAAiC;EAC/B,MAAM,4BAA4B,KAAK,UACrC,KAAK,iBACL,MACA,EACD;AAeD,
|
|
1
|
+
{"version":3,"file":"prompt_generator.js","names":[],"sources":["../../../src/experimental/autogpt/prompt_generator.ts"],"sourcesContent":["import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport { ObjectTool, FINISH_NAME } from \"./schema.js\";\n\n/**\n * Class that generates prompts for generative agents. It maintains a list\n * of constraints, commands, resources, and performance evaluations.\n */\nexport class PromptGenerator {\n constraints: string[];\n\n commands: ObjectTool[];\n\n resources: string[];\n\n performance_evaluation: string[];\n\n response_format: object;\n\n constructor() {\n this.constraints = [];\n this.commands = [];\n this.resources = [];\n this.performance_evaluation = [];\n this.response_format = {\n thoughts: {\n text: \"thought\",\n reasoning: \"reasoning\",\n plan: \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n criticism: \"constructive self-criticism\",\n speak: \"thoughts summary to say to user\",\n },\n command: { name: \"command name\", args: { \"arg name\": \"value\" } },\n };\n }\n\n /**\n * Adds a constraint to the list of constraints.\n * @param constraint The constraint to add.\n * @returns void\n */\n add_constraint(constraint: string): void {\n this.constraints.push(constraint);\n }\n\n /**\n * Adds a tool to the list of commands.\n * @param tool The tool to add.\n * @returns void\n */\n add_tool(tool: ObjectTool): void {\n this.commands.push(tool);\n }\n\n _generate_command_string(tool: ObjectTool): string {\n let output = `\"${tool.name}\": ${tool.description}`;\n const jsonSchema = (\n isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema\n ) as { properties?: Record<string, JsonSchema7Type> } | undefined;\n output += `, args json schema: ${JSON.stringify(jsonSchema?.properties)}`;\n return output;\n }\n\n /**\n * Adds a resource to the list of resources.\n * @param resource The resource to add.\n * @returns void\n */\n add_resource(resource: string): void {\n this.resources.push(resource);\n }\n\n /**\n * Adds a performance evaluation to the list of performance evaluations.\n * @param evaluation The performance evaluation to add.\n * @returns void\n */\n add_performance_evaluation(evaluation: string): void {\n this.performance_evaluation.push(evaluation);\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _generate_numbered_list(items: any[], item_type = \"list\"): string {\n if (item_type === \"command\") {\n const command_strings = items.map(\n (item, i) => `${i + 1}. ${this._generate_command_string(item)}`\n );\n const finish_description =\n \"use this to signal that you have finished all your objectives\";\n const finish_args =\n '\"response\": \"final response to let people know you have finished your objectives\"';\n const finish_string = `${\n items.length + 1\n }. ${FINISH_NAME}: ${finish_description}, args: ${finish_args}`;\n return command_strings.concat([finish_string]).join(\"\\n\");\n }\n\n return items.map((item, i) => `${i + 1}. ${item}`).join(\"\\n\");\n }\n\n /**\n * Generates a prompt string that includes the constraints, commands,\n * resources, performance evaluations, and response format.\n * @returns A string representing the prompt.\n */\n generate_prompt_string(): string {\n const formatted_response_format = JSON.stringify(\n this.response_format,\n null,\n 4\n );\n const prompt_string =\n `Constraints:\\n${this._generate_numbered_list(this.constraints)}\\n\\n` +\n `Commands:\\n${this._generate_numbered_list(\n this.commands,\n \"command\"\n )}\\n\\n` +\n `Resources:\\n${this._generate_numbered_list(this.resources)}\\n\\n` +\n `Performance Evaluation:\\n${this._generate_numbered_list(\n this.performance_evaluation\n )}\\n\\n` +\n `You should only respond in JSON format as described below ` +\n `\\nResponse Format: \\n${formatted_response_format} ` +\n `\\nEnsure the response can be parsed by Python json.loads`;\n\n return prompt_string;\n }\n}\n\n/**\n * Function that generates a prompt string for a given list of tools.\n */\nexport function getPrompt(tools: ObjectTool[]): string {\n const prompt_generator = new PromptGenerator();\n\n prompt_generator.add_constraint(\n \"~4000 word limit for short term memory. \" +\n \"Your short term memory is short, \" +\n \"so immediately save important information to files.\"\n );\n prompt_generator.add_constraint(\n \"If you are unsure how you previously did something \" +\n \"or want to recall past events, \" +\n \"thinking about similar events will help you remember.\"\n );\n prompt_generator.add_constraint(\"No user assistance\");\n prompt_generator.add_constraint(\n 'Exclusively use the commands listed in double quotes e.g. \"command name\"'\n );\n\n for (const tool of tools) {\n prompt_generator.add_tool(tool);\n }\n\n prompt_generator.add_resource(\n \"Internet access for searches and information gathering.\"\n );\n prompt_generator.add_resource(\"Long Term memory management.\");\n prompt_generator.add_resource(\n \"GPT-3.5 powered Agents for delegation of simple tasks.\"\n );\n prompt_generator.add_resource(\"File output.\");\n\n prompt_generator.add_performance_evaluation(\n \"Continuously review and analyze your actions \" +\n \"to ensure you are performing to the best of your abilities.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Constructively self-criticize your big-picture behavior constantly.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Reflect on past decisions and strategies to refine your approach.\"\n );\n prompt_generator.add_performance_evaluation(\n \"Every command has a cost, so be smart and efficient. \" +\n \"Aim to complete tasks in the least number of steps.\"\n );\n\n const prompt_string = prompt_generator.generate_prompt_string();\n\n return prompt_string;\n}\n"],"mappings":";;;;;;;;AAWA,IAAa,kBAAb,MAA6B;CAC3B;CAEA;CAEA;CAEA;CAEA;CAEA,cAAc;AACZ,OAAK,cAAc,EAAE;AACrB,OAAK,WAAW,EAAE;AAClB,OAAK,YAAY,EAAE;AACnB,OAAK,yBAAyB,EAAE;AAChC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AUxD,SAAgB,UAAU,OAA6B;CACrD,MAAM,mBAAmB,IAAI,iBAAiB;AAE9C,kBAAiB,eACf,+HAGD;AACD,kBAAiB,eACf,0IAGD;AACD,kBAAiB,eAAe,qBAAqB;AACrD,kBAAiB,eACf,6EACD;AAED,MAAK,MAAM,QAAQ,MACjB,kBAAiB,SAAS,KAAK;AAGjC,kBAAiB,aACf,0DACD;AACD,kBAAiB,aAAa,+BAA+B;AAC7D,kBAAiB,aACf,yDACD;AACD,kBAAiB,aAAa,eAAe;AAE7C,kBAAiB,2BACf,2GAED;AACD,kBAAiB,2BACf,sEACD;AACD,kBAAiB,2BACf,oEACD;AACD,kBAAiB,2BACf,2GAED;AAID,QAFsB,iBAAiB,wBAEnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.cjs","names":["BaseChain","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,aAAAA,UAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;;CAGT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,aACgB;AAChB,QAAM,KAAA,GAAW,SAAS,UAAU;AACpC,OAAK,WAAW,EAAE;AAClB,OAAK,gBAAgB;AACrB,OAAK,sBAAsB;AAC3B,OAAK,iBAAiB;AACtB,OAAK,gBAAgB;AACrB,OAAK,cAAc;AACnB,OAAK,gBAAgB;;CAGvB,aAAa;AACX,SAAO;;CAGT,IAAI,YAAY;AACd,SAAO,CAAC,aAA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,WACD;AACD,QAAK,MAAM,WAAW,UAAU;AAC9B,SAAK,iBAAiB;AACtB,YAAQ,SAAS,KAAK,cAAc,SAAS;AAC7C,UAAM,KAAK,QAAQ,QAAgB;;AAErC,QAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;AAED,eAAY;;AAEd,SAAO,EAAE;;CAGX,YAAiC;AAC/B,QAAM,IAAI,MAAM,0BAA0B;;;;;;;;;;;;;CAc5C,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,WACA,GAAG,QAIoC;AAWvC,SAAO,IAAI,QAAQ;GACjB,eAXoBC,sBAAAA,kBAAkB,QAAQ;IAC9C;IACA;IACA;IACD,CAAC;GAQA,qBAP0BC,4BAAAA,wBAAwB,QAAQ;IAC1D;IACA;IACA;IACD,CAAC;GAIA,gBACE,kBACAC,uBAAAA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;IAAW,CAAC;GACzD;GACA;GACA;GACA,GAAG;GACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"agent.cjs","names":["BaseChain","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,aAAAA,UAAmC;CAC9D,OAAO,UAAU;AACf,SAAO;;CAGT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,aACgB;AAChB,QAAM,KAAA,GAAW,SAAS,UAAU;AACpC,OAAK,WAAW,EAAE;AAClB,OAAK,gBAAgB;AACrB,OAAK,sBAAsB;AAC3B,OAAK,i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AS;IACX,aAAa;IACb,UAAU,EAAE,MAAM,KAAK,UAAU;IAClC,CAAC,CACH,CAAC;GAEF,MAAM,WAAW,MAAM,KAAK,aAC1B,QACA,KAAK,UACL,WACA,WACD;AACD,QAAK,MAAM,WAAW,UAAU;AAC9B,SAAK,iBAAiB;AACtB,YAAQ,SAAS,KAAK,cAAc,SAAS;AAC7C,UAAM,KAAK,QAAQ,QAAgB;;AAErC,QAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;AAED,eAAY;;AAEd,SAAO,EAAE;;CAGX,YAAiC;AAC/B,QAAM,IAAI,MAAM,0BAA0B;;;;;;;;;;;;;CAc5C,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,WACA,GAAG,QAIoC;AAWvC,SAAO,IAAI,QAAQ;GACjB,eAXoBC,sBAAAA,kBAAkB,QAAQ;IAC9C;IACA;IACA;IACD,CAOc;GACb,qBAP0BC,4BAAAA,wBAAwB,QAAQ;IAC1D;IACA;IACA;IACD,CAGoB;GACnB,gBACE,kBACAC,uBAAAA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;IAAW,CAAC;GACzD;GACA;GACA;GACA,GAAG;GACJ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":[],"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;;CAGT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA,aACgB;AAChB,QAAM,KAAA,GAAW,S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Q,GAAG;AAC5C,QAAK,gBAAgB,OAAO;AAE5B,SAAM,KAAK,YAAY,aAAa,CAClC,IAAI,SAAS;IACX,aAAa;IACb,UAAU,EAAE,MAAM,KAAK,UAAU;IAClC,CAAC,CACH,CAAC;GAEF,MAAM,WAAW,MAAM,KAAK,aAC1B,QACA,KAAK,UACL,WACA,WACD;AACD,QAAK,MAAM,WAAW,UAAU;AAC9B,SAAK,iBAAiB;AACtB,YAAQ,SAAS,KAAK,cAAc,SAAS;AAC7C,UAAM,KAAK,QAAQ,QAAgB;;AAErC,QAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;AAED,eAAY;;AAEd,SAAO,EAAE;;CAGX,YAAiC;AAC/B,QAAM,IAAI,MAAM,0BAA0B;;;;;;;;;;;;;CAc5C,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,WACA,GAAG,QAIoC;AAWvC,SAAO,IAAI,QAAQ;GACjB,eAXoB,kBAAkB,QAAQ;IAC9C;IACA;IACA;IACD,CAAC;GAQA,qBAP0B,wBAAwB,QAAQ;IAC1D;IACA;IACA;IACD,CAAC;GAIA,gBACE,kBACA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;IAAW,CAAC;GACzD;GACA;GACA;GACA,GAAG;GACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"agent.js","names":[],"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;;CAGT;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,EACV,eACA,qBACA,gBACA,aACA,gBAAgB,KAChB,SACA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D,MAAM,aAAa,SAAS,KAAK,QAAQ,GAAG;AAC5C,QAAK,gBAAgB,OAAO;AAE5B,SAAM,KAAK,YAAY,aAAa,CAClC,IAAI,SAAS;IACX,aAAa;IACb,UAAU,EAAE,MAAM,KAAK,UAAU;IAClC,CAAC,CACH,CAAC;GAEF,MAAM,WAAW,MAAM,KAAK,aAC1B,QACA,KAAK,UACL,WACA,WACD;AACD,QAAK,MAAM,WAAW,UAAU;AAC9B,SAAK,iBAAiB;AACtB,YAAQ,SAAS,KAAK,cAAc,SAAS;AAC7C,UAAM,KAAK,QAAQ,QAAgB;;AAErC,QAAK,WAAW,MAAM,KAAK,gBACzB,YACA,WACA,WACD;AAED,eAAY;;AAEd,SAAO,EAAE;;CAGX,YAAiC;AAC/B,QAAM,IAAI,MAAM,0BAA0B;;;;;;;;;;;;;CAc5C,OAAO,QAAQ,EACb,KACA,aACA,gBACA,SACA,WACA,GAAG,QAIoC;AAWvC,SAAO,IAAI,QAAQ;GACjB,eAXoB,kBAAkB,QAAQ;IAC9C;IACA;IACA;IACD,CAOc;GACb,qBAP0B,wBAAwB,QAAQ;IAC1D;IACA;IACA;IACD,CAGoB;GACnB,gBACE,kBACA,mBAAmB,QAAQ;IAAE;IAAK;IAAS;IAAW,CAAC;GACzD;GACA;GACA;GACA,GAAG;GACJ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_creation.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_creation.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to generate tasks. */\nexport class TaskCreationChain extends LLMChain {\n static lc_name() {\n return \"TaskCreationChain\";\n }\n\n /**\n * Creates a new TaskCreationChain instance. It takes an object of type\n * LLMChainInput as input, omitting the 'prompt' field. It uses the\n * PromptTemplate class to create a new prompt based on the task creation\n * template and the input variables. The new TaskCreationChain instance is\n * then created with this prompt and the remaining fields from the input\n * object.\n * @param fields An object of type LLMChainInput, omitting the 'prompt' field.\n * @returns A new instance of TaskCreationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskCreationTemplate =\n `You are an task creation AI that uses the result of an execution agent` +\n ` to create new tasks with the following objective: {objective},` +\n ` The last completed task has the result: {result}.` +\n ` This result was based on this task description: {task_description}.` +\n ` These are incomplete tasks: {incomplete_tasks}.` +\n ` Based on the result, create new tasks to be completed` +\n ` by the AI system that do not overlap with incomplete tasks.` +\n ` Return the tasks as an array.`;\n const prompt = new PromptTemplate({\n template: taskCreationTemplate,\n inputVariables: [\n \"result\",\n \"task_description\",\n \"incomplete_tasks\",\n \"objective\",\n ],\n });\n return new TaskCreationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,oBAAb,MAAa,0BAA0BA,kBAAAA,SAAS;CAC9C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;;CAaT,OAAO,QAAQ,QAAiD;AAmB9D,SAAO,IAAI,kBAAkB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_creation.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_creation.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to generate tasks. */\nexport class TaskCreationChain extends LLMChain {\n static lc_name() {\n return \"TaskCreationChain\";\n }\n\n /**\n * Creates a new TaskCreationChain instance. It takes an object of type\n * LLMChainInput as input, omitting the 'prompt' field. It uses the\n * PromptTemplate class to create a new prompt based on the task creation\n * template and the input variables. The new TaskCreationChain instance is\n * then created with this prompt and the remaining fields from the input\n * object.\n * @param fields An object of type LLMChainInput, omitting the 'prompt' field.\n * @returns A new instance of TaskCreationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskCreationTemplate =\n `You are an task creation AI that uses the result of an execution agent` +\n ` to create new tasks with the following objective: {objective},` +\n ` The last completed task has the result: {result}.` +\n ` This result was based on this task description: {task_description}.` +\n ` These are incomplete tasks: {incomplete_tasks}.` +\n ` Based on the result, create new tasks to be completed` +\n ` by the AI system that do not overlap with incomplete tasks.` +\n ` Return the tasks as an array.`;\n const prompt = new PromptTemplate({\n template: taskCreationTemplate,\n inputVariables: [\n \"result\",\n \"task_description\",\n \"incomplete_tasks\",\n \"objective\",\n ],\n });\n return new TaskCreationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,oBAAb,MAAa,0BAA0BA,kBAAAA,SAAS;CAC9C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;;CAaT,OAAO,QAAQ,QAAiD;AAmB9D,SAAO,IAAI,kBAAkB;GAAE,QAAA,IATZC,wBAAAA,eAAe;IAChC,UAAU;IACV,gBAAgB;KACd;KACA;KACA;KACA;KACD;IACF,CACoC;GAAE,GAAG;GAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_creation.js","names":[],"sources":["../../../src/experimental/babyagi/task_creation.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to generate tasks. */\nexport class TaskCreationChain extends LLMChain {\n static lc_name() {\n return \"TaskCreationChain\";\n }\n\n /**\n * Creates a new TaskCreationChain instance. It takes an object of type\n * LLMChainInput as input, omitting the 'prompt' field. It uses the\n * PromptTemplate class to create a new prompt based on the task creation\n * template and the input variables. The new TaskCreationChain instance is\n * then created with this prompt and the remaining fields from the input\n * object.\n * @param fields An object of type LLMChainInput, omitting the 'prompt' field.\n * @returns A new instance of TaskCreationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskCreationTemplate =\n `You are an task creation AI that uses the result of an execution agent` +\n ` to create new tasks with the following objective: {objective},` +\n ` The last completed task has the result: {result}.` +\n ` This result was based on this task description: {task_description}.` +\n ` These are incomplete tasks: {incomplete_tasks}.` +\n ` Based on the result, create new tasks to be completed` +\n ` by the AI system that do not overlap with incomplete tasks.` +\n ` Return the tasks as an array.`;\n const prompt = new PromptTemplate({\n template: taskCreationTemplate,\n inputVariables: [\n \"result\",\n \"task_description\",\n \"incomplete_tasks\",\n \"objective\",\n ],\n });\n return new TaskCreationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,oBAAb,MAAa,0BAA0B,SAAS;CAC9C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;;CAaT,OAAO,QAAQ,QAAiD;AAmB9D,SAAO,IAAI,kBAAkB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_creation.js","names":[],"sources":["../../../src/experimental/babyagi/task_creation.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to generate tasks. */\nexport class TaskCreationChain extends LLMChain {\n static lc_name() {\n return \"TaskCreationChain\";\n }\n\n /**\n * Creates a new TaskCreationChain instance. It takes an object of type\n * LLMChainInput as input, omitting the 'prompt' field. It uses the\n * PromptTemplate class to create a new prompt based on the task creation\n * template and the input variables. The new TaskCreationChain instance is\n * then created with this prompt and the remaining fields from the input\n * object.\n * @param fields An object of type LLMChainInput, omitting the 'prompt' field.\n * @returns A new instance of TaskCreationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskCreationTemplate =\n `You are an task creation AI that uses the result of an execution agent` +\n ` to create new tasks with the following objective: {objective},` +\n ` The last completed task has the result: {result}.` +\n ` This result was based on this task description: {task_description}.` +\n ` These are incomplete tasks: {incomplete_tasks}.` +\n ` Based on the result, create new tasks to be completed` +\n ` by the AI system that do not overlap with incomplete tasks.` +\n ` Return the tasks as an array.`;\n const prompt = new PromptTemplate({\n template: taskCreationTemplate,\n inputVariables: [\n \"result\",\n \"task_description\",\n \"incomplete_tasks\",\n \"objective\",\n ],\n });\n return new TaskCreationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,oBAAb,MAAa,0BAA0B,SAAS;CAC9C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;;CAaT,OAAO,QAAQ,QAAiD;AAmB9D,SAAO,IAAI,kBAAkB;GAAE,QAAA,IATZ,eAAe;IAChC,UAAU;IACV,gBAAgB;KACd;KACA;KACA;KACA;KACD;IACF,CACoC;GAAE,GAAG;GAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_execution.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_execution.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to execute tasks. */\nexport class TaskExecutionChain extends LLMChain {\n static lc_name() {\n return \"TaskExecutionChain\";\n }\n\n /**\n * A static factory method that creates an instance of TaskExecutionChain.\n * It constructs a prompt template for task execution, which is then used\n * to create a new instance of TaskExecutionChain. The prompt template\n * instructs an AI to perform a task based on a given objective, taking\n * into account previously completed tasks.\n * @param fields An object of type LLMChainInput, excluding the \"prompt\" field.\n * @returns An instance of LLMChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const executionTemplate =\n `You are an AI who performs one task based on the following objective: ` +\n `{objective}.` +\n `Take into account these previously completed tasks: {context}.` +\n ` Your task: {task}. Response:`;\n const prompt = new PromptTemplate({\n template: executionTemplate,\n inputVariables: [\"objective\", \"context\", \"task\"],\n });\n return new TaskExecutionChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,qBAAb,MAAa,2BAA2BA,kBAAAA,SAAS;CAC/C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;CAYT,OAAO,QAAQ,QAAiD;AAU9D,SAAO,IAAI,mBAAmB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_execution.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_execution.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to execute tasks. */\nexport class TaskExecutionChain extends LLMChain {\n static lc_name() {\n return \"TaskExecutionChain\";\n }\n\n /**\n * A static factory method that creates an instance of TaskExecutionChain.\n * It constructs a prompt template for task execution, which is then used\n * to create a new instance of TaskExecutionChain. The prompt template\n * instructs an AI to perform a task based on a given objective, taking\n * into account previously completed tasks.\n * @param fields An object of type LLMChainInput, excluding the \"prompt\" field.\n * @returns An instance of LLMChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const executionTemplate =\n `You are an AI who performs one task based on the following objective: ` +\n `{objective}.` +\n `Take into account these previously completed tasks: {context}.` +\n ` Your task: {task}. Response:`;\n const prompt = new PromptTemplate({\n template: executionTemplate,\n inputVariables: [\"objective\", \"context\", \"task\"],\n });\n return new TaskExecutionChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,qBAAb,MAAa,2BAA2BA,kBAAAA,SAAS;CAC/C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;CAYT,OAAO,QAAQ,QAAiD;AAU9D,SAAO,IAAI,mBAAmB;GAAE,QAAA,IAJbC,wBAAAA,eAAe;IAChC,UAAU;IACV,gBAAgB;KAAC;KAAa;KAAW;KAAO;IACjD,CACqC;GAAE,GAAG;GAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_execution.js","names":[],"sources":["../../../src/experimental/babyagi/task_execution.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to execute tasks. */\nexport class TaskExecutionChain extends LLMChain {\n static lc_name() {\n return \"TaskExecutionChain\";\n }\n\n /**\n * A static factory method that creates an instance of TaskExecutionChain.\n * It constructs a prompt template for task execution, which is then used\n * to create a new instance of TaskExecutionChain. The prompt template\n * instructs an AI to perform a task based on a given objective, taking\n * into account previously completed tasks.\n * @param fields An object of type LLMChainInput, excluding the \"prompt\" field.\n * @returns An instance of LLMChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const executionTemplate =\n `You are an AI who performs one task based on the following objective: ` +\n `{objective}.` +\n `Take into account these previously completed tasks: {context}.` +\n ` Your task: {task}. Response:`;\n const prompt = new PromptTemplate({\n template: executionTemplate,\n inputVariables: [\"objective\", \"context\", \"task\"],\n });\n return new TaskExecutionChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,qBAAb,MAAa,2BAA2B,SAAS;CAC/C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;CAYT,OAAO,QAAQ,QAAiD;AAU9D,SAAO,IAAI,mBAAmB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_execution.js","names":[],"sources":["../../../src/experimental/babyagi/task_execution.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to execute tasks. */\nexport class TaskExecutionChain extends LLMChain {\n static lc_name() {\n return \"TaskExecutionChain\";\n }\n\n /**\n * A static factory method that creates an instance of TaskExecutionChain.\n * It constructs a prompt template for task execution, which is then used\n * to create a new instance of TaskExecutionChain. The prompt template\n * instructs an AI to perform a task based on a given objective, taking\n * into account previously completed tasks.\n * @param fields An object of type LLMChainInput, excluding the \"prompt\" field.\n * @returns An instance of LLMChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const executionTemplate =\n `You are an AI who performs one task based on the following objective: ` +\n `{objective}.` +\n `Take into account these previously completed tasks: {context}.` +\n ` Your task: {task}. Response:`;\n const prompt = new PromptTemplate({\n template: executionTemplate,\n inputVariables: [\"objective\", \"context\", \"task\"],\n });\n return new TaskExecutionChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,qBAAb,MAAa,2BAA2B,SAAS;CAC/C,OAAO,UAAU;AACf,SAAO;;;;;;;;;;;CAYT,OAAO,QAAQ,QAAiD;AAU9D,SAAO,IAAI,mBAAmB;GAAE,QAAA,IAJb,eAAe;IAChC,UAAU;IACV,gBAAgB;KAAC;KAAa;KAAW;KAAO;IACjD,CACqC;GAAE,GAAG;GAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_prioritization.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_prioritization.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to prioritize tasks. */\nexport class TaskPrioritizationChain extends LLMChain {\n static lc_name() {\n return \"TaskPrioritizationChain\";\n }\n\n /**\n * Static method to create a new TaskPrioritizationChain from a\n * BaseLanguageModel. It generates a prompt using the PromptTemplate class\n * and the task prioritization template, and returns a new instance of\n * TaskPrioritizationChain.\n * @param fields Object with fields used to initialize the chain, excluding the prompt.\n * @returns A new instance of TaskPrioritizationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskPrioritizationTemplate =\n `You are a task prioritization AI tasked with cleaning the formatting of ` +\n `and reprioritizing the following tasks: {task_names}.` +\n ` Consider the ultimate objective of your team: {objective}.` +\n ` Do not remove any tasks. Return the result as a numbered list, like:` +\n ` #. First task` +\n ` #. Second task` +\n ` Start the task list with number {next_task_id}.`;\n const prompt = new PromptTemplate({\n template: taskPrioritizationTemplate,\n inputVariables: [\"task_names\", \"next_task_id\", \"objective\"],\n });\n return new TaskPrioritizationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,0BAAb,MAAa,gCAAgCA,kBAAAA,SAAS;CACpD,OAAO,UAAU;AACf,SAAO;;;;;;;;;;CAWT,OAAO,QAAQ,QAAiD;AAa9D,SAAO,IAAI,wBAAwB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_prioritization.cjs","names":["LLMChain","PromptTemplate"],"sources":["../../../src/experimental/babyagi/task_prioritization.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to prioritize tasks. */\nexport class TaskPrioritizationChain extends LLMChain {\n static lc_name() {\n return \"TaskPrioritizationChain\";\n }\n\n /**\n * Static method to create a new TaskPrioritizationChain from a\n * BaseLanguageModel. It generates a prompt using the PromptTemplate class\n * and the task prioritization template, and returns a new instance of\n * TaskPrioritizationChain.\n * @param fields Object with fields used to initialize the chain, excluding the prompt.\n * @returns A new instance of TaskPrioritizationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskPrioritizationTemplate =\n `You are a task prioritization AI tasked with cleaning the formatting of ` +\n `and reprioritizing the following tasks: {task_names}.` +\n ` Consider the ultimate objective of your team: {objective}.` +\n ` Do not remove any tasks. Return the result as a numbered list, like:` +\n ` #. First task` +\n ` #. Second task` +\n ` Start the task list with number {next_task_id}.`;\n const prompt = new PromptTemplate({\n template: taskPrioritizationTemplate,\n inputVariables: [\"task_names\", \"next_task_id\", \"objective\"],\n });\n return new TaskPrioritizationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,0BAAb,MAAa,gCAAgCA,kBAAAA,SAAS;CACpD,OAAO,UAAU;AACf,SAAO;;;;;;;;;;CAWT,OAAO,QAAQ,QAAiD;AAa9D,SAAO,IAAI,wBAAwB;GAAE,QAAA,IAJlBC,wBAAAA,eAAe;IAChC,UAAU;IACV,gBAAgB;KAAC;KAAc;KAAgB;KAAY;IAC5D,CAC0C;GAAE,GAAG;GAAQ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task_prioritization.js","names":[],"sources":["../../../src/experimental/babyagi/task_prioritization.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to prioritize tasks. */\nexport class TaskPrioritizationChain extends LLMChain {\n static lc_name() {\n return \"TaskPrioritizationChain\";\n }\n\n /**\n * Static method to create a new TaskPrioritizationChain from a\n * BaseLanguageModel. It generates a prompt using the PromptTemplate class\n * and the task prioritization template, and returns a new instance of\n * TaskPrioritizationChain.\n * @param fields Object with fields used to initialize the chain, excluding the prompt.\n * @returns A new instance of TaskPrioritizationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskPrioritizationTemplate =\n `You are a task prioritization AI tasked with cleaning the formatting of ` +\n `and reprioritizing the following tasks: {task_names}.` +\n ` Consider the ultimate objective of your team: {objective}.` +\n ` Do not remove any tasks. Return the result as a numbered list, like:` +\n ` #. First task` +\n ` #. Second task` +\n ` Start the task list with number {next_task_id}.`;\n const prompt = new PromptTemplate({\n template: taskPrioritizationTemplate,\n inputVariables: [\"task_names\", \"next_task_id\", \"objective\"],\n });\n return new TaskPrioritizationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,0BAAb,MAAa,gCAAgC,SAAS;CACpD,OAAO,UAAU;AACf,SAAO;;;;;;;;;;CAWT,OAAO,QAAQ,QAAiD;AAa9D,SAAO,IAAI,wBAAwB;GAAE,
|
|
1
|
+
{"version":3,"file":"task_prioritization.js","names":[],"sources":["../../../src/experimental/babyagi/task_prioritization.ts"],"sourcesContent":["import { PromptTemplate } from \"@langchain/core/prompts\";\nimport { LLMChain, LLMChainInput } from \"../../chains/llm_chain.js\";\n\n/** Chain to prioritize tasks. */\nexport class TaskPrioritizationChain extends LLMChain {\n static lc_name() {\n return \"TaskPrioritizationChain\";\n }\n\n /**\n * Static method to create a new TaskPrioritizationChain from a\n * BaseLanguageModel. It generates a prompt using the PromptTemplate class\n * and the task prioritization template, and returns a new instance of\n * TaskPrioritizationChain.\n * @param fields Object with fields used to initialize the chain, excluding the prompt.\n * @returns A new instance of TaskPrioritizationChain.\n */\n static fromLLM(fields: Omit<LLMChainInput, \"prompt\">): LLMChain {\n const taskPrioritizationTemplate =\n `You are a task prioritization AI tasked with cleaning the formatting of ` +\n `and reprioritizing the following tasks: {task_names}.` +\n ` Consider the ultimate objective of your team: {objective}.` +\n ` Do not remove any tasks. Return the result as a numbered list, like:` +\n ` #. First task` +\n ` #. Second task` +\n ` Start the task list with number {next_task_id}.`;\n const prompt = new PromptTemplate({\n template: taskPrioritizationTemplate,\n inputVariables: [\"task_names\", \"next_task_id\", \"objective\"],\n });\n return new TaskPrioritizationChain({ prompt, ...fields });\n }\n}\n"],"mappings":";;;;AAIA,IAAa,0BAAb,MAAa,gCAAgC,SAAS;CACpD,OAAO,UAAU;AACf,SAAO;;;;;;;;;;CAWT,OAAO,QAAQ,QAAiD;AAa9D,SAAO,IAAI,wBAAwB;GAAE,QAAA,IAJlB,eAAe;IAChC,UAAU;IACV,gBAAgB;KAAC;KAAc;KAAgB;KAAY;IAC5D,CAC0C;GAAE,GAAG;GAAQ,CAAC"}
|
package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"violation_of_expectations_chain.cjs","names":["BaseChain","JsonOutputFunctionsParser","StringOutputParser","HumanMessage","PREDICT_NEXT_USER_MESSAGE_FUNCTION","PREDICT_NEXT_USER_MESSAGE_PROMPT","PREDICTION_VIOLATIONS_FUNCTION","PREDICTION_VIOLATIONS_PROMPT","GENERATE_REVISED_PREDICTION_PROMPT","GENERATE_FACTS_PROMPT"],"sources":["../../../../src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport {\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"@langchain/core/messages\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { StringOutputParser } from \"@langchain/core/output_parsers\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { JsonOutputFunctionsParser } from \"../../../output_parsers/openai_functions.js\";\nimport { BaseChain, ChainInputs } from \"../../../chains/base.js\";\nimport {\n GetPredictionViolationsResponse,\n MessageChunkResult,\n PREDICTION_VIOLATIONS_FUNCTION,\n PREDICT_NEXT_USER_MESSAGE_FUNCTION,\n PredictNextUserMessageResponse,\n} from \"./types.js\";\nimport {\n GENERATE_FACTS_PROMPT,\n GENERATE_REVISED_PREDICTION_PROMPT,\n PREDICTION_VIOLATIONS_PROMPT,\n PREDICT_NEXT_USER_MESSAGE_PROMPT,\n} from \"./violation_of_expectations_prompt.js\";\n\n/**\n * Interface for the input parameters of the ViolationOfExpectationsChain class.\n */\nexport interface ViolationOfExpectationsChainInput extends ChainInputs {\n /**\n * The retriever to use for retrieving stored\n * thoughts and insights.\n */\n retriever: BaseRetrieverInterface;\n /**\n * The LLM to use\n */\n llm: ChatOpenAI;\n}\n\n/**\n * Chain that generates key insights/facts of a user based on a\n * a chat conversation with an AI.\n */\nexport class ViolationOfExpectationsChain\n extends BaseChain\n implements ViolationOfExpectationsChainInput\n{\n static lc_name() {\n return \"ViolationOfExpectationsChain\";\n }\n\n _chainType(): string {\n return \"violation_of_expectation_chain\";\n }\n\n chatHistoryKey = \"chat_history\";\n\n thoughtsKey = \"thoughts\";\n\n get inputKeys() {\n return [this.chatHistoryKey];\n }\n\n get outputKeys() {\n return [this.thoughtsKey];\n }\n\n retriever: BaseRetrieverInterface;\n\n llm: ChatOpenAI;\n\n jsonOutputParser: JsonOutputFunctionsParser;\n\n stringOutputParser: StringOutputParser;\n\n constructor(fields: ViolationOfExpectationsChainInput) {\n super(fields);\n this.retriever = fields.retriever;\n this.llm = fields.llm;\n this.jsonOutputParser = new JsonOutputFunctionsParser();\n this.stringOutputParser = new StringOutputParser();\n }\n\n getChatHistoryString(chatHistory: BaseMessage[]): string {\n return chatHistory\n .map((chatMessage) => {\n if (chatMessage._getType() === \"human\") {\n return `Human: ${chatMessage.content}`;\n } else if (chatMessage._getType() === \"ai\") {\n return `AI: ${chatMessage.content}`;\n } else {\n return `${chatMessage.content}`;\n }\n })\n .join(\"\\n\");\n }\n\n removeDuplicateStrings(strings: Array<string>): Array<string> {\n return [...new Set(strings)];\n }\n\n /**\n * This method breaks down the chat history into chunks of messages.\n * Each chunk consists of a sequence of messages ending with an AI message and the subsequent user response, if any.\n *\n * @param {BaseMessage[]} chatHistory - The chat history to be chunked.\n *\n * @returns {MessageChunkResult[]} An array of message chunks. Each chunk includes a sequence of messages and the subsequent user response.\n *\n * @description\n * The method iterates over the chat history and pushes each message into a temporary array.\n * When it encounters an AI message, it checks for a subsequent user message.\n * If a user message is found, it is considered as the user response to the AI message.\n * If no user message is found after the AI message, the user response is undefined.\n * The method then pushes the chunk (sequence of messages and user response) into the result array.\n * This process continues until all messages in the chat history have been processed.\n */\n chunkMessagesByAIResponse(chatHistory: BaseMessage[]): MessageChunkResult[] {\n const newArray: MessageChunkResult[] = [];\n const tempArray: BaseMessage[] = [];\n\n chatHistory.forEach((item, index) => {\n tempArray.push(item);\n if (item._getType() === \"ai\") {\n let userResponse: BaseMessage | undefined = chatHistory[index + 1];\n if (!userResponse || userResponse._getType() !== \"human\") {\n userResponse = undefined;\n }\n\n newArray.push({\n chunkedMessages: tempArray,\n userResponse: userResponse\n ? new HumanMessage(userResponse)\n : undefined,\n });\n }\n });\n\n return newArray;\n }\n\n /**\n * This method processes a chat history to generate insights about the user.\n *\n * @param {ChainValues} values - The input values for the chain. It should contain a key for chat history.\n * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<ChainValues>} A promise that resolves to a list of insights about the user.\n *\n * @throws {Error} If the chat history key is not found in the input values or if the chat history is not an array of BaseMessages.\n *\n * @description\n * The method performs the following steps:\n * 1. Checks if the chat history key is present in the input values and if the chat history is an array of BaseMessages.\n * 2. Breaks the chat history into chunks of messages.\n * 3. For each chunk, it generates an initial prediction for the user's next message.\n * 4. For each prediction, it generates insights and prediction violations, and regenerates the prediction based on the violations.\n * 5. For each set of messages, it generates a fact/insight about the user.\n * The method returns a list of these insights.\n */\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n if (!(this.chatHistoryKey in values)) {\n throw new Error(`Chat history key ${this.chatHistoryKey} not found`);\n }\n\n const chatHistory: unknown[] = values[this.chatHistoryKey];\n\n const isEveryMessageBaseMessage = chatHistory.every((message) =>\n isBaseMessage(message)\n );\n if (!isEveryMessageBaseMessage) {\n throw new Error(\"Chat history must be an array of BaseMessages\");\n }\n\n const messageChunks = this.chunkMessagesByAIResponse(\n chatHistory as BaseMessage[]\n );\n\n // Generate the initial prediction for every user message.\n const userPredictions = await Promise.all(\n messageChunks.map(async (chatHistoryChunk) => ({\n userPredictions: await this.predictNextUserMessage(\n chatHistoryChunk.chunkedMessages\n ),\n userResponse: chatHistoryChunk.userResponse,\n runManager,\n }))\n );\n\n // Generate insights, and prediction violations for every user message.\n // This call also regenerates the prediction based on the violations.\n const predictionViolations = await Promise.all(\n userPredictions.map((prediction) =>\n this.getPredictionViolations({\n userPredictions: prediction.userPredictions,\n userResponse: prediction.userResponse,\n runManager,\n })\n )\n );\n\n // Generate a fact/insight about the user for every set of messages.\n const insights = await Promise.all(\n predictionViolations.map((violation) =>\n this.generateFacts({\n userResponse: violation.userResponse,\n predictions: {\n revisedPrediction: violation.revisedPrediction,\n explainedPredictionErrors: violation.explainedPredictionErrors,\n },\n })\n )\n );\n\n return {\n insights,\n };\n }\n\n /**\n * This method predicts the next user message based on the chat history.\n *\n * @param {BaseMessage[]} chatHistory - The chat history based on which the next user message is predicted.\n * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<PredictNextUserMessageResponse>} A promise that resolves to the predicted next user message, the user state, and any insights.\n *\n * @throws {Error} If the response from the language model does not contain the expected keys: 'userState', 'predictedUserMessage', and 'insights'.\n */\n private async predictNextUserMessage(\n chatHistory: BaseMessage[],\n runManager?: CallbackManagerForChainRun\n ): Promise<PredictNextUserMessageResponse> {\n const messageString = this.getChatHistoryString(chatHistory);\n\n const llmWithFunctions = this.llm\n .bindTools([PREDICT_NEXT_USER_MESSAGE_FUNCTION])\n .withConfig({\n function_call: { name: PREDICT_NEXT_USER_MESSAGE_FUNCTION.name },\n });\n\n const chain = PREDICT_NEXT_USER_MESSAGE_PROMPT.pipe(llmWithFunctions).pipe(\n this.jsonOutputParser\n );\n\n const res = await chain.invoke(\n {\n chat_history: messageString,\n },\n runManager?.getChild(\"prediction\")\n );\n\n if (\n !(\n \"userState\" in res &&\n \"predictedUserMessage\" in res &&\n \"insights\" in res\n )\n ) {\n throw new Error(`Invalid response from LLM: ${JSON.stringify(res)}`);\n }\n\n const predictionResponse = res as PredictNextUserMessageResponse;\n\n // Query the retriever for relevant insights. Use the generates insights as a query.\n const retrievedDocs = await this.retrieveRelevantInsights(\n predictionResponse.insights\n );\n const relevantDocs = this.removeDuplicateStrings([\n ...predictionResponse.insights,\n ...retrievedDocs,\n ]);\n\n return {\n ...predictionResponse,\n insights: relevantDocs,\n };\n }\n\n /**\n * Retrieves relevant insights based on the provided insights.\n *\n * @param {Array<string>} insights - An array of insights to be used for retrieving relevant documents.\n *\n * @returns {Promise<Array<string>>} A promise that resolves to an array of relevant insights content.\n */\n private async retrieveRelevantInsights(\n insights: Array<string>\n ): Promise<Array<string>> {\n // Only extract the first relevant doc from the retriever. We don't need more than one.\n const relevantInsightsDocuments = await Promise.all(\n insights.map(async (insight) => {\n const relevantInsight = await this.retriever.invoke(insight);\n return relevantInsight[0];\n })\n );\n\n const relevantInsightsContent = relevantInsightsDocuments.map(\n (document) => document.pageContent\n );\n\n return relevantInsightsContent;\n }\n\n /**\n * This method generates prediction violations based on the predicted and actual user responses.\n * It also generates a revised prediction based on the identified violations.\n *\n * @param {Object} params - The parameters for the method.\n * @param {PredictNextUserMessageResponse} params.userPredictions - The predicted user message, user state, and insights.\n * @param {BaseMessage} [params.userResponse] - The actual user response.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<{ userResponse: BaseMessage | undefined; revisedPrediction: string; explainedPredictionErrors: Array<string>; }>} A promise that resolves to an object containing the actual user response, the revised prediction, and the explained prediction errors.\n *\n * @throws {Error} If the response from the language model does not contain the expected keys: 'violationExplanation', 'explainedPredictionErrors', and 'accuratePrediction'.\n */\n private async getPredictionViolations({\n userPredictions,\n userResponse,\n runManager,\n }: {\n userPredictions: PredictNextUserMessageResponse;\n userResponse?: BaseMessage;\n runManager?: CallbackManagerForChainRun;\n }): Promise<GetPredictionViolationsResponse> {\n const llmWithFunctions = this.llm\n .bindTools([PREDICTION_VIOLATIONS_FUNCTION])\n .withConfig({\n function_call: { name: PREDICTION_VIOLATIONS_FUNCTION.name },\n });\n\n const chain = PREDICTION_VIOLATIONS_PROMPT.pipe(llmWithFunctions).pipe(\n this.jsonOutputParser\n );\n\n if (typeof userResponse?.content !== \"string\") {\n throw new Error(\"This chain does not support non-string model output.\");\n }\n const res = (await chain.invoke(\n {\n predicted_output: userPredictions.predictedUserMessage,\n actual_output: userResponse?.content ?? \"\",\n user_insights: userPredictions.insights.join(\"\\n\"),\n },\n runManager?.getChild(\"prediction_violations\")\n )) as Awaited<{\n violationExplanation: string;\n explainedPredictionErrors: Array<string>;\n accuratePrediction: boolean;\n }>;\n\n // Generate a revised prediction based on violations.\n const revisedPrediction = await this.generateRevisedPrediction({\n originalPrediction: userPredictions.predictedUserMessage,\n explainedPredictionErrors: res.explainedPredictionErrors,\n userInsights: userPredictions.insights,\n runManager,\n });\n\n return {\n userResponse,\n revisedPrediction,\n explainedPredictionErrors: res.explainedPredictionErrors,\n };\n }\n\n /**\n * This method generates a revised prediction based on the original prediction, explained prediction errors, and user insights.\n *\n * @param {Object} params - The parameters for the method.\n * @param {string} params.originalPrediction - The original prediction made by the model.\n * @param {Array<string>} params.explainedPredictionErrors - An array of explained prediction errors.\n * @param {Array<string>} params.userInsights - An array of insights about the user.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<string>} A promise that resolves to a revised prediction.\n */\n private async generateRevisedPrediction({\n originalPrediction,\n explainedPredictionErrors,\n userInsights,\n runManager,\n }: {\n originalPrediction: string;\n explainedPredictionErrors: Array<string>;\n userInsights: Array<string>;\n runManager?: CallbackManagerForChainRun;\n }): Promise<string> {\n const revisedPredictionChain = GENERATE_REVISED_PREDICTION_PROMPT.pipe(\n this.llm\n ).pipe(this.stringOutputParser);\n\n const revisedPredictionRes = await revisedPredictionChain.invoke(\n {\n prediction: originalPrediction,\n explained_prediction_errors: explainedPredictionErrors.join(\"\\n\"),\n user_insights: userInsights.join(\"\\n\"),\n },\n runManager?.getChild(\"prediction_revision\")\n );\n\n return revisedPredictionRes;\n }\n\n /**\n * This method generates facts or insights about the user based on the revised prediction, explained prediction errors, and the user's response.\n *\n * @param {Object} params - The parameters for the method.\n * @param {BaseMessage} [params.userResponse] - The actual user response.\n * @param {Object} params.predictions - The revised prediction and explained prediction errors.\n * @param {string} params.predictions.revisedPrediction - The revised prediction made by the model.\n * @param {Array<string>} params.predictions.explainedPredictionErrors - An array of explained prediction errors.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<string>} A promise that resolves to a string containing the generated facts or insights about the user.\n */\n private async generateFacts({\n userResponse,\n predictions,\n runManager,\n }: {\n userResponse?: BaseMessage;\n /**\n * Optional if the prediction was accurate.\n */\n predictions: {\n revisedPrediction: string;\n explainedPredictionErrors: Array<string>;\n };\n runManager?: CallbackManagerForChainRun;\n }): Promise<string> {\n const chain = GENERATE_FACTS_PROMPT.pipe(this.llm).pipe(\n this.stringOutputParser\n );\n\n if (typeof userResponse?.content !== \"string\") {\n throw new Error(\"This chain does not support non-string model output.\");\n }\n const res = await chain.invoke(\n {\n prediction_violations: predictions.explainedPredictionErrors.join(\"\\n\"),\n prediction: predictions.revisedPrediction,\n user_message: userResponse?.content ?? \"\",\n },\n runManager?.getChild(\"generate_facts\")\n );\n\n return res;\n }\n\n /**\n * Static method that creates a ViolationOfExpectationsChain instance from a\n * ChatOpenAI and retriever. It also accepts optional options\n * to customize the chain.\n *\n * @param llm The ChatOpenAI instance.\n * @param retriever The retriever used for similarity search.\n * @param options Optional options to customize the chain.\n *\n * @returns A new instance of ViolationOfExpectationsChain.\n */\n static fromLLM(\n llm: ChatOpenAI,\n retriever: BaseRetrieverInterface,\n options?: Partial<\n Omit<ViolationOfExpectationsChainInput, \"llm\" | \"retriever\">\n >\n ): ViolationOfExpectationsChain {\n return new this({\n retriever,\n llm,\n ...options,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,IAAa,+BAAb,cACUA,aAAAA,UAEV;CACE,OAAO,UAAU;AACf,SAAO;;CAGT,aAAqB;AACnB,SAAO;;CAGT,iBAAiB;CAEjB,cAAc;CAEd,IAAI,YAAY;AACd,SAAO,CAAC,KAAK,eAAe;;CAG9B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,YAAY;;CAG3B;CAEA;CAEA;CAEA;CAEA,YAAY,QAA2C;AACrD,QAAM,OAAO;AACb,OAAK,YAAY,OAAO;AACxB,OAAK,MAAM,OAAO;AAClB,OAAK,mBAAmB,IAAIC,yBAAAA,2BAA2B;AACvD,OAAK,qBAAqB,IAAIC,+BAAAA,oBAAoB;;CAGpD,qBAAqB,aAAoC;AACvD,SAAO,YACJ,KAAK,gBAAgB;AACpB,OAAI,YAAY,UAAU,KAAK,QAC7B,QAAO,UAAU,YAAY;YACpB,YAAY,UAAU,KAAK,KACpC,QAAO,OAAO,YAAY;OAE1B,QAAO,GAAG,YAAY;IAExB,CACD,KAAK,KAAK;;CAGf,uBAAuB,SAAuC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MAAM,MAAM,OACvB;GACE,kBAAkB,gBAAgB;GAClC,eAAe,cAAc,WAAW;GACxC,eAAe,gBAAgB,SAAS,KAAK,KAAK;GACnD,EACD,YAAY,SAAS,wBAAwB,CAC9C;AAcD,SAAO;GACL;GACA,mBATwB,MAAM,KAAK,0BAA0B;IAC7D,oBAAoB,gBAAgB;IACpC,2BAA2B,IAAI;IAC/B,cAAc,gBAAgB;IAC9B;IACD,CAAC;GAKA,2BAA2B,IAAI;GAChC;;;;;;;;;;;;;CAcH,MAAc,0BAA0B,EACtC,oBACA,2BACA,cACA,cAMkB;AAclB,SAT6B,MAJEC,yCAAAA,mCAAmC,KAChE,KAAK,IACN,CAAC,KAAK,KAAK,mBAAmB,CAE2B,OACxD;GACE,YAAY;GACZ,6BAA6B,0BAA0B,KAAK,KAAK;GACjE,eAAe,aAAa,KAAK,KAAK;GACvC,EACD,YAAY,SAAS,sBAAsB,CAC5C;;;;;;;;;;;;;;CAiBH,MAAc,cAAc,EAC1B,cACA,aACA,cAWkB;EAClB,MAAM,QAAQC,yCAAAA,sBAAsB,KAAK,KAAK,IAAI,CAAC,KACjD,KAAK,mBACN;AAED,MAAI,OAAO,cAAc,YAAY,SACnC,OAAM,IAAI,MAAM,uDAAuD;AAWzE,SATY,MAAM,MAAM,OACtB;GACE,uBAAuB,YAAY,0BAA0B,KAAK,KAAK;GACvE,YAAY,YAAY;GACxB,cAAc,cAAc,WAAW;GACxC,EACD,YAAY,SAAS,iBAAiB,CACvC;;;;;;;;;;;;;CAgBH,OAAO,QACL,KACA,WACA,SAG8B;AAC9B,SAAO,IAAI,KAAK;GACd;GACA;GACA,GAAG;GACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"violation_of_expectations_chain.cjs","names":["BaseChain","JsonOutputFunctionsParser","StringOutputParser","HumanMessage","PREDICT_NEXT_USER_MESSAGE_FUNCTION","PREDICT_NEXT_USER_MESSAGE_PROMPT","PREDICTION_VIOLATIONS_FUNCTION","PREDICTION_VIOLATIONS_PROMPT","GENERATE_REVISED_PREDICTION_PROMPT","GENERATE_FACTS_PROMPT"],"sources":["../../../../src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts"],"sourcesContent":["import type { BaseRetrieverInterface } from \"@langchain/core/retrievers\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport {\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"@langchain/core/messages\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { StringOutputParser } from \"@langchain/core/output_parsers\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { JsonOutputFunctionsParser } from \"../../../output_parsers/openai_functions.js\";\nimport { BaseChain, ChainInputs } from \"../../../chains/base.js\";\nimport {\n GetPredictionViolationsResponse,\n MessageChunkResult,\n PREDICTION_VIOLATIONS_FUNCTION,\n PREDICT_NEXT_USER_MESSAGE_FUNCTION,\n PredictNextUserMessageResponse,\n} from \"./types.js\";\nimport {\n GENERATE_FACTS_PROMPT,\n GENERATE_REVISED_PREDICTION_PROMPT,\n PREDICTION_VIOLATIONS_PROMPT,\n PREDICT_NEXT_USER_MESSAGE_PROMPT,\n} from \"./violation_of_expectations_prompt.js\";\n\n/**\n * Interface for the input parameters of the ViolationOfExpectationsChain class.\n */\nexport interface ViolationOfExpectationsChainInput extends ChainInputs {\n /**\n * The retriever to use for retrieving stored\n * thoughts and insights.\n */\n retriever: BaseRetrieverInterface;\n /**\n * The LLM to use\n */\n llm: ChatOpenAI;\n}\n\n/**\n * Chain that generates key insights/facts of a user based on a\n * a chat conversation with an AI.\n */\nexport class ViolationOfExpectationsChain\n extends BaseChain\n implements ViolationOfExpectationsChainInput\n{\n static lc_name() {\n return \"ViolationOfExpectationsChain\";\n }\n\n _chainType(): string {\n return \"violation_of_expectation_chain\";\n }\n\n chatHistoryKey = \"chat_history\";\n\n thoughtsKey = \"thoughts\";\n\n get inputKeys() {\n return [this.chatHistoryKey];\n }\n\n get outputKeys() {\n return [this.thoughtsKey];\n }\n\n retriever: BaseRetrieverInterface;\n\n llm: ChatOpenAI;\n\n jsonOutputParser: JsonOutputFunctionsParser;\n\n stringOutputParser: StringOutputParser;\n\n constructor(fields: ViolationOfExpectationsChainInput) {\n super(fields);\n this.retriever = fields.retriever;\n this.llm = fields.llm;\n this.jsonOutputParser = new JsonOutputFunctionsParser();\n this.stringOutputParser = new StringOutputParser();\n }\n\n getChatHistoryString(chatHistory: BaseMessage[]): string {\n return chatHistory\n .map((chatMessage) => {\n if (chatMessage._getType() === \"human\") {\n return `Human: ${chatMessage.content}`;\n } else if (chatMessage._getType() === \"ai\") {\n return `AI: ${chatMessage.content}`;\n } else {\n return `${chatMessage.content}`;\n }\n })\n .join(\"\\n\");\n }\n\n removeDuplicateStrings(strings: Array<string>): Array<string> {\n return [...new Set(strings)];\n }\n\n /**\n * This method breaks down the chat history into chunks of messages.\n * Each chunk consists of a sequence of messages ending with an AI message and the subsequent user response, if any.\n *\n * @param {BaseMessage[]} chatHistory - The chat history to be chunked.\n *\n * @returns {MessageChunkResult[]} An array of message chunks. Each chunk includes a sequence of messages and the subsequent user response.\n *\n * @description\n * The method iterates over the chat history and pushes each message into a temporary array.\n * When it encounters an AI message, it checks for a subsequent user message.\n * If a user message is found, it is considered as the user response to the AI message.\n * If no user message is found after the AI message, the user response is undefined.\n * The method then pushes the chunk (sequence of messages and user response) into the result array.\n * This process continues until all messages in the chat history have been processed.\n */\n chunkMessagesByAIResponse(chatHistory: BaseMessage[]): MessageChunkResult[] {\n const newArray: MessageChunkResult[] = [];\n const tempArray: BaseMessage[] = [];\n\n chatHistory.forEach((item, index) => {\n tempArray.push(item);\n if (item._getType() === \"ai\") {\n let userResponse: BaseMessage | undefined = chatHistory[index + 1];\n if (!userResponse || userResponse._getType() !== \"human\") {\n userResponse = undefined;\n }\n\n newArray.push({\n chunkedMessages: tempArray,\n userResponse: userResponse\n ? new HumanMessage(userResponse)\n : undefined,\n });\n }\n });\n\n return newArray;\n }\n\n /**\n * This method processes a chat history to generate insights about the user.\n *\n * @param {ChainValues} values - The input values for the chain. It should contain a key for chat history.\n * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<ChainValues>} A promise that resolves to a list of insights about the user.\n *\n * @throws {Error} If the chat history key is not found in the input values or if the chat history is not an array of BaseMessages.\n *\n * @description\n * The method performs the following steps:\n * 1. Checks if the chat history key is present in the input values and if the chat history is an array of BaseMessages.\n * 2. Breaks the chat history into chunks of messages.\n * 3. For each chunk, it generates an initial prediction for the user's next message.\n * 4. For each prediction, it generates insights and prediction violations, and regenerates the prediction based on the violations.\n * 5. For each set of messages, it generates a fact/insight about the user.\n * The method returns a list of these insights.\n */\n async _call(\n values: ChainValues,\n runManager?: CallbackManagerForChainRun\n ): Promise<ChainValues> {\n if (!(this.chatHistoryKey in values)) {\n throw new Error(`Chat history key ${this.chatHistoryKey} not found`);\n }\n\n const chatHistory: unknown[] = values[this.chatHistoryKey];\n\n const isEveryMessageBaseMessage = chatHistory.every((message) =>\n isBaseMessage(message)\n );\n if (!isEveryMessageBaseMessage) {\n throw new Error(\"Chat history must be an array of BaseMessages\");\n }\n\n const messageChunks = this.chunkMessagesByAIResponse(\n chatHistory as BaseMessage[]\n );\n\n // Generate the initial prediction for every user message.\n const userPredictions = await Promise.all(\n messageChunks.map(async (chatHistoryChunk) => ({\n userPredictions: await this.predictNextUserMessage(\n chatHistoryChunk.chunkedMessages\n ),\n userResponse: chatHistoryChunk.userResponse,\n runManager,\n }))\n );\n\n // Generate insights, and prediction violations for every user message.\n // This call also regenerates the prediction based on the violations.\n const predictionViolations = await Promise.all(\n userPredictions.map((prediction) =>\n this.getPredictionViolations({\n userPredictions: prediction.userPredictions,\n userResponse: prediction.userResponse,\n runManager,\n })\n )\n );\n\n // Generate a fact/insight about the user for every set of messages.\n const insights = await Promise.all(\n predictionViolations.map((violation) =>\n this.generateFacts({\n userResponse: violation.userResponse,\n predictions: {\n revisedPrediction: violation.revisedPrediction,\n explainedPredictionErrors: violation.explainedPredictionErrors,\n },\n })\n )\n );\n\n return {\n insights,\n };\n }\n\n /**\n * This method predicts the next user message based on the chat history.\n *\n * @param {BaseMessage[]} chatHistory - The chat history based on which the next user message is predicted.\n * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<PredictNextUserMessageResponse>} A promise that resolves to the predicted next user message, the user state, and any insights.\n *\n * @throws {Error} If the response from the language model does not contain the expected keys: 'userState', 'predictedUserMessage', and 'insights'.\n */\n private async predictNextUserMessage(\n chatHistory: BaseMessage[],\n runManager?: CallbackManagerForChainRun\n ): Promise<PredictNextUserMessageResponse> {\n const messageString = this.getChatHistoryString(chatHistory);\n\n const llmWithFunctions = this.llm\n .bindTools([PREDICT_NEXT_USER_MESSAGE_FUNCTION])\n .withConfig({\n function_call: { name: PREDICT_NEXT_USER_MESSAGE_FUNCTION.name },\n });\n\n const chain = PREDICT_NEXT_USER_MESSAGE_PROMPT.pipe(llmWithFunctions).pipe(\n this.jsonOutputParser\n );\n\n const res = await chain.invoke(\n {\n chat_history: messageString,\n },\n runManager?.getChild(\"prediction\")\n );\n\n if (\n !(\n \"userState\" in res &&\n \"predictedUserMessage\" in res &&\n \"insights\" in res\n )\n ) {\n throw new Error(`Invalid response from LLM: ${JSON.stringify(res)}`);\n }\n\n const predictionResponse = res as PredictNextUserMessageResponse;\n\n // Query the retriever for relevant insights. Use the generates insights as a query.\n const retrievedDocs = await this.retrieveRelevantInsights(\n predictionResponse.insights\n );\n const relevantDocs = this.removeDuplicateStrings([\n ...predictionResponse.insights,\n ...retrievedDocs,\n ]);\n\n return {\n ...predictionResponse,\n insights: relevantDocs,\n };\n }\n\n /**\n * Retrieves relevant insights based on the provided insights.\n *\n * @param {Array<string>} insights - An array of insights to be used for retrieving relevant documents.\n *\n * @returns {Promise<Array<string>>} A promise that resolves to an array of relevant insights content.\n */\n private async retrieveRelevantInsights(\n insights: Array<string>\n ): Promise<Array<string>> {\n // Only extract the first relevant doc from the retriever. We don't need more than one.\n const relevantInsightsDocuments = await Promise.all(\n insights.map(async (insight) => {\n const relevantInsight = await this.retriever.invoke(insight);\n return relevantInsight[0];\n })\n );\n\n const relevantInsightsContent = relevantInsightsDocuments.map(\n (document) => document.pageContent\n );\n\n return relevantInsightsContent;\n }\n\n /**\n * This method generates prediction violations based on the predicted and actual user responses.\n * It also generates a revised prediction based on the identified violations.\n *\n * @param {Object} params - The parameters for the method.\n * @param {PredictNextUserMessageResponse} params.userPredictions - The predicted user message, user state, and insights.\n * @param {BaseMessage} [params.userResponse] - The actual user response.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<{ userResponse: BaseMessage | undefined; revisedPrediction: string; explainedPredictionErrors: Array<string>; }>} A promise that resolves to an object containing the actual user response, the revised prediction, and the explained prediction errors.\n *\n * @throws {Error} If the response from the language model does not contain the expected keys: 'violationExplanation', 'explainedPredictionErrors', and 'accuratePrediction'.\n */\n private async getPredictionViolations({\n userPredictions,\n userResponse,\n runManager,\n }: {\n userPredictions: PredictNextUserMessageResponse;\n userResponse?: BaseMessage;\n runManager?: CallbackManagerForChainRun;\n }): Promise<GetPredictionViolationsResponse> {\n const llmWithFunctions = this.llm\n .bindTools([PREDICTION_VIOLATIONS_FUNCTION])\n .withConfig({\n function_call: { name: PREDICTION_VIOLATIONS_FUNCTION.name },\n });\n\n const chain = PREDICTION_VIOLATIONS_PROMPT.pipe(llmWithFunctions).pipe(\n this.jsonOutputParser\n );\n\n if (typeof userResponse?.content !== \"string\") {\n throw new Error(\"This chain does not support non-string model output.\");\n }\n const res = (await chain.invoke(\n {\n predicted_output: userPredictions.predictedUserMessage,\n actual_output: userResponse?.content ?? \"\",\n user_insights: userPredictions.insights.join(\"\\n\"),\n },\n runManager?.getChild(\"prediction_violations\")\n )) as Awaited<{\n violationExplanation: string;\n explainedPredictionErrors: Array<string>;\n accuratePrediction: boolean;\n }>;\n\n // Generate a revised prediction based on violations.\n const revisedPrediction = await this.generateRevisedPrediction({\n originalPrediction: userPredictions.predictedUserMessage,\n explainedPredictionErrors: res.explainedPredictionErrors,\n userInsights: userPredictions.insights,\n runManager,\n });\n\n return {\n userResponse,\n revisedPrediction,\n explainedPredictionErrors: res.explainedPredictionErrors,\n };\n }\n\n /**\n * This method generates a revised prediction based on the original prediction, explained prediction errors, and user insights.\n *\n * @param {Object} params - The parameters for the method.\n * @param {string} params.originalPrediction - The original prediction made by the model.\n * @param {Array<string>} params.explainedPredictionErrors - An array of explained prediction errors.\n * @param {Array<string>} params.userInsights - An array of insights about the user.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<string>} A promise that resolves to a revised prediction.\n */\n private async generateRevisedPrediction({\n originalPrediction,\n explainedPredictionErrors,\n userInsights,\n runManager,\n }: {\n originalPrediction: string;\n explainedPredictionErrors: Array<string>;\n userInsights: Array<string>;\n runManager?: CallbackManagerForChainRun;\n }): Promise<string> {\n const revisedPredictionChain = GENERATE_REVISED_PREDICTION_PROMPT.pipe(\n this.llm\n ).pipe(this.stringOutputParser);\n\n const revisedPredictionRes = await revisedPredictionChain.invoke(\n {\n prediction: originalPrediction,\n explained_prediction_errors: explainedPredictionErrors.join(\"\\n\"),\n user_insights: userInsights.join(\"\\n\"),\n },\n runManager?.getChild(\"prediction_revision\")\n );\n\n return revisedPredictionRes;\n }\n\n /**\n * This method generates facts or insights about the user based on the revised prediction, explained prediction errors, and the user's response.\n *\n * @param {Object} params - The parameters for the method.\n * @param {BaseMessage} [params.userResponse] - The actual user response.\n * @param {Object} params.predictions - The revised prediction and explained prediction errors.\n * @param {string} params.predictions.revisedPrediction - The revised prediction made by the model.\n * @param {Array<string>} params.predictions.explainedPredictionErrors - An array of explained prediction errors.\n * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.\n *\n * @returns {Promise<string>} A promise that resolves to a string containing the generated facts or insights about the user.\n */\n private async generateFacts({\n userResponse,\n predictions,\n runManager,\n }: {\n userResponse?: BaseMessage;\n /**\n * Optional if the prediction was accurate.\n */\n predictions: {\n revisedPrediction: string;\n explainedPredictionErrors: Array<string>;\n };\n runManager?: CallbackManagerForChainRun;\n }): Promise<string> {\n const chain = GENERATE_FACTS_PROMPT.pipe(this.llm).pipe(\n this.stringOutputParser\n );\n\n if (typeof userResponse?.content !== \"string\") {\n throw new Error(\"This chain does not support non-string model output.\");\n }\n const res = await chain.invoke(\n {\n prediction_violations: predictions.explainedPredictionErrors.join(\"\\n\"),\n prediction: predictions.revisedPrediction,\n user_message: userResponse?.content ?? \"\",\n },\n runManager?.getChild(\"generate_facts\")\n );\n\n return res;\n }\n\n /**\n * Static method that creates a ViolationOfExpectationsChain instance from a\n * ChatOpenAI and retriever. It also accepts optional options\n * to customize the chain.\n *\n * @param llm The ChatOpenAI instance.\n * @param retriever The retriever used for similarity search.\n * @param options Optional options to customize the chain.\n *\n * @returns A new instance of ViolationOfExpectationsChain.\n */\n static fromLLM(\n llm: ChatOpenAI,\n retriever: BaseRetrieverInterface,\n options?: Partial<\n Omit<ViolationOfExpectationsChainInput, \"llm\" | \"retriever\">\n >\n ): ViolationOfExpectationsChain {\n return new this({\n retriever,\n llm,\n ...options,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,IAAa,+BAAb,cACUA,aAAAA,UAEV;CACE,OAAO,UAAU;AACf,SAAO;;CAGT,aAAqB;AACnB,SAAO;;CAGT,iBAAiB;CAEjB,cAAc;CAEd,IAAI,YAAY;AACd,SAAO,CAAC,KAAK,eAAe;;CAG9B,IAAI,aAAa;AACf,SAAO,CAAC,KAAK,YAAY;;CAG3B;CAEA;CAEA;CAEA;CAEA,YAAY,QAA2C;AACrD,QAAM,OAAO;AACb,OAAK,YAAY,OAAO;AACxB,OAAK,MAAM,OAAO;AAClB,OAAK,mBAAmB,IAAIC,yBAAAA,2BAA2B;AACvD,OAAK,qBAAqB,IAAIC,+BAAAA,oBAAoB;;CAGpD,qBAAqB,aAAoC;A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