|
| 1 | +import { Embedding, EmbeddingModel } from '../types'; |
| 2 | +import { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff'; |
| 3 | + |
| 4 | +/** |
| 5 | +Embed a value using an embedding model. The type of the value is defined by the embedding model. |
| 6 | +
|
| 7 | +@param model - The embedding model to use. |
| 8 | +@param value - The value that should be embedded. |
| 9 | +
|
| 10 | +@param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. |
| 11 | +@param abortSignal - An optional abort signal that can be used to cancel the call. |
| 12 | +
|
| 13 | +@returns A result object that contains the embedding, the value, and additional information. |
| 14 | + */ |
| 15 | +export async function embed<VALUE>({ |
| 16 | + model, |
| 17 | + value, |
| 18 | + maxRetries, |
| 19 | + abortSignal, |
| 20 | +}: { |
| 21 | + /** |
| 22 | +The embedding model to use. |
| 23 | + */ |
| 24 | + model: EmbeddingModel<VALUE>; |
| 25 | + |
| 26 | + /** |
| 27 | +The value that should be embedded. |
| 28 | + */ |
| 29 | + value: VALUE; |
| 30 | + |
| 31 | + /** |
| 32 | +Maximum number of retries per embedding model call. Set to 0 to disable retries. |
| 33 | +
|
| 34 | +@default 2 |
| 35 | + */ |
| 36 | + maxRetries?: number; |
| 37 | + |
| 38 | + /** |
| 39 | +Abort signal. |
| 40 | + */ |
| 41 | + abortSignal?: AbortSignal; |
| 42 | +}): Promise<EmbedResult<VALUE>> { |
| 43 | + const retry = retryWithExponentialBackoff({ maxRetries }); |
| 44 | + |
| 45 | + const modelResponse = await retry(() => |
| 46 | + model.doEmbed({ |
| 47 | + values: [value], |
| 48 | + abortSignal, |
| 49 | + }), |
| 50 | + ); |
| 51 | + |
| 52 | + return new EmbedResult({ |
| 53 | + value, |
| 54 | + embedding: modelResponse.embeddings[0], |
| 55 | + rawResponse: modelResponse.rawResponse, |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | +The result of a `embed` call. |
| 61 | +It contains the embedding, the value, and additional information. |
| 62 | + */ |
| 63 | +export class EmbedResult<VALUE> { |
| 64 | + /** |
| 65 | +The value that was embedded. |
| 66 | + */ |
| 67 | + readonly value: VALUE; |
| 68 | + |
| 69 | + /** |
| 70 | +The embedding of the value. |
| 71 | + */ |
| 72 | + readonly embedding: Embedding; |
| 73 | + |
| 74 | + /** |
| 75 | +Optional raw response data. |
| 76 | + */ |
| 77 | + readonly rawResponse?: { |
| 78 | + /** |
| 79 | +Response headers. |
| 80 | + */ |
| 81 | + headers?: Record<string, string>; |
| 82 | + }; |
| 83 | + |
| 84 | + constructor(options: { |
| 85 | + value: VALUE; |
| 86 | + embedding: Embedding; |
| 87 | + rawResponse?: { |
| 88 | + headers?: Record<string, string>; |
| 89 | + }; |
| 90 | + }) { |
| 91 | + this.value = options.value; |
| 92 | + this.embedding = options.embedding; |
| 93 | + this.rawResponse = options.rawResponse; |
| 94 | + } |
| 95 | +} |
0 commit comments