{"version":3,"file":"hyde.cjs","names":["VectorStoreRetriever","StringPromptValue","PromptTemplate"],"sources":["../../src/retrievers/hyde.ts"],"sourcesContent":["import type { BaseLanguageModelInterface } from \"@langchain/core/language_models/base\";\nimport { Document } from \"@langchain/core/documents\";\nimport { PromptTemplate, BasePromptTemplate } from \"@langchain/core/prompts\";\nimport {\n  StringPromptValue,\n  BasePromptValue,\n} from \"@langchain/core/prompt_values\";\nimport {\n  VectorStore,\n  VectorStoreRetriever,\n  VectorStoreRetrieverInput,\n} from \"@langchain/core/vectorstores\";\nimport { CallbackManagerForRetrieverRun } from \"@langchain/core/callbacks/manager\";\n\n/**\n * A string that corresponds to a specific prompt template.\n */\nexport type PromptKey =\n  | \"websearch\"\n  | \"scifact\"\n  | \"arguana\"\n  | \"trec-covid\"\n  | \"fiqa\"\n  | \"dbpedia-entity\"\n  | \"trec-news\"\n  | \"mr-tydi\";\n\n/**\n * Options for the HydeRetriever class, which includes a BaseLanguageModel\n * instance, a VectorStore instance, and an optional promptTemplate which\n * can either be a BasePromptTemplate instance or a PromptKey.\n */\nexport type HydeRetrieverOptions<V extends VectorStore> =\n  VectorStoreRetrieverInput<V> & {\n    llm: BaseLanguageModelInterface;\n    promptTemplate?: BasePromptTemplate | PromptKey;\n  };\n\n/**\n * A class for retrieving relevant documents based on a given query. It\n * extends the VectorStoreRetriever class and uses a BaseLanguageModel to\n * generate a hypothetical answer to the query, which is then used to\n * retrieve relevant documents.\n * @example\n * ```typescript\n * const retriever = new HydeRetriever({\n *   vectorStore: new MemoryVectorStore(new OpenAIEmbeddings()),\n *   llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n *   k: 1,\n * });\n * await vectorStore.addDocuments(\n *   [\n *     \"My name is John.\",\n *     \"My name is Bob.\",\n *     \"My favourite food is pizza.\",\n *     \"My favourite food is pasta.\",\n *   ].map((pageContent) => new Document({ pageContent })),\n * );\n * const results = await retriever.invoke(\n *   \"What is my favourite food?\",\n * );\n * ```\n */\nexport class HydeRetriever<\n  V extends VectorStore = VectorStore,\n> extends VectorStoreRetriever<V> {\n  static lc_name() {\n    return \"HydeRetriever\";\n  }\n\n  get lc_namespace(): string[] {\n    return [\"langchain\", \"retrievers\", \"hyde\"];\n  }\n\n  llm: BaseLanguageModelInterface;\n\n  promptTemplate?: BasePromptTemplate;\n\n  constructor(fields: HydeRetrieverOptions<V>) {\n    super(fields);\n    this.llm = fields.llm;\n    this.promptTemplate =\n      typeof fields.promptTemplate === \"string\"\n        ? getPromptTemplateFromKey(fields.promptTemplate)\n        : fields.promptTemplate;\n    if (this.promptTemplate) {\n      const { inputVariables } = this.promptTemplate;\n      if (inputVariables.length !== 1 && inputVariables[0] !== \"question\") {\n        throw new Error(\n          `Prompt template must accept a single input variable 'question'. Invalid input variables for prompt template: ${inputVariables}`\n        );\n      }\n    }\n  }\n\n  async _getRelevantDocuments(\n    query: string,\n    runManager?: CallbackManagerForRetrieverRun\n  ): Promise<Document[]> {\n    let value: BasePromptValue = new StringPromptValue(query);\n\n    // Use a custom template if provided\n    if (this.promptTemplate) {\n      value = await this.promptTemplate.formatPromptValue({ question: query });\n    }\n\n    // Get a hypothetical answer from the LLM\n    const res = await this.llm.generatePrompt([value]);\n    const answer = res.generations[0][0].text;\n\n    // Retrieve relevant documents based on the hypothetical answer\n    const results = await this.vectorStore.similaritySearch(\n      answer,\n      this.k,\n      this.filter,\n      runManager?.getChild(\"vectorstore\")\n    );\n\n    return results;\n  }\n}\n\n/**\n * Returns a BasePromptTemplate instance based on a given PromptKey.\n */\nexport function getPromptTemplateFromKey(key: PromptKey): BasePromptTemplate {\n  let template: string;\n\n  switch (key) {\n    case \"websearch\":\n      template = `Please write a passage to answer the question\nQuestion: {question}\nPassage:`;\n      break;\n    case \"scifact\":\n      template = `Please write a scientific paper passage to support/refute the claim\nClaim: {question}\nPassage:`;\n      break;\n    case \"arguana\":\n      template = `Please write a counter argument for the passage\nPassage: {question}\nCounter Argument:`;\n      break;\n    case \"trec-covid\":\n      template = `Please write a scientific paper passage to answer the question\nQuestion: {question}\nPassage:`;\n      break;\n    case \"fiqa\":\n      template = `Please write a financial article passage to answer the question\nQuestion: {question}\nPassage:`;\n      break;\n    case \"dbpedia-entity\":\n      template = `Please write a passage to answer the question.\nQuestion: {question}\nPassage:`;\n      break;\n    case \"trec-news\":\n      template = `Please write a news passage about the topic.\nTopic: {question}\nPassage:`;\n      break;\n    case \"mr-tydi\":\n      template = `Please write a passage in Swahili/Korean/Japanese/Bengali to answer the question in detail.\nQuestion: {question}\nPassage:`;\n      break;\n    default:\n      throw new Error(`Invalid prompt key: ${key}`);\n  }\n\n  return PromptTemplate.fromTemplate(template);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAa,gBAAb,cAEUA,6BAAAA,qBAAwB;CAChC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,IAAI,eAAyB;EAC3B,OAAO;GAAC;GAAa;GAAc;EAAM;CAC3C;CAEA;CAEA;CAEA,YAAY,QAAiC;EAC3C,MAAM,MAAM;EACZ,KAAK,MAAM,OAAO;EAClB,KAAK,iBACH,OAAO,OAAO,mBAAmB,WAC7B,yBAAyB,OAAO,cAAc,IAC9C,OAAO;EACb,IAAI,KAAK,gBAAgB;GACvB,MAAM,EAAE,mBAAmB,KAAK;GAChC,IAAI,eAAe,WAAW,KAAK,eAAe,OAAO,YACvD,MAAM,IAAI,MACR,gHAAgH,gBAClH;EAEJ;CACF;CAEA,MAAM,sBACJ,OACA,YACqB;EACrB,IAAI,QAAyB,IAAIC,8BAAAA,kBAAkB,KAAK;EAGxD,IAAI,KAAK,gBACP,QAAQ,MAAM,KAAK,eAAe,kBAAkB,EAAE,UAAU,MAAM,CAAC;EAKzE,MAAM,UAAS,MADG,KAAK,IAAI,eAAe,CAAC,KAAK,CAAC,EAAA,CAC9B,YAAY,EAAE,CAAC,EAAE,CAAC;EAUrC,OAAO,MAPe,KAAK,YAAY,iBACrC,QACA,KAAK,GACL,KAAK,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