@jerome-benoit/sap-ai-provider 4.0.0-rc.2 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29746,9 +29746,7 @@ import {
29746
29746
  import { zodToJsonSchema } from "zod-to-json-schema";
29747
29747
 
29748
29748
  // src/convert-to-sap-messages.ts
29749
- import {
29750
- UnsupportedFunctionalityError
29751
- } from "@ai-sdk/provider";
29749
+ import { UnsupportedFunctionalityError } from "@ai-sdk/provider";
29752
29750
  import { Buffer as Buffer2 } from "buffer";
29753
29751
  function convertToSAPMessages(prompt, options = {}) {
29754
29752
  const messages = [];
@@ -29901,9 +29899,7 @@ function convertToSAPMessages(prompt, options = {}) {
29901
29899
  }
29902
29900
  default: {
29903
29901
  const _exhaustiveCheck = message;
29904
- throw new Error(
29905
- `Unsupported role: ${_exhaustiveCheck.role}`
29906
- );
29902
+ throw new Error(`Unsupported role: ${_exhaustiveCheck.role}`);
29907
29903
  }
29908
29904
  }
29909
29905
  }
@@ -29972,18 +29968,29 @@ function convertToAISDKError(error, context) {
29972
29968
  if (error instanceof APICallError || error instanceof LoadAPIKeyError) {
29973
29969
  return error;
29974
29970
  }
29975
- if (isOrchestrationErrorResponse(error)) {
29976
- return convertSAPErrorToAPICallError(error, {
29971
+ const rootError = error instanceof Error && (0, import_util.isErrorWithCause)(error) ? error.rootCause : error;
29972
+ if (isOrchestrationErrorResponse(rootError)) {
29973
+ return convertSAPErrorToAPICallError(rootError, {
29977
29974
  ...context,
29978
29975
  responseHeaders: context?.responseHeaders ?? getAxiosResponseHeaders(error)
29979
29976
  });
29980
29977
  }
29978
+ if (rootError instanceof Error) {
29979
+ const parsedError = tryExtractSAPErrorFromMessage(rootError.message);
29980
+ if (parsedError && isOrchestrationErrorResponse(parsedError)) {
29981
+ return convertSAPErrorToAPICallError(parsedError, {
29982
+ ...context,
29983
+ responseHeaders: context?.responseHeaders ?? getAxiosResponseHeaders(error)
29984
+ });
29985
+ }
29986
+ }
29981
29987
  const responseHeaders = context?.responseHeaders ?? getAxiosResponseHeaders(error);
29982
- if (error instanceof Error) {
29983
- const errorMsg = error.message.toLowerCase();
29984
- if (errorMsg.includes("authentication") || errorMsg.includes("unauthorized") || errorMsg.includes("aicore_service_key") || errorMsg.includes("invalid credentials")) {
29988
+ if (rootError instanceof Error) {
29989
+ const errorMsg = rootError.message.toLowerCase();
29990
+ const originalMsg = rootError.message;
29991
+ if (errorMsg.includes("authentication") || errorMsg.includes("unauthorized") || errorMsg.includes("aicore_service_key") || errorMsg.includes("invalid credentials") || errorMsg.includes("service credentials") || errorMsg.includes("service binding")) {
29985
29992
  return new LoadAPIKeyError({
29986
- message: `SAP AI Core authentication failed: ${error.message}
29993
+ message: `SAP AI Core authentication failed: ${originalMsg}
29987
29994
 
29988
29995
  Make sure your AICORE_SERVICE_KEY environment variable is set correctly.
29989
29996
  See: https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-service-key`
@@ -29993,15 +30000,79 @@ See: https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-serv
29993
30000
  return new APICallError({
29994
30001
  cause: error,
29995
30002
  isRetryable: true,
29996
- message: `Network error connecting to SAP AI Core: ${error.message}`,
30003
+ message: `Network error connecting to SAP AI Core: ${originalMsg}`,
29997
30004
  requestBodyValues: context?.requestBody,
29998
30005
  responseHeaders,
29999
30006
  statusCode: 503,
30000
30007
  url: context?.url ?? ""
30001
30008
  });
30002
30009
  }
30010
+ if (errorMsg.includes("could not resolve destination")) {
30011
+ return new APICallError({
30012
+ cause: error,
30013
+ isRetryable: false,
30014
+ message: `SAP AI Core destination error: ${originalMsg}
30015
+
30016
+ Check your destination configuration or provide a valid destinationName.`,
30017
+ requestBodyValues: context?.requestBody,
30018
+ responseHeaders,
30019
+ statusCode: 500,
30020
+ url: context?.url ?? ""
30021
+ });
30022
+ }
30023
+ if (errorMsg.includes("failed to resolve deployment") || errorMsg.includes("no deployment matched")) {
30024
+ return new APICallError({
30025
+ cause: error,
30026
+ isRetryable: false,
30027
+ message: `SAP AI Core deployment error: ${originalMsg}
30028
+
30029
+ Make sure you have a running orchestration deployment in your AI Core instance.
30030
+ See: https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-deployment-for-orchestration`,
30031
+ requestBodyValues: context?.requestBody,
30032
+ responseHeaders,
30033
+ statusCode: 404,
30034
+ url: context?.url ?? ""
30035
+ });
30036
+ }
30037
+ if (errorMsg.includes("filtered by the output filter")) {
30038
+ return new APICallError({
30039
+ cause: error,
30040
+ isRetryable: false,
30041
+ message: `Content was filtered: ${originalMsg}
30042
+
30043
+ The model's response was blocked by content safety filters. Try a different prompt.`,
30044
+ requestBodyValues: context?.requestBody,
30045
+ responseHeaders,
30046
+ statusCode: 400,
30047
+ url: context?.url ?? ""
30048
+ });
30049
+ }
30050
+ const statusMatch = /status code (\d+)/i.exec(originalMsg);
30051
+ if (statusMatch) {
30052
+ const extractedStatus = parseInt(statusMatch[1], 10);
30053
+ return new APICallError({
30054
+ cause: error,
30055
+ isRetryable: isRetryable(extractedStatus),
30056
+ message: `SAP AI Core request failed: ${originalMsg}`,
30057
+ requestBodyValues: context?.requestBody,
30058
+ responseHeaders,
30059
+ statusCode: extractedStatus,
30060
+ url: context?.url ?? ""
30061
+ });
30062
+ }
30063
+ if (errorMsg.includes("iterate over") || errorMsg.includes("consumed stream") || errorMsg.includes("parse message into json") || errorMsg.includes("no body")) {
30064
+ return new APICallError({
30065
+ cause: error,
30066
+ isRetryable: true,
30067
+ message: `SAP AI Core streaming error: ${originalMsg}`,
30068
+ requestBodyValues: context?.requestBody,
30069
+ responseHeaders,
30070
+ statusCode: 500,
30071
+ url: context?.url ?? ""
30072
+ });
30073
+ }
30003
30074
  }
30004
- const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error occurred";
30075
+ const message = rootError instanceof Error ? rootError.message : typeof rootError === "string" ? rootError : "Unknown error occurred";
30005
30076
  const fullMessage = context?.operation ? `SAP AI Core ${context.operation} failed: ${message}` : `SAP AI Core error: ${message}`;
30006
30077
  return new APICallError({
30007
30078
  cause: error,
@@ -30062,13 +30133,35 @@ function normalizeHeaders(headers) {
30062
30133
  if (entries.length === 0) return void 0;
30063
30134
  return Object.fromEntries(entries);
30064
30135
  }
30136
+ function tryExtractSAPErrorFromMessage(message) {
30137
+ const jsonMatch = /\{[\s\S]*\}/.exec(message);
30138
+ if (!jsonMatch) return null;
30139
+ try {
30140
+ const parsed = JSON.parse(jsonMatch[0]);
30141
+ if (parsed && typeof parsed === "object" && "error" in parsed) {
30142
+ return parsed;
30143
+ }
30144
+ if (parsed && typeof parsed === "object" && "message" in parsed) {
30145
+ return { error: parsed };
30146
+ }
30147
+ return null;
30148
+ } catch {
30149
+ return null;
30150
+ }
30151
+ }
30065
30152
 
30066
30153
  // src/sap-ai-language-model.ts
30067
30154
  var StreamIdGenerator = class {
30155
+ /**
30156
+ * Generates a unique ID for a response stream.
30157
+ * @returns RFC 4122-compliant UUID
30158
+ */
30159
+ generateResponseId() {
30160
+ return crypto.randomUUID();
30161
+ }
30068
30162
  /**
30069
30163
  * Generates a unique ID for a text block.
30070
- *
30071
- * @returns RFC 4122-compliant UUID string
30164
+ * @returns RFC 4122-compliant UUID
30072
30165
  */
30073
30166
  generateTextBlockId() {
30074
30167
  return crypto.randomUUID();
@@ -30085,7 +30178,11 @@ var SAPAILanguageModel = class {
30085
30178
  * SAP AI Core will fail the request at runtime.
30086
30179
  */
30087
30180
  supportsImageUrls = true;
30088
- /** Multiple completions via the `n` parameter (provider-specific support). */
30181
+ /**
30182
+ * Multiple completions via the `n` parameter.
30183
+ * Note: Amazon and Anthropic models do not support this feature.
30184
+ * The provider silently omits the parameter for unsupported models.
30185
+ */
30089
30186
  supportsMultipleCompletions = true;
30090
30187
  /** Parallel tool calls. */
30091
30188
  supportsParallelToolCalls = true;
@@ -30096,52 +30193,14 @@ var SAPAILanguageModel = class {
30096
30193
  /** Tool/function calling. */
30097
30194
  supportsToolCalls = true;
30098
30195
  /**
30099
- * Generates text completion using SAP AI Core's Orchestration API.
30100
- *
30101
- * This method implements the `LanguageModelV3.doGenerate` interface,
30102
- * providing synchronous (non-streaming) text generation with support for:
30103
- * - Multi-turn conversations with system/user/assistant messages
30104
- * - Tool calling (function calling) with structured outputs
30105
- * - Multi-modal inputs (text + images)
30106
- * - Data masking via SAP DPI
30107
- * - Content filtering via Azure Content Safety or Llama Guard
30108
- *
30109
- * **Return Structure:**
30110
- * - Finish reason: `{ unified: string, raw?: string }`
30111
- * - Usage: Nested structure with token breakdown `{ inputTokens: { total, ... }, outputTokens: { total, ... } }`
30112
- * - Warnings: Array of warnings with `type` and optional `feature` field
30113
- *
30114
- * @param options - Generation options including prompt, tools, temperature, etc.
30115
- * @returns Promise resolving to generation result with content, usage, and metadata
30116
- *
30117
- * @throws {InvalidPromptError} If prompt format is invalid
30118
- * @throws {InvalidArgumentError} If arguments are malformed
30119
- * @throws {APICallError} If the SAP AI Core API call fails
30120
- *
30121
- * @example
30122
- * ```typescript
30123
- * const result = await model.doGenerate({
30124
- * prompt: [
30125
- * { role: 'user', content: [{ type: 'text', text: 'Hello!' }] }
30126
- * ],
30127
- * temperature: 0.7,
30128
- * maxTokens: 100
30129
- * });
30130
- *
30131
- * console.log(result.content); // Array of V3 content parts
30132
- * console.log(result.finishReason.unified); // "stop", "length", "tool-calls", etc.
30133
- * console.log(result.usage.inputTokens.total); // Total input tokens
30134
- * ```
30135
- *
30136
- * @since 1.0.0
30137
- * @since 4.0.0 Updated to LanguageModelV3 interface
30196
+ * Returns the provider identifier.
30197
+ * @returns The provider name
30138
30198
  */
30139
30199
  get provider() {
30140
30200
  return this.config.provider;
30141
30201
  }
30142
30202
  /**
30143
30203
  * Returns supported URL patterns for different content types.
30144
- *
30145
30204
  * @returns Record of content types to regex patterns
30146
30205
  */
30147
30206
  get supportedUrls() {
@@ -30153,13 +30212,10 @@ var SAPAILanguageModel = class {
30153
30212
  settings;
30154
30213
  /**
30155
30214
  * Creates a new SAP AI Chat Language Model instance.
30156
- *
30215
+ * @internal
30157
30216
  * @param modelId - The model identifier
30158
30217
  * @param settings - Model-specific configuration settings
30159
30218
  * @param config - Internal configuration (deployment config, destination, etc.)
30160
- *
30161
- * @internal This constructor is not meant to be called directly.
30162
- * Use the provider function instead.
30163
30219
  */
30164
30220
  constructor(modelId, settings, config) {
30165
30221
  this.settings = settings;
@@ -30181,13 +30237,12 @@ var SAPAILanguageModel = class {
30181
30237
  *
30182
30238
  * **Note on Abort Signal:**
30183
30239
  * The abort signal implementation uses Promise.race to reject the promise when
30184
- * the signal is aborted. However, this does not cancel the underlying HTTP request
30185
- * to SAP AI Core - the request continues executing on the server. This is a
30186
- * limitation of the SAP AI SDK's chatCompletion API.
30187
- *
30240
+ * aborted. However, this does not cancel the underlying HTTP request to SAP AI Core -
30241
+ * the request continues executing on the server. This is a current limitation of the
30242
+ * SAP AI SDK's API. See https://github.com/SAP/ai-sdk-js/issues/1429
30188
30243
  * @param options - Generation options including prompt, tools, and settings
30189
30244
  * @returns Promise resolving to the generation result with content, usage, and metadata
30190
- *
30245
+ * @since 1.0.0
30191
30246
  * @example
30192
30247
  * ```typescript
30193
30248
  * const result = await model.doGenerate({
@@ -30346,33 +30401,29 @@ var SAPAILanguageModel = class {
30346
30401
  /**
30347
30402
  * Generates a streaming completion.
30348
30403
  *
30349
- * This method implements the `LanguageModelV3.doStream` interface,
30350
- * sending a streaming request to SAP AI Core and returning a stream of response parts.
30404
+ * Implements `LanguageModelV3.doStream`, sending a streaming request to SAP AI Core
30405
+ * and returning a stream of response parts.
30351
30406
  *
30352
30407
  * **Stream Events:**
30353
- * - `stream-start` - Stream initialization with warnings
30354
- * - `response-metadata` - Response metadata (model, timestamp)
30408
+ * - `stream-start` - Initialization with warnings
30409
+ * - `response-metadata` - Model, timestamp, response ID
30355
30410
  * - `text-start` - Text block begins (with unique ID)
30356
- * - `text-delta` - Incremental text chunks (with block ID)
30357
- * - `text-end` - Text block completes (with accumulated text)
30358
- * - `tool-input-start` - Tool input begins
30359
- * - `tool-input-delta` - Tool input chunk
30360
- * - `tool-input-end` - Tool input completes
30411
+ * - `text-delta` - Incremental text chunks
30412
+ * - `text-end` - Text block completes
30413
+ * - `tool-input-start/delta/end` - Tool input lifecycle
30361
30414
  * - `tool-call` - Complete tool call
30362
30415
  * - `finish` - Stream completes with usage and finish reason
30363
30416
  * - `error` - Error occurred
30364
30417
  *
30365
- * **Stream Structure:**
30366
- * - Text blocks have explicit lifecycle with unique IDs
30367
- * - Finish reason format: `{ unified: string, raw?: string }`
30368
- * - Usage format: `{ inputTokens: { total, ... }, outputTokens: { total, ... } }`
30369
- * - Warnings only in `stream-start` event
30418
+ * **Response ID:**
30419
+ * Client-generated UUID in `response-metadata.id` and `providerMetadata['sap-ai'].responseId`.
30420
+ * TODO: Use backend's `x-request-id` when `OrchestrationStreamResponse` exposes `rawResponse`.
30370
30421
  *
30422
+ * **Abort Signal:**
30423
+ * Same limitation as `doGenerate` - see its documentation for details.
30371
30424
  * @see {@link https://sdk.vercel.ai/docs/ai-sdk-core/streaming Vercel AI SDK Streaming}
30372
- *
30373
30425
  * @param options - Streaming options including prompt, tools, and settings
30374
30426
  * @returns Promise resolving to stream and request metadata
30375
- *
30376
30427
  * @example
30377
30428
  * ```typescript
30378
30429
  * const { stream } = await model.doStream({
@@ -30385,13 +30436,9 @@ var SAPAILanguageModel = class {
30385
30436
  * if (part.type === 'text-delta') {
30386
30437
  * process.stdout.write(part.delta);
30387
30438
  * }
30388
- * if (part.type === 'text-end') {
30389
- * console.log('Block complete:', part.id, part.text);
30390
- * }
30391
30439
  * }
30392
30440
  * ```
30393
- *
30394
- * @since 4.0.0
30441
+ * @since 1.0.0
30395
30442
  */
30396
30443
  async doStream(options) {
30397
30444
  try {
@@ -30414,12 +30461,11 @@ var SAPAILanguageModel = class {
30414
30461
  return filtering && Object.keys(filtering).length > 0 ? { filtering } : {};
30415
30462
  })()
30416
30463
  };
30417
- const streamResponse = await client.stream(
30418
- requestBody,
30419
- options.abortSignal,
30420
- { promptTemplating: { include_usage: true } }
30421
- );
30464
+ const streamResponse = await client.stream(requestBody, options.abortSignal, {
30465
+ promptTemplating: { include_usage: true }
30466
+ });
30422
30467
  const idGenerator = new StreamIdGenerator();
30468
+ const responseId = idGenerator.generateResponseId();
30423
30469
  let textBlockId = null;
30424
30470
  const streamState = {
30425
30471
  activeText: false,
@@ -30463,6 +30509,7 @@ var SAPAILanguageModel = class {
30463
30509
  if (streamState.isFirstChunk) {
30464
30510
  streamState.isFirstChunk = false;
30465
30511
  controller.enqueue({
30512
+ id: responseId,
30466
30513
  modelId,
30467
30514
  timestamp: /* @__PURE__ */ new Date(),
30468
30515
  type: "response-metadata"
@@ -30625,6 +30672,12 @@ var SAPAILanguageModel = class {
30625
30672
  }
30626
30673
  controller.enqueue({
30627
30674
  finishReason: streamState.finishReason,
30675
+ providerMetadata: {
30676
+ "sap-ai": {
30677
+ finishReason: streamState.finishReason.raw,
30678
+ responseId
30679
+ }
30680
+ },
30628
30681
  type: "finish",
30629
30682
  usage: streamState.usage
30630
30683
  });
@@ -30659,7 +30712,6 @@ var SAPAILanguageModel = class {
30659
30712
  }
30660
30713
  /**
30661
30714
  * Checks if a URL is supported for file/image uploads.
30662
- *
30663
30715
  * @param url - The URL to check
30664
30716
  * @returns True if the URL protocol is HTTPS or data with valid image format
30665
30717
  */
@@ -30672,7 +30724,6 @@ var SAPAILanguageModel = class {
30672
30724
  }
30673
30725
  /**
30674
30726
  * Builds orchestration module config for SAP AI SDK.
30675
- *
30676
30727
  * @param options - Call options from the AI SDK
30677
30728
  * @returns Object containing orchestration config, messages, and warnings
30678
30729
  * @internal
@@ -30705,12 +30756,9 @@ var SAPAILanguageModel = class {
30705
30756
  let parameters;
30706
30757
  if (toolWithParams.parameters && isZodSchema(toolWithParams.parameters)) {
30707
30758
  try {
30708
- const jsonSchema = zodToJsonSchema(
30709
- toolWithParams.parameters,
30710
- {
30711
- $refStrategy: "none"
30712
- }
30713
- );
30759
+ const jsonSchema = zodToJsonSchema(toolWithParams.parameters, {
30760
+ $refStrategy: "none"
30761
+ });
30714
30762
  const schemaRecord = jsonSchema;
30715
30763
  delete schemaRecord.$schema;
30716
30764
  parameters = buildSAPToolParameters(schemaRecord);
@@ -30850,17 +30898,12 @@ var SAPAILanguageModel = class {
30850
30898
  }
30851
30899
  /**
30852
30900
  * Creates an OrchestrationClient instance.
30853
- *
30854
30901
  * @param config - Orchestration module configuration
30855
30902
  * @returns OrchestrationClient instance
30856
30903
  * @internal
30857
30904
  */
30858
30905
  createClient(config) {
30859
- return new OrchestrationClient(
30860
- config,
30861
- this.config.deploymentConfig,
30862
- this.config.destination
30863
- );
30906
+ return new OrchestrationClient(config, this.config.deploymentConfig, this.config.destination);
30864
30907
  }
30865
30908
  };
30866
30909
  function buildSAPToolParameters(schema) {
@@ -30889,9 +30932,7 @@ function buildSAPToolParameters(schema) {
30889
30932
  function createAISDKRequestBodySummary(options) {
30890
30933
  return {
30891
30934
  hasImageParts: options.prompt.some(
30892
- (message) => message.role === "user" && message.content.some(
30893
- (part) => part.type === "file" && part.mediaType.startsWith("image/")
30894
- )
30935
+ (message) => message.role === "user" && message.content.some((part) => part.type === "file" && part.mediaType.startsWith("image/"))
30895
30936
  ),
30896
30937
  maxOutputTokens: options.maxOutputTokens,
30897
30938
  promptMessages: options.prompt.length,
@@ -31010,9 +31051,7 @@ function createSAPAIProvider(options = {}) {
31010
31051
  };
31011
31052
  const provider = function(modelId, settings) {
31012
31053
  if (new.target) {
31013
- throw new Error(
31014
- "The SAP AI provider function cannot be called with the new keyword."
31015
- );
31054
+ throw new Error("The SAP AI provider function cannot be called with the new keyword.");
31016
31055
  }
31017
31056
  return createModel(modelId, settings);
31018
31057
  };