{"version":3,"file":"embeddings.cjs","names":["GoogleAIConnection","Embeddings","ApiKeyGoogleAuth"],"sources":["../src/embeddings.ts"],"sourcesContent":["import { Embeddings } from \"@langchain/core/embeddings\";\nimport {\n  AsyncCaller,\n  AsyncCallerCallOptions,\n} from \"@langchain/core/utils/async_caller\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\nimport { GoogleAIConnection } from \"./connection.js\";\nimport { ApiKeyGoogleAuth, GoogleAbstractedClient } from \"./auth.js\";\nimport {\n  BaseGoogleEmbeddingsOptions,\n  BaseGoogleEmbeddingsParams,\n  GoogleConnectionParams,\n  VertexEmbeddingsInstance,\n  GoogleEmbeddingsResponse,\n  VertexEmbeddingsParameters,\n  GoogleEmbeddingsRequest,\n  VertexEmbeddingsResponse,\n  AIStudioEmbeddingsResponse,\n  VertexEmbeddingsResponsePrediction,\n  AIStudioEmbeddingsRequest,\n  GeminiPartText,\n  VertexEmbeddingsRequest,\n} from \"./types.js\";\n\nclass EmbeddingsConnection<\n  CallOptions extends AsyncCallerCallOptions,\n  AuthOptions,\n> extends GoogleAIConnection<\n  CallOptions,\n  VertexEmbeddingsInstance[],\n  AuthOptions,\n  GoogleEmbeddingsResponse\n> {\n  convertSystemMessageToHumanContent: boolean | undefined;\n\n  constructor(\n    fields: BaseGoogleEmbeddingsParams<AuthOptions> | undefined,\n    caller: AsyncCaller,\n    client: GoogleAbstractedClient,\n    streaming: boolean\n  ) {\n    super(fields, caller, client, streaming);\n  }\n\n  buildUrlMethodAiStudio(): string {\n    return \"embedContent\";\n  }\n\n  buildUrlMethodVertex(): string {\n    return \"predict\";\n  }\n\n  async buildUrlMethod(): Promise<string> {\n    switch (this.platform) {\n      case \"gcp\":\n        return this.buildUrlMethodVertex();\n      case \"gai\":\n        return this.buildUrlMethodAiStudio();\n      default:\n        throw new Error(\n          `Unknown platform when building method: ${this.platform}`\n        );\n    }\n  }\n\n  get modelPublisher(): string {\n    // All the embedding models are currently published by \"google\"\n    return \"google\";\n  }\n\n  formatDataAiStudio(\n    input: VertexEmbeddingsInstance[],\n    parameters: VertexEmbeddingsParameters\n  ): AIStudioEmbeddingsRequest {\n    const parts: GeminiPartText[] = input.map(\n      (instance: VertexEmbeddingsInstance) => ({\n        text: instance.content,\n      })\n    );\n    const content = {\n      parts,\n    };\n    const outputDimensionality = parameters?.outputDimensionality;\n\n    const ret: AIStudioEmbeddingsRequest = {\n      content,\n      outputDimensionality,\n    };\n\n    // Remove undefined attributes\n    let key: keyof AIStudioEmbeddingsRequest;\n    for (key in ret) {\n      if (ret[key] === undefined) {\n        delete ret[key];\n      }\n    }\n\n    return ret;\n  }\n\n  formatDataVertex(\n    input: VertexEmbeddingsInstance[],\n    parameters: VertexEmbeddingsParameters\n  ): VertexEmbeddingsRequest {\n    return {\n      instances: input,\n      parameters,\n    };\n  }\n\n  async formatData(\n    input: VertexEmbeddingsInstance[],\n    parameters: VertexEmbeddingsParameters\n  ): Promise<GoogleEmbeddingsRequest> {\n    switch (this.platform) {\n      case \"gcp\":\n        return this.formatDataVertex(input, parameters);\n      case \"gai\":\n        return this.formatDataAiStudio(input, parameters);\n      default:\n        throw new Error(\n          `Unknown platform to format embeddings ${this.platform}`\n        );\n    }\n  }\n}\n\n/**\n * Enables calls to Google APIs for generating\n * text embeddings.\n */\nexport abstract class BaseGoogleEmbeddings<AuthOptions>\n  extends Embeddings\n  implements BaseGoogleEmbeddingsParams<AuthOptions>\n{\n  model: string;\n\n  dimensions?: number;\n\n  private connection: EmbeddingsConnection<\n    BaseGoogleEmbeddingsOptions,\n    AuthOptions\n  >;\n\n  constructor(fields: BaseGoogleEmbeddingsParams<AuthOptions>) {\n    super(fields);\n\n    this.model = fields.model;\n    this.dimensions = fields.dimensions ?? fields.outputDimensionality;\n\n    this.connection = new EmbeddingsConnection(\n      { ...fields, ...this },\n      this.caller,\n      this.buildClient(fields),\n      false\n    );\n  }\n\n  abstract buildAbstractedClient(\n    fields?: GoogleConnectionParams<AuthOptions>\n  ): GoogleAbstractedClient;\n\n  buildApiKeyClient(apiKey: string): GoogleAbstractedClient {\n    return new ApiKeyGoogleAuth(apiKey);\n  }\n\n  buildApiKey(\n    fields?: GoogleConnectionParams<AuthOptions>\n  ): string | undefined {\n    return fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n  }\n\n  buildClient(\n    fields?: GoogleConnectionParams<AuthOptions>\n  ): GoogleAbstractedClient {\n    const apiKey = this.buildApiKey(fields);\n    if (apiKey) {\n      return this.buildApiKeyClient(apiKey);\n    } else {\n      return this.buildAbstractedClient(fields);\n    }\n  }\n\n  buildParameters(): VertexEmbeddingsParameters {\n    const ret: VertexEmbeddingsParameters = {\n      outputDimensionality: this.dimensions,\n    };\n\n    // Remove undefined attributes\n    let key: keyof VertexEmbeddingsParameters;\n    for (key in ret) {\n      if (ret[key] === undefined) {\n        delete ret[key];\n      }\n    }\n\n    return ret;\n  }\n\n  vertexResponseToValues(response: VertexEmbeddingsResponse): number[][] {\n    const predictions: VertexEmbeddingsResponsePrediction[] =\n      response?.data?.predictions ?? [];\n    return predictions.map(\n      (prediction: VertexEmbeddingsResponsePrediction): number[] =>\n        prediction.embeddings.values\n    );\n  }\n\n  aiStudioResponseToValues(response: AIStudioEmbeddingsResponse): number[][] {\n    const value: number[] = response?.data?.embedding?.values ?? [];\n    return [value];\n  }\n\n  responseToValues(response: GoogleEmbeddingsResponse): number[][] {\n    switch (this.connection.platform) {\n      case \"gcp\":\n        return this.vertexResponseToValues(\n          response as VertexEmbeddingsResponse\n        );\n      case \"gai\":\n        return this.aiStudioResponseToValues(\n          response as AIStudioEmbeddingsResponse\n        );\n      default:\n        throw new Error(\n          `Unknown response platform: ${this.connection.platform}`\n        );\n    }\n  }\n\n  /**\n   * Takes an array of documents as input and returns a promise that\n   * resolves to a 2D array of embeddings for each document. It splits the\n   * documents into chunks and makes requests to the Google Vertex AI API to\n   * generate embeddings.\n   * @param documents An array of documents to be embedded.\n   * @returns A promise that resolves to a 2D array of embeddings for each document.\n   */\n  async embedDocuments(documents: string[]): Promise<number[][]> {\n    // Vertex \"text-\" models could do up 5 documents at once,\n    // but the \"gemini-embedding-001\" can only do 1.\n    // AI Studio can only do a chunk size of 1.\n    // TODO: Make this configurable\n    const chunkSize = 1;\n    const instanceChunks: VertexEmbeddingsInstance[][] = chunkArray(\n      documents.map((document) => ({\n        content: document,\n      })),\n      chunkSize\n    );\n    const parameters: VertexEmbeddingsParameters = this.buildParameters();\n    const options = {};\n    const responses = await Promise.all(\n      instanceChunks.map((instances) =>\n        this.connection.request(instances, parameters, options)\n      )\n    );\n    const result: number[][] =\n      responses?.map((response) => this.responseToValues(response)).flat() ??\n      [];\n    return result;\n  }\n\n  /**\n   * Takes a document as input and returns a promise that resolves to an\n   * embedding for the document. It calls the embedDocuments method with the\n   * document as the input.\n   * @param document A document to be embedded.\n   * @returns A promise that resolves to an embedding for the document.\n   */\n  async embedQuery(document: string): Promise<number[]> {\n    const data = await this.embedDocuments([document]);\n    return data[0];\n  }\n}\n"],"mappings":";;;;;;AA0BA,IAAM,uBAAN,cAGUA,mBAAAA,mBAKR;CACA;CAEA,YACE,QACA,QACA,QACA,WACA;AACA,QAAM,QAAQ,QAAQ,QAAQ,UAAU;;CAG1C,yBAAiC;AAC/B,SAAO;;CAGT,uBAA+B;AAC7B,SAAO;;CAGT,MAAM,iBAAkC;AACtC,UAAQ,KAAK,UAAb;GACE,KAAK,MACH,QAAO,KAAK,sBAAsB;GACpC,KAAK,MACH,QAAO,KAAK,wBAAwB;GACtC,QACE,OAAM,IAAI,MACR,0CAA0C,KAAK,WAChD;;;CAIP,IAAI,iBAAyB;AAE3B,SAAO;;CAGT,mBACE,OACA,YAC2B;EAW3B,MAAM,MAAiC;GACrC,SAAA,EALA,OAN8B,MAAM,KACnC,cAAwC,EACvC,MAAM,SAAS,SAChB,EAGI,EAKE;GACP,sBAJ2B,YAAY;GAKxC;EAGD,IAAI;AACJ,OAAK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