{"version":3,"file":"chat_vector_db_chain.cjs","names":["BaseChain","LLMChain","PromptTemplate","loadQAStuffChain"],"sources":["../../src/chains/chat_vector_db_chain.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport type { VectorStoreInterface } from \"@langchain/core/vectorstores\";\nimport { ChainValues } from \"@langchain/core/utils/types\";\nimport { CallbackManagerForChainRun } from \"@langchain/core/callbacks/manager\";\nimport { PromptTemplate } from \"@langchain/core/prompts\";\nimport { SerializedChatVectorDBQAChain } from \"./serde.js\";\nimport { BaseChain, ChainInputs } from \"./base.js\";\nimport { LLMChain } from \"./llm_chain.js\";\nimport { loadQAStuffChain } from \"./question_answering/load.js\";\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LoadValues = Record<string, any>;\n\nconst question_generator_template = `Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:`;\n\nconst qa_template = `Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:`;\n\n/**\n * Interface for the input parameters of the ChatVectorDBQAChain class.\n */\nexport interface ChatVectorDBQAChainInput extends ChainInputs {\n  vectorstore: VectorStoreInterface;\n  combineDocumentsChain: BaseChain;\n  questionGeneratorChain: LLMChain;\n  returnSourceDocuments?: boolean;\n  outputKey?: string;\n  inputKey?: string;\n  k?: number;\n}\n\n/** @deprecated use `ConversationalRetrievalQAChain` instead. */\nexport class ChatVectorDBQAChain\n  extends BaseChain\n  implements ChatVectorDBQAChainInput\n{\n  k = 4;\n\n  inputKey = \"question\";\n\n  chatHistoryKey = \"chat_history\";\n\n  get inputKeys() {\n    return [this.inputKey, this.chatHistoryKey];\n  }\n\n  outputKey = \"result\";\n\n  get outputKeys() {\n    return [this.outputKey];\n  }\n\n  vectorstore: VectorStoreInterface;\n\n  combineDocumentsChain: BaseChain;\n\n  questionGeneratorChain: LLMChain;\n\n  returnSourceDocuments = false;\n\n  constructor(fields: ChatVectorDBQAChainInput) {\n    super(fields);\n    this.vectorstore = fields.vectorstore;\n    this.combineDocumentsChain = fields.combineDocumentsChain;\n    this.questionGeneratorChain = fields.questionGeneratorChain;\n    this.inputKey = fields.inputKey ?? this.inputKey;\n    this.outputKey = fields.outputKey ?? this.outputKey;\n    this.k = fields.k ?? this.k;\n    this.returnSourceDocuments =\n      fields.returnSourceDocuments ?? this.returnSourceDocuments;\n  }\n\n  /** @ignore */\n  async _call(\n    values: ChainValues,\n    runManager?: CallbackManagerForChainRun\n  ): Promise<ChainValues> {\n    if (!(this.inputKey in values)) {\n      throw new Error(`Question key ${this.inputKey} not found.`);\n    }\n    if (!(this.chatHistoryKey in values)) {\n      throw new Error(`chat history key ${this.inputKey} not found.`);\n    }\n    const question: string = values[this.inputKey];\n    const chatHistory: string = values[this.chatHistoryKey];\n    let newQuestion = question;\n    if (chatHistory.length > 0) {\n      const result = await this.questionGeneratorChain.call(\n        {\n          question,\n          chat_history: chatHistory,\n        },\n        runManager?.getChild(\"question_generator\")\n      );\n      const keys = Object.keys(result);\n      console.log(\"_call\", values, keys);\n      if (keys.length === 1) {\n        newQuestion = result[keys[0]];\n      } else {\n        throw new Error(\n          \"Return from llm chain has multiple values, only single values supported.\"\n        );\n      }\n    }\n    const docs = await this.vectorstore.similaritySearch(\n      newQuestion,\n      this.k,\n      undefined,\n      runManager?.getChild(\"vectorstore\")\n    );\n    const inputs = {\n      question: newQuestion,\n      input_documents: docs,\n      chat_history: chatHistory,\n    };\n    const result = await this.combineDocumentsChain.call(\n      inputs,\n      runManager?.getChild(\"combine_documents\")\n    );\n    if (this.returnSourceDocuments) {\n      return {\n        ...result,\n        sourceDocuments: docs,\n      };\n    }\n    return result;\n  }\n\n  _chainType() {\n    return \"chat-vector-db\" as const;\n  }\n\n  static async deserialize(\n    data: SerializedChatVectorDBQAChain,\n    values: LoadValues\n  ) {\n    if (!(\"vectorstore\" in values)) {\n      throw new Error(\n        `Need to pass in a vectorstore to deserialize VectorDBQAChain`\n      );\n    }\n    const { vectorstore } = values;\n\n    return new ChatVectorDBQAChain({\n      combineDocumentsChain: await BaseChain.deserialize(\n        data.combine_documents_chain\n      ),\n      questionGeneratorChain: await LLMChain.deserialize(\n        data.question_generator\n      ),\n      k: data.k,\n      vectorstore,\n    });\n  }\n\n  serialize(): SerializedChatVectorDBQAChain {\n    return {\n      _type: this._chainType(),\n      combine_documents_chain: this.combineDocumentsChain.serialize(),\n      question_generator: this.questionGeneratorChain.serialize(),\n      k: this.k,\n    };\n  }\n\n  /**\n   * Creates an instance of ChatVectorDBQAChain using a BaseLanguageModel\n   * and other options.\n   * @param llm Instance of BaseLanguageModel used to generate a new question.\n   * @param vectorstore Instance of VectorStore used for vector operations.\n   * @param options (Optional) Additional options for creating the ChatVectorDBQAChain instance.\n   * @returns New instance of ChatVectorDBQAChain.\n   */\n  static fromLLM(\n    llm: BaseLanguageModelInterface,\n    vectorstore: VectorStoreInterface,\n    options: {\n      inputKey?: string;\n      outputKey?: string;\n      k?: number;\n      returnSourceDocuments?: boolean;\n      questionGeneratorTemplate?: string;\n      qaTemplate?: string;\n      verbose?: boolean;\n    } = {}\n  ): ChatVectorDBQAChain {\n    const { questionGeneratorTemplate, qaTemplate, verbose, ...rest } = options;\n    const question_generator_prompt = PromptTemplate.fromTemplate(\n      questionGeneratorTemplate || question_generator_template\n    );\n    const qa_prompt = PromptTemplate.fromTemplate(qaTemplate || qa_template);\n\n    const qaChain = loadQAStuffChain(llm, { prompt: qa_prompt, verbose });\n    const questionGeneratorChain = new LLMChain({\n      prompt: question_generator_prompt,\n      llm,\n      verbose,\n    });\n    const instance = new this({\n      vectorstore,\n      combineDocumentsChain: qaChain,\n      questionGeneratorChain,\n      ...rest,\n    });\n    return instance;\n  }\n}\n"],"mappings":";;;;;;AAaA,MAAM,8BAA8B;;;;;;AAOpC,MAAM,cAAc;;;;;;;AAqBpB,IAAa,sBAAb,MAAa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