UNPKG

@langchain/community

Version:
1 lines 7.24 kB
{"version":3,"file":"base.cjs","names":["Embeddings"],"sources":["../../../src/embeddings/tencent_hunyuan/base.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings, type EmbeddingsParams } from \"@langchain/core/embeddings\";\nimport { sign } from \"../../utils/tencent_hunyuan/common.js\";\n\n/**\n * Interface that extends EmbeddingsParams and defines additional\n * parameters specific to the TencentHunyuanEmbeddingsParams class.\n */\nexport interface TencentHunyuanEmbeddingsParams extends EmbeddingsParams {\n /**\n * Tencent Cloud API Host.\n * @default \"hunyuan.tencentcloudapi.com\"\n */\n host?: string;\n\n /**\n * SecretID to use when making requests, can be obtained from https://console.cloud.tencent.com/cam/capi.\n * Defaults to the value of `TENCENT_SECRET_ID` environment variable.\n */\n tencentSecretId?: string;\n\n /**\n * Secret key to use when making requests, can be obtained from https://console.cloud.tencent.com/cam/capi.\n * Defaults to the value of `TENCENT_SECRET_KEY` environment variable.\n */\n tencentSecretKey?: string;\n}\n\n/**\n * Interface that extends EmbeddingsParams and defines additional\n * parameters specific to the TencentHunyuanEmbeddingsParams class.\n */\ninterface TencentHunyuanEmbeddingsParamsWithSign extends TencentHunyuanEmbeddingsParams {\n /**\n * Tencent Cloud API v3 sign method.\n */\n sign: sign;\n}\n\n/**\n * Interface representing the embedding data.\n * See https://cloud.tencent.com/document/api/1729/101838#EmbeddingData.\n */\ninterface EmbeddingData {\n Embedding: number[];\n Index: number;\n Object: string;\n}\n\n/**\n * Interface representing the usage of tokens in text embedding.\n * See https://cloud.tencent.com/document/api/1729/101838#EmbeddingUsage.\n */\ninterface EmbeddingUsage {\n TotalTokens: number;\n PromptTokens: number;\n CompletionTokens?: number;\n}\n\n/**\n * Interface representing a error response from Tencent Hunyuan embedding.\n * See https://cloud.tencent.com/document/product/1729/102832\n */\ninterface Error {\n Code: string;\n Message: string;\n}\n\n/**\n * Interface representing a response from Tencent Hunyuan embedding.\n * See https://cloud.tencent.com/document/product/1729/102832\n */\ninterface GetEmbeddingResponse {\n Response: {\n Error?: Error;\n Data: EmbeddingData[];\n Usage: EmbeddingUsage;\n RequestId: string;\n };\n}\n\n/**\n * Class for generating embeddings using the Tencent Hunyuan API.\n */\nexport class TencentHunyuanEmbeddings\n extends Embeddings\n implements TencentHunyuanEmbeddingsParams\n{\n tencentSecretId?: string;\n\n tencentSecretKey?: string;\n\n host = \"hunyuan.tencentcloudapi.com\";\n\n sign: sign;\n\n constructor(fields?: TencentHunyuanEmbeddingsParamsWithSign) {\n super(fields ?? {});\n\n this.tencentSecretId =\n fields?.tencentSecretId ?? getEnvironmentVariable(\"TENCENT_SECRET_ID\");\n if (!this.tencentSecretId) {\n throw new Error(\"Tencent SecretID not found\");\n }\n\n this.tencentSecretKey =\n fields?.tencentSecretKey ?? getEnvironmentVariable(\"TENCENT_SECRET_KEY\");\n if (!this.tencentSecretKey) {\n throw new Error(\"Tencent SecretKey not found\");\n }\n\n this.host = fields?.host ?? this.host;\n if (!fields?.sign) {\n throw new Error(\"Sign method undefined\");\n }\n this.sign = fields?.sign;\n }\n\n /**\n * Private method to make a request to the TogetherAI API to generate\n * embeddings. Handles the retry logic and returns the response from the API.\n * @param {string} input The input text to embed.\n * @returns Promise that resolves to the response from the API.\n * @TODO Figure out return type and statically type it.\n */\n private async embeddingWithRetry(\n input: string\n ): Promise<GetEmbeddingResponse> {\n const request = { Input: input };\n const timestamp = Math.trunc(Date.now() / 1000);\n const headers = {\n \"Content-Type\": \"application/json\",\n \"X-TC-Action\": \"GetEmbedding\",\n \"X-TC-Version\": \"2023-09-01\",\n \"X-TC-Timestamp\": timestamp.toString(),\n Authorization: \"\",\n };\n\n headers.Authorization = this.sign(\n this.host,\n request,\n timestamp,\n this.tencentSecretId ?? \"\",\n this.tencentSecretKey ?? \"\",\n headers\n );\n\n return this.caller.call(async () => {\n const response = await fetch(`https://${this.host}`, {\n headers,\n method: \"POST\",\n body: JSON.stringify(request),\n });\n\n if (response.ok) {\n return response.json();\n }\n\n throw new Error(\n `Error getting embeddings from Tencent Hunyuan. ${JSON.stringify(\n await response.json(),\n null,\n 2\n )}`\n );\n });\n }\n\n /**\n * Method to generate an embedding for a single document. Calls the\n * embeddingWithRetry method with the document as the input.\n * @param {string} text Document to generate an embedding for.\n * @returns {Promise<number[]>} Promise that resolves to an embedding for the document.\n */\n async embedQuery(text: string): Promise<number[]> {\n const { Response } = await this.embeddingWithRetry(text);\n if (Response?.Error?.Message) {\n throw new Error(`[${Response.RequestId}] ${Response.Error.Message}`);\n }\n return Response.Data[0].Embedding;\n }\n\n /**\n * Method that takes an array of documents as input and returns a promise\n * that resolves to a 2D array of embeddings for each document. It calls\n * the embedQuery method for each document in the array.\n * @param documents Array of documents for which to generate embeddings.\n * @returns Promise that resolves to a 2D array of embeddings for each input document.\n */\n embedDocuments(documents: string[]): Promise<number[][]> {\n return Promise.all(documents.map((doc) => this.embedQuery(doc)));\n }\n}\n"],"mappings":";;;;;;;AAoFA,IAAa,2BAAb,cACUA,2BAAAA,WAEV;CACE;CAEA;CAEA,OAAO;CAEP;CAEA,YAAY,QAAiD;AAC3D,QAAM,UAAU,EAAE,CAAC;AAEnB,OAAK,kBACH,QAAQ,oBAAA,GAAA,0BAAA,wBAA0C,oBAAoB;AACxE,MAAI,CAAC,KAAK,gBACR,OAAM,IAAI,MAAM,6BAA6B;AAG/C,OAAK,mBACH,QAAQ,qBAAA,GAAA,0BAAA,wBAA2C,qBAAqB;AAC1E,MAAI,CAAC,KAAK,iBACR,OAAM,IAAI,MAAM,8BAA8B;AAGhD,OAAK,OAAO,QAAQ,QAAQ,KAAK;AACjC,MAAI,CAAC,QAAQ,KACX,OAAM,IAAI,MAAM,wBAAwB;AAE1C,OAAK,OAAO,QAAQ;;;;;;;;;CAUtB,MAAc,mBACZ,OAC+B;EAC/B,MAAM,UAAU,EAAE,OAAO,OAAO;EAChC,MAAM,YAAY,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;EAC/C,MAAM,UA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