Repository navigation
Expand file tree
/
Copy pathbase-embedding-model-strategy.ts
More file actions
200 lines (181 loc) · 6.57 KB
/
Copy pathbase-embedding-model-strategy.ts
File metadata and controls
200 lines (181 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/** Base class for embedding model strategies using the Template Method pattern. */
import type {
EmbeddingModelV3CallOptions,
EmbeddingModelV3Embedding,
EmbeddingModelV3Result,
SharedV3Warning,
} from "@ai-sdk/provider";
import type { CustomRequestConfig } from "@sap-ai-sdk/core";
import { TooManyEmbeddingValuesForCallError } from "@ai-sdk/provider";
import type { SAPAIEmbeddingSettings } from "./sap-ai-settings.js";
import type { EmbeddingModelAPIStrategy, EmbeddingModelStrategyConfig } from "./sap-ai-strategy.js";
import { throwIfAborted, waitWithAbort } from "./abort-utils.js";
import { deepMerge } from "./deep-merge.js";
import { convertToAISDKError } from "./sap-ai-error.js";
import { getProviderName } from "./sap-ai-provider-options.js";
import {
buildEmbeddingResult,
type EmbeddingProviderOptions,
type EmbeddingType,
mergeRequestConfig,
type ResponseMetadata,
} from "./strategy-utils.js";
import { VERSION } from "./version.js";
/**
* Abstract base class for embedding model strategies using the Template Method pattern.
* @template TClient - The SDK client type (e.g., AzureOpenAiEmbeddingClient, OrchestrationEmbeddingClient).
* @template TResponse - The API response type from the SDK client.
* @internal
*/
export abstract class BaseEmbeddingModelStrategy<
TClient,
TResponse,
> implements EmbeddingModelAPIStrategy {
/**
* Template method implementing the shared embedding algorithm.
* @param config - Strategy configuration.
* @param settings - Embedding model settings.
* @param options - AI SDK call options.
* @param maxEmbeddingsPerCall - Maximum embeddings per call.
* @returns Complete embedding result for AI SDK.
* @internal
*/
async doEmbed(
config: EmbeddingModelStrategyConfig,
settings: SAPAIEmbeddingSettings,
options: EmbeddingModelV3CallOptions,
maxEmbeddingsPerCall: number,
): Promise<EmbeddingModelV3Result> {
const { abortSignal, values } = options;
try {
if (values.length > maxEmbeddingsPerCall) {
throw new TooManyEmbeddingValuesForCallError({
maxEmbeddingsPerCall,
modelId: config.modelId,
provider: config.provider,
values,
});
}
throwIfAborted(abortSignal);
const embeddingOptions = config.parsedProviderOptions;
const providerName = getProviderName(config.provider);
const embeddingType = embeddingOptions?.type ?? settings.type ?? "text";
const warnings: SharedV3Warning[] = [];
this.resolveWarnings(settings, warnings);
const client = this.createClient(config, settings, embeddingOptions);
const response = await waitWithAbort(
this.executeCall(
client,
values,
embeddingType,
mergeRequestConfig(config.requestConfig, abortSignal, options.headers),
),
abortSignal,
);
throwIfAborted(abortSignal);
const embeddings = this.extractEmbeddings(response);
const totalTokens = this.extractTokenCount(response);
const { headers: responseHeaders, requestId } = this.extractResponseMetadata(response);
return buildEmbeddingResult({
embeddings,
modelId: config.modelId,
providerName,
requestId,
responseHeaders,
totalTokens,
version: VERSION,
warnings,
});
} catch (error) {
if (error instanceof TooManyEmbeddingValuesForCallError) {
throw error;
}
throw convertToAISDKError(error, {
modelId: config.modelId,
modelType: "embeddingModel",
operation: "doEmbed",
requestBody: { values: values.length },
url: this.getUrl(),
});
}
}
/**
* Creates the appropriate SDK client for this API.
* @param config - Strategy configuration.
* @param settings - Embedding model settings.
* @param embeddingOptions - Parsed provider options from the call.
* @returns SDK client instance.
* @internal
*/
protected abstract createClient(
config: EmbeddingModelStrategyConfig,
settings: SAPAIEmbeddingSettings,
embeddingOptions: EmbeddingProviderOptions | undefined,
): TClient;
/**
* Executes the embedding API call.
* @param client - SDK client instance.
* @param values - Input strings to embed.
* @param embeddingType - Type of embedding (text, query, document).
* @param requestConfig - Request configuration with merged headers and abort signal.
* @returns SDK response containing embeddings.
* @internal
*/
protected abstract executeCall(
client: TClient,
values: string[],
embeddingType: EmbeddingType,
requestConfig: CustomRequestConfig | undefined,
): Promise<TResponse>;
/**
* Extracts embeddings from the SDK response.
* @param response - SDK response containing embedding data.
* @returns Array of normalized embedding vectors.
* @internal
*/
protected abstract extractEmbeddings(response: TResponse): EmbeddingModelV3Embedding[];
/**
* Extracts response metadata (request id and HTTP headers) from the SDK response.
*
* Default returns both fields as `undefined`; subclasses override to extract from the SDK response.
* @param _response - SDK response.
* @returns Combined `{ headers, requestId }` metadata.
* @internal
*/
protected extractResponseMetadata(_response: TResponse): ResponseMetadata {
return { headers: undefined, requestId: undefined };
}
/**
* Extracts total token count from the SDK response.
* @param response - SDK response containing usage data.
* @returns Total token count used for the embedding request.
* @internal
*/
protected abstract extractTokenCount(response: TResponse): number;
/**
* Returns the URL identifier for this API (used in error messages).
* @returns URL string identifier.
* @internal
*/
protected abstract getUrl(): string;
protected mergeModelParams(
settings: SAPAIEmbeddingSettings,
embeddingOptions: EmbeddingProviderOptions | undefined,
): Record<string, unknown> {
return deepMerge(
(settings.modelParams as Record<string, unknown> | undefined) ?? {},
embeddingOptions?.modelParams ?? {},
);
}
/**
* Pushes API-specific deprecation or migration warnings into the shared
* sink. Default no-op; subclasses override to surface settings-level
* warnings (e.g. orchestration's masking_providers deprecation).
* @param _settings - Embedding model settings.
* @param _warnings - Shared warnings sink for the current call.
* @internal
*/
protected resolveWarnings(_settings: SAPAIEmbeddingSettings, _warnings: SharedV3Warning[]): void {
return;
}
}