|
| 1 | +import { getEnvironmentVariable } from "@langchain/core/utils/env"; |
| 2 | +import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings"; |
| 3 | +import { chunkArray } from "@langchain/core/utils/chunk_array"; |
| 4 | + |
| 5 | +/** |
| 6 | + * The default model name to use for generating embeddings. |
| 7 | + */ |
| 8 | +const DEFAULT_MODEL_NAME = "sentence-transformers/clip-ViT-B-32"; |
| 9 | + |
| 10 | +/** |
| 11 | + * The default batch size to use for generating embeddings. |
| 12 | + * This is limited by the DeepInfra API to a maximum of 1024. |
| 13 | + */ |
| 14 | +const DEFAULT_BATCH_SIZE = 1024; |
| 15 | + |
| 16 | +/** |
| 17 | + * Environment variable name for the DeepInfra API token. |
| 18 | + */ |
| 19 | +const API_TOKEN_ENV_VAR = "DEEPINFRA_API_TOKEN"; |
| 20 | + |
| 21 | +export interface DeepInfraEmbeddingsRequest { |
| 22 | + inputs: string[]; |
| 23 | + normalize?: boolean; |
| 24 | + image?: string; |
| 25 | + webhook?: string; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Input parameters for the DeepInfra embeddings |
| 30 | + */ |
| 31 | +export interface DeepInfraEmbeddingsParams extends EmbeddingsParams { |
| 32 | + /** |
| 33 | + * The API token to use for authentication. |
| 34 | + * If not provided, it will be read from the `DEEPINFRA_API_TOKEN` environment variable. |
| 35 | + */ |
| 36 | + apiToken?: string; |
| 37 | + |
| 38 | + /** |
| 39 | + * The model ID to use for generating completions. |
| 40 | + * Default: `sentence-transformers/clip-ViT-B-32` |
| 41 | + */ |
| 42 | + modelName?: string; |
| 43 | + |
| 44 | + /** |
| 45 | + * The maximum number of texts to embed in a single request. This is |
| 46 | + * limited by the DeepInfra API to a maximum of 1024. |
| 47 | + */ |
| 48 | + batchSize?: number; |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Response from the DeepInfra embeddings API. |
| 53 | + */ |
| 54 | +export interface DeepInfraEmbeddingsResponse { |
| 55 | + /** |
| 56 | + * The embeddings generated for the input texts. |
| 57 | + */ |
| 58 | + embeddings: number[][]; |
| 59 | + /** |
| 60 | + * The number of tokens in the input texts. |
| 61 | + */ |
| 62 | + input_tokens: number; |
| 63 | + /** |
| 64 | + * The status of the inference. |
| 65 | + */ |
| 66 | + request_id?: string; |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * A class for generating embeddings using the DeepInfra API. |
| 71 | + * @example |
| 72 | + * ```typescript |
| 73 | + * // Embed a query using the DeepInfraEmbeddings class |
| 74 | + * const model = new DeepInfraEmbeddings(); |
| 75 | + * const res = await model.embedQuery( |
| 76 | + * "What would be a good company name for a company that makes colorful socks?", |
| 77 | + * ); |
| 78 | + * console.log({ res }); |
| 79 | + * ``` |
| 80 | + */ |
| 81 | +export class DeepInfraEmbeddings |
| 82 | + extends Embeddings |
| 83 | + implements DeepInfraEmbeddingsParams |
| 84 | +{ |
| 85 | + apiToken: string; |
| 86 | + |
| 87 | + batchSize: number; |
| 88 | + |
| 89 | + modelName: string; |
| 90 | + |
| 91 | + /** |
| 92 | + * Constructor for the DeepInfraEmbeddings class. |
| 93 | + * @param fields - An optional object with properties to configure the instance. |
| 94 | + */ |
| 95 | + constructor( |
| 96 | + fields?: Partial<DeepInfraEmbeddingsParams> & { |
| 97 | + verbose?: boolean; |
| 98 | + } |
| 99 | + ) { |
| 100 | + const fieldsWithDefaults = { |
| 101 | + modelName: DEFAULT_MODEL_NAME, |
| 102 | + batchSize: DEFAULT_BATCH_SIZE, |
| 103 | + ...fields, |
| 104 | + }; |
| 105 | + |
| 106 | + super(fieldsWithDefaults); |
| 107 | + |
| 108 | + const apiKey = |
| 109 | + fieldsWithDefaults?.apiToken || getEnvironmentVariable(API_TOKEN_ENV_VAR); |
| 110 | + |
| 111 | + if (!apiKey) { |
| 112 | + throw new Error("DeepInfra API token not found"); |
| 113 | + } |
| 114 | + |
| 115 | + this.modelName = fieldsWithDefaults?.modelName ?? this.modelName; |
| 116 | + this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize; |
| 117 | + this.apiToken = apiKey; |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Generates embeddings for an array of texts. |
| 122 | + * @param inputs - An array of strings to generate embeddings for. |
| 123 | + * @returns A Promise that resolves to an array of embeddings. |
| 124 | + */ |
| 125 | + async embedDocuments(inputs: string[]): Promise<number[][]> { |
| 126 | + const batches = chunkArray(inputs, this.batchSize); |
| 127 | + |
| 128 | + const batchRequests = batches.map((batch: string[]) => |
| 129 | + this.embeddingWithRetry({ |
| 130 | + inputs: batch, |
| 131 | + }) |
| 132 | + ); |
| 133 | + |
| 134 | + const batchResponses = await Promise.all(batchRequests); |
| 135 | + |
| 136 | + const out: number[][] = []; |
| 137 | + |
| 138 | + for (let i = 0; i < batchResponses.length; i += 1) { |
| 139 | + const batch = batches[i]; |
| 140 | + const { embeddings } = batchResponses[i]; |
| 141 | + for (let j = 0; j < batch.length; j += 1) { |
| 142 | + out.push(embeddings[j]); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + return out; |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * Generates an embedding for a single text. |
| 151 | + * @param text - A string to generate an embedding for. |
| 152 | + * @returns A Promise that resolves to an array of numbers representing the embedding. |
| 153 | + */ |
| 154 | + async embedQuery(text: string): Promise<number[]> { |
| 155 | + const { embeddings } = await this.embeddingWithRetry({ |
| 156 | + inputs: [text], |
| 157 | + }); |
| 158 | + return embeddings[0]; |
| 159 | + } |
| 160 | + |
| 161 | + /** |
| 162 | + * Generates embeddings with retry capabilities. |
| 163 | + * @param request - An object containing the request parameters for generating embeddings. |
| 164 | + * @returns A Promise that resolves to the API response. |
| 165 | + */ |
| 166 | + private async embeddingWithRetry( |
| 167 | + request: DeepInfraEmbeddingsRequest |
| 168 | + ): Promise<DeepInfraEmbeddingsResponse> { |
| 169 | + const response = await this.caller.call(() => |
| 170 | + fetch(`https://api.deepinfra.com/v1/inference/${this.modelName}`, { |
| 171 | + method: "POST", |
| 172 | + headers: { |
| 173 | + Authorization: `Bearer ${this.apiToken}`, |
| 174 | + "Content-Type": "application/json", |
| 175 | + }, |
| 176 | + body: JSON.stringify(request), |
| 177 | + }).then((res) => res.json()) |
| 178 | + ); |
| 179 | + return response as DeepInfraEmbeddingsResponse; |
| 180 | + } |
| 181 | +} |
0 commit comments