{"version":3,"file":"agent.cjs","names":["AutoGPTOutputParser","LLMChain","AutoGPTPrompt","HumanMessage","AIMessage","SystemMessage"],"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,aAAA,GAAA,qCAAA,yBACJ,eAAe,OAAO,YAAY,aAC7B,OAAO,YAAY,WAAW,YAC/B,KAAA,EACL;AACD,OAAK,eAAe,IAAA,sBAAA,sBAAI,kBAAkB;GACxC;GACA,cAAc,KAAK,MAAM,YAAY,GAAG;GACzC,CAAC;;;;;;;;;;;;;CAcJ,OAAO,gBACL,KACA,OACA,EACE,QACA,QACA,QACA,gBAAgB,KAEhB,eAAe,IAAIA,sBAAAA,qBAAqB,IAEjC;AAYT,SAAO,IAAI,QAAQ;GACjB;GACA;GACA,OAJY,IAAIC,kBAAAA,SAAS;IAAE;IAAK,QAVnB,IAAIC,eAAAA,cAAc;KAC/B;KACA;KACA;KACA,cAAc,IAAI,aAAa,KAAK,IAAI;KACxC,iBAAA,GAAA,qCAAA,qBACE,eAAe,MAAO,IAAI,YAAuB,OAClD;KACF,CAAC;IAEwC,CAAC;GAKzC;GACA;GAEA;GACD,CAAC;;;;;;;CAQJ,MAAM,IAAI,OAA8C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