Repository navigation
Expand file tree
/
Copy pathbase-language-model-strategy.ts
More file actions
476 lines (438 loc) · 16.6 KB
/
Copy pathbase-language-model-strategy.ts
File metadata and controls
476 lines (438 loc) · 16.6 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/** Base class for language model strategies using the Template Method pattern. */
import type {
LanguageModelV3CallOptions,
LanguageModelV3GenerateResult,
LanguageModelV3ResponseMetadata,
LanguageModelV3StreamResult,
SharedV3Warning,
} from "@ai-sdk/provider";
import type { CustomRequestConfig } from "@sap-ai-sdk/core";
import type { ChatMessage } from "@sap-ai-sdk/orchestration";
import type { ParsePartProviderOptions } from "./sap-ai-provider-options.js";
import type { SAPAIModelSettings } from "./sap-ai-settings.js";
import type { LanguageModelAPIStrategy, LanguageModelStrategyConfig } from "./sap-ai-strategy.js";
import { throwIfAborted, waitWithAbort } from "./abort-utils.js";
import { convertToSAPMessages } from "./convert-to-sap-messages.js";
import { convertToAISDKError, normalizeHeaders } from "./sap-ai-error.js";
import { getProviderName } from "./sap-ai-provider-options.js";
import {
buildGenerateResult,
buildModelParams,
createAISDKRequestBodySummary,
extractCompletionMetadata,
extractResponseMetadata,
mapToolChoice,
mergeRequestConfig,
type ParamMapping,
type SAPToolChoice,
type SDKCitation,
type SDKResponse,
type SDKStreamChunk,
} from "./strategy-utils.js";
import { createStreamTransformer, StreamIdGenerator } from "./stream-transformer.js";
import { VERSION } from "./version.js";
/**
* Result of building common parts for a language model request.
* @template TMessages - The message array type (e.g., `ChatMessage[]`, `AzureOpenAiChatCompletionRequestMessage[]`)
* @template TToolChoice - The tool choice type (e.g., `SAPToolChoice`)
* @internal
*/
export interface CommonBuildResult<TMessages extends unknown[] = unknown[], TToolChoice = unknown> {
readonly messages: TMessages;
readonly modelParams: Record<string, unknown>;
readonly providerName: string;
readonly resolvedState?: unknown;
readonly sapOptions: Record<string, unknown> | undefined;
readonly toolChoice: TToolChoice;
readonly warnings: SharedV3Warning[];
}
/**
* Stream response shape returned by executeStreamCall.
* @internal
*/
export interface StreamCallResponse {
readonly cancel: () => void;
readonly extractProviderSpecificFields?: (chunk: SDKStreamChunk) => unknown;
readonly extractReasoningBlocks?: (chunk: SDKStreamChunk) => unknown;
readonly getCitations?: () => SDKCitation[] | undefined;
readonly getFinishReason: () => null | string | undefined;
readonly getIntermediateFailures?: () => undefined | unknown[];
/** SAP-pipeline request id resolved by `extractResponseMetadata`. */
readonly requestId?: string;
readonly responseHeaders?: Record<string, string>;
readonly responseMetadata?: LanguageModelV3ResponseMetadata;
readonly stream: AsyncIterable<SDKStreamChunk>;
}
/**
* Abstract base class for language model strategies using the Template Method pattern.
* @template TClient - The SDK client type (e.g., AzureOpenAiChatClient, OrchestrationClient).
* @template TRequest - The API request type (e.g., AzureOpenAiChatCompletionParameters).
* @template TSettings - The model settings type extending SAPAIModelSettings.
* @internal
*/
export abstract class BaseLanguageModelStrategy<
TClient,
TRequest,
TSettings extends SAPAIModelSettings = SAPAIModelSettings,
> implements LanguageModelAPIStrategy<TSettings> {
/**
* Common parameter mappings for language model APIs.
* @internal
*/
static readonly COMMON_PARAM_MAPPINGS: readonly ParamMapping[] = [
{ camelCaseKey: "maxTokens", optionKey: "maxOutputTokens", outputKey: "max_completion_tokens" },
{ camelCaseKey: "temperature", optionKey: "temperature", outputKey: "temperature" },
{ camelCaseKey: "topP", optionKey: "topP", outputKey: "top_p" },
{
camelCaseKey: "frequencyPenalty",
optionKey: "frequencyPenalty",
outputKey: "frequency_penalty",
},
{
camelCaseKey: "presencePenalty",
optionKey: "presencePenalty",
outputKey: "presence_penalty",
},
{ camelCaseKey: "seed", optionKey: "seed", outputKey: "seed" },
{ optionKey: "reasoning", outputKey: "reasoning_effort" },
{ camelCaseKey: "parallel_tool_calls", outputKey: "parallel_tool_calls" },
] as const;
async doGenerate(
config: LanguageModelStrategyConfig,
settings: TSettings,
options: LanguageModelV3CallOptions,
): Promise<LanguageModelV3GenerateResult> {
try {
throwIfAborted(options.abortSignal);
const commonParts = this.buildCommonParts(config, settings, options);
const { request, warnings } = this.buildRequest(config, settings, options, commonParts);
const client = this.createClient(config, settings, commonParts);
const response = await waitWithAbort(
this.executeApiCall(
client,
request,
mergeRequestConfig(config.requestConfig, options.abortSignal, options.headers),
),
options.abortSignal,
);
throwIfAborted(options.abortSignal);
return buildGenerateResult({
providerName: commonParts.providerName,
requestBody: request,
requestId: response.requestId,
response,
responseHeaders: normalizeHeaders(response.rawResponse.headers),
version: VERSION,
warnings: [...commonParts.warnings, ...warnings],
});
} catch (error) {
throw convertToAISDKError(error, {
modelId: config.modelId,
modelType: "languageModel",
operation: "doGenerate",
requestBody: createAISDKRequestBodySummary(options),
url: this.getUrl(),
});
}
}
async doStream(
config: LanguageModelStrategyConfig,
settings: TSettings,
options: LanguageModelV3CallOptions,
): Promise<LanguageModelV3StreamResult> {
try {
throwIfAborted(options.abortSignal);
const commonParts = this.buildCommonParts(config, settings, options);
const { request, warnings } = this.buildRequest(config, settings, options, commonParts);
const client = this.createClient(config, settings, commonParts);
const streamResponse = await this.executeStreamCall(
client,
request,
options.abortSignal ?? undefined,
settings,
mergeRequestConfig(config.requestConfig, undefined, options.headers),
commonParts,
);
if (options.abortSignal?.aborted) {
try {
streamResponse.cancel();
} finally {
throwIfAborted(options.abortSignal);
}
}
const idGenerator = new StreamIdGenerator();
const streamWarnings = this.collectStreamWarnings(settings, commonParts.sapOptions);
const transformedStream = createStreamTransformer({
cancel: streamResponse.cancel,
convertToAISDKError,
extractChunkMetadata: (chunk) => this.extractMetadata(chunk),
extractProviderSpecificFields: streamResponse.extractProviderSpecificFields,
extractReasoningBlocks: streamResponse.extractReasoningBlocks,
idGenerator,
includeRawChunks: options.includeRawChunks ?? false,
modelId: config.modelId,
options,
providerName: commonParts.providerName,
requestId: streamResponse.requestId,
responseMetadata: {
...streamResponse.responseMetadata,
id: streamResponse.responseMetadata?.id ?? idGenerator.generateResponseId(),
},
sdkStream: streamResponse.stream,
streamResponseGetCitations: streamResponse.getCitations,
streamResponseGetFinishReason: streamResponse.getFinishReason,
streamResponseGetIntermediateFailures: streamResponse.getIntermediateFailures,
url: this.getUrl(),
version: VERSION,
warnings: [...commonParts.warnings, ...warnings, ...streamWarnings],
});
return {
request: {
body: request,
},
response: {
headers: streamResponse.responseHeaders,
},
stream: transformedStream,
};
} catch (error) {
throw convertToAISDKError(error, {
modelId: config.modelId,
modelType: "languageModel",
operation: "doStream",
requestBody: createAISDKRequestBodySummary(options),
url: this.getUrl(),
});
}
}
/**
* Builds common parts shared between doGenerate and doStream.
* @param config - Strategy configuration.
* @param settings - Model settings.
* @param options - AI SDK call options.
* @returns Common build result with typed messages and tool choice.
* @internal
*/
protected buildCommonParts(
config: LanguageModelStrategyConfig,
settings: TSettings,
options: LanguageModelV3CallOptions,
): CommonBuildResult<ChatMessage[], SAPToolChoice | undefined> {
const providerName = getProviderName(config.provider);
const sapOptions = config.parsedProviderOptions;
const warnings: SharedV3Warning[] = [];
const resolvedState = this.resolveAdditionalState(
config,
settings,
sapOptions,
options,
warnings,
);
const messages = convertToSAPMessages(options.prompt, {
escapeTemplatePlaceholders: this.getEscapeTemplatePlaceholders(sapOptions, settings),
includeReasoning: this.getIncludeReasoning(sapOptions, settings),
nativeReasoningProviderName: this.getNativeReasoningProviderName(providerName),
parsePartProviderOptions: this.getPartProviderOptionsParser(),
warnings,
});
const { modelParams, warnings: paramWarnings } = buildModelParams({
options,
paramMappings: this.getParamMappings(),
providerModelParams: sapOptions?.modelParams,
settingsModelParams: settings.modelParams,
});
warnings.push(...paramWarnings);
const toolChoice = mapToolChoice(options.toolChoice);
return {
messages,
modelParams,
providerName,
resolvedState,
sapOptions,
toolChoice,
warnings,
};
}
/**
* Builds the API-specific request body.
* @param config - Strategy configuration.
* @param settings - Model settings.
* @param options - AI SDK call options.
* @param commonParts - Common build result from base class.
* @returns Request body and accumulated warnings.
* @internal
*/
protected abstract buildRequest(
config: LanguageModelStrategyConfig,
settings: TSettings,
options: LanguageModelV3CallOptions,
commonParts: CommonBuildResult<ChatMessage[], SAPToolChoice | undefined>,
): { readonly request: TRequest; readonly warnings: SharedV3Warning[] };
/**
* Collects stream-specific warnings.
* Override in subclasses to add API-specific streaming warnings.
* @param _settings - Model settings (unused in base implementation).
* @param _sapOptions - Provider options (unused in base implementation).
* @returns Array of warnings for streaming operations.
* @internal
*/
protected collectStreamWarnings(
_settings: TSettings,
_sapOptions?: Record<string, unknown>,
): SharedV3Warning[] {
return [];
}
/**
* Creates the appropriate SDK client for this API.
* @param config - Strategy configuration.
* @param settings - Model settings.
* @param commonParts - Common build result (messages, options, etc.).
* @returns SDK client instance.
* @internal
*/
protected abstract createClient(
config: LanguageModelStrategyConfig,
settings: TSettings,
commonParts: CommonBuildResult<ChatMessage[], SAPToolChoice | undefined>,
): TClient;
/**
* Executes the non-streaming API call.
* @param client - SDK client instance.
* @param request - Request body.
* @param requestConfig - Optional custom request configuration (e.g. custom headers).
* @returns SDK response.
* @internal
*/
protected abstract executeApiCall(
client: TClient,
request: TRequest,
requestConfig: CustomRequestConfig | undefined,
): Promise<SDKResponse>;
/**
* Executes the streaming API call.
* @param client - SDK client instance.
* @param request - Request body.
* @param abortSignal - Optional abort signal.
* @param settings - Model settings for API-specific stream options.
* @param requestConfig - Optional custom request configuration (e.g. custom headers).
* @param commonParts - Common build result (resolved state, provider options, etc.).
* @returns Stream response with accessors.
* @internal
*/
protected abstract executeStreamCall(
client: TClient,
request: TRequest,
abortSignal: AbortSignal | undefined,
settings: TSettings,
requestConfig: CustomRequestConfig | undefined,
commonParts: CommonBuildResult<ChatMessage[], SAPToolChoice | undefined>,
): Promise<StreamCallResponse>;
/**
* Resolves completion metadata, request ID, and normalised headers from an SDK response.
* @param response - Raw SDK response or stream response.
* @returns Combined metadata fragment.
* @internal
*/
protected extractMetadata(response: unknown): {
requestId?: string;
responseHeaders?: Record<string, string>;
responseMetadata: LanguageModelV3ResponseMetadata;
} {
const responseMetadata = extractCompletionMetadata(
response as { _data?: unknown; getRequestId?: () => string | undefined },
this.getCompletionDataPath(),
);
const { headers, requestId } = extractResponseMetadata(response, "rawResponse");
return { requestId, responseHeaders: headers, responseMetadata };
}
/**
* Returns the API-specific path to the completion object in an SDK payload.
* @returns Completion path (`["final_result"]` for orchestration, `[]` for Foundation Models).
* @internal
*/
protected abstract getCompletionDataPath(): readonly string[];
/**
* Returns whether to escape template placeholders for this API.
* @param _sapOptions - Parsed provider options (unused in base implementation).
* @param _settings - Model settings (unused in base implementation).
* @returns false by default; the Orchestration override defaults to true unless disabled.
* @internal
*/
protected getEscapeTemplatePlaceholders(
_sapOptions: Record<string, unknown> | undefined,
_settings: TSettings,
): boolean {
return false;
}
/**
* Returns whether assistant reasoning in the input history is forwarded as text.
* @param sapOptions - Parsed provider options.
* @param settings - Model settings.
* @returns Whether to forward input reasoning (checks sapOptions then settings, defaults to false).
* @internal
*/
protected getIncludeReasoning(
sapOptions: Record<string, unknown> | undefined,
settings: TSettings,
): boolean {
return (
(sapOptions?.includeReasoning as boolean | undefined) ??
("includeReasoning" in settings ? settings.includeReasoning : false) ??
false
);
}
/**
* Enables native reasoning history only for strategies supporting the Orchestration wire format.
* @param _providerName - Configured provider namespace.
* @returns The native reasoning namespace, or undefined for legacy text-only history.
* @internal
*/
protected getNativeReasoningProviderName(_providerName: string): string | undefined {
return undefined;
}
/**
* Returns the parameter mappings specific to this API strategy.
* @returns Array of parameter mappings.
* @internal
*/
protected abstract getParamMappings(): readonly ParamMapping[];
/**
* Returns a parser for per-message-part `providerOptions['sap-ai']`.
*
* Default returns `undefined`; strategies honouring part-level directives
* (e.g. Anthropic `cacheControl` on orchestration) override to return a parser.
* @returns Parser callback, or undefined to disable per-part plumbing.
* @internal
*/
protected getPartProviderOptionsParser(): ParsePartProviderOptions | undefined {
return undefined;
}
/**
* Returns the URL identifier for this API (used in error messages).
* @returns URL string identifier.
* @internal
*/
protected abstract getUrl(): string;
/**
* Resolves API-specific extra state shared between doGenerate and doStream
* (e.g. orchestration `configRef` / `promptTemplateRef` / `tools`). Override
* to add API-specific deprecation checks or pre-resolve auxiliary inputs.
* Pushed warnings flow into the shared sink.
* @param _config - Strategy configuration.
* @param _settings - Model settings.
* @param _sapOptions - Parsed provider options, or `undefined`.
* @param _options - AI SDK call options.
* @param _warnings - Shared warnings sink for the current call.
* @returns Strategy-specific resolved state, or `undefined` (default).
* @internal
*/
protected resolveAdditionalState(
_config: LanguageModelStrategyConfig,
_settings: TSettings,
_sapOptions: Record<string, unknown> | undefined,
_options: LanguageModelV3CallOptions,
_warnings: SharedV3Warning[],
): unknown {
return undefined;
}
}