This document provides a detailed overview of the SAP AI Provider's architecture, internal components, and integration patterns.
For general usage, see README. For API documentation, see API Reference.
3-layer architecture bridging your application to SAP AI services:
- Application → Provider → SAP AI Core → AI Models
- Implements Vercel AI SDK V3 strategies with V2 compatibility and native V4 Responses
- Uses SAP AI SDK clients for Orchestration and Foundation Models Chat Completions;
Responses delegates its protocol to
@ai-sdk/openaithrough SAP's HTTP transport - Converts messages and results through the selected API strategy
- Supports streaming, tool calling, multi-modal, data masking, and embeddings
Key Components: Provider → SAP SDK Client Configuration → Message Transformer → Error Handler → SAP AI Core API
- TL;DR (Executive Summary)
- Overview
- Component Architecture
- Request/Response Flow
- SAP SDK Authentication
- Error Handling
- Type System
- Integration Patterns
- Performance Considerations
- Versioned Package Architecture (V4 + V3 + V2)
- See Also
The SAP AI Provider is designed as a bridge between the Vercel AI SDK and
SAP AI Core services. Its shared core implements ProviderV3; thin V2 and V4
facades expose the contracts required by AI SDK 5, 6, and 7 while preserving
the same SAP authentication, validation, and request strategies.
The diagram below illustrates the SAP Chat Completions generation path, showing how it integrates your application with SAP AI Core through the Vercel AI SDK. For the Responses delegate and transport, see Strategy Pattern (API Selection). The provider layer configures SAP AI SDK clients, transforms messages between AI SDK and SAP formats, and converts errors. The SAP AI SDK and SAP Cloud SDK handle credential discovery, token acquisition, token caching, and token refresh. SAP AI Core routes requests to various AI models (OpenAI, Anthropic Claude, Google Gemini, Amazon Nova, and open-source models).
graph TB
subgraph "Application Layer"
App[Your Application]
SDK[Vercel AI SDK]
end
subgraph "Provider Layer"
Provider[SAP AI Provider]
SAPSDK[SAP AI SDK Client]
Transform[Message Transformer]
Error[Error Handler]
end
subgraph "SAP BTP"
OAuth[OAuth2 Server]
SAPAI[SAP AI Core APIs]
end
subgraph "AI Models"
GPT[OpenAI gpt-4.1]
Claude[Anthropic Claude]
Gemini[Google Gemini]
Nova[Amazon Nova]
OSS[Open Source Models]
end
App -->|generateText/streamText| SDK
SDK -->|doGenerate/doStream| Provider
Provider -->|Configure Client| SAPSDK
SAPSDK -->|Credential and Token Handling| OAuth
OAuth -->|Access Token| SAPSDK
Provider -->|Convert Messages| Transform
Transform -->|SAP Format| Provider
SAPSDK -->|API Request| SAPAI
SAPAI -->|Route to Model| GPT
SAPAI -->|Route to Model| Claude
SAPAI -->|Route to Model| Gemini
SAPAI -->|Route to Model| Nova
SAPAI -->|Route to Model| OSS
GPT -->|Response| SAPAI
Claude -->|Response| SAPAI
Gemini -->|Response| SAPAI
Nova -->|Response| SAPAI
OSS -->|Response| SAPAI
SAPAI -->|API Response| SAPSDK
SAPSDK -->|SDK Response| Provider
Provider -->|Parse/Validate| Error
Error -->|Transform| Provider
Provider -->|AI SDK Format| SDK
SDK -->|Result| App
style Provider fill:#e1f5ff
style SDK fill:#fff4e1
style SAPAI fill:#ffe1f5
style App fill:#e1ffe1
This sequence diagram shows the Orchestration generation lifecycle from your application through the AI SDK and provider to SAP AI Core. The flow is divided into four phases: Message Transformation (converting AI SDK format to SAP format), SAP SDK client setup, API Request & Response (including SDK authentication and communication with SAP AI Core and the AI model), and Response Processing (converting back to AI SDK format).
sequenceDiagram
participant App as Application
participant SDK as Vercel AI SDK
participant Prov as SAP AI Provider
participant SAPSDK as SAP AI SDK
participant Trans as Transformer
participant SAP as SAP AI Core
participant Model as AI Model
App->>SDK: generateText(config)
SDK->>Prov: doGenerate(options)
rect rgb(255, 248, 240)
Note over Prov,Trans: Message Transformation
Prov->>Trans: convertToSAPMessages(prompt)
Trans-->>Prov: SAP format messages
Prov->>Prov: Build request and model configuration
end
rect rgb(240, 248, 255)
Note over Prov,SAPSDK: SAP SDK Client Setup
Prov->>SAPSDK: Create client with module config and deployment/resource group
SAPSDK-->>Prov: Configured client
end
rect rgb(248, 255, 240)
Note over Prov,Model: API Request & Response
Prov->>SAPSDK: chatCompletion(request)
SAPSDK->>SAPSDK: Resolve deployment, credentials, and token
SAPSDK->>SAP: POST /v2/completion
Note right of SAP: Request Body:<br/>- config.modules.prompt_templating<br/>- config.modules.masking (optional)<br/>- model params
SAP->>Model: Forward request
Model-->>SAP: Generated response
SAP-->>SAPSDK: Orchestration response
SAPSDK-->>Prov: SDK response object
Note left of SAP: Response:<br/>- intermediate_results<br/>- final_result<br/>- usage stats
end
rect rgb(255, 240, 248)
Note over Prov,SDK: Response Processing
Prov->>Prov: Parse & validate
Prov->>Prov: Extract content & tool calls
Prov-->>SDK: LanguageModelV3GenerateResult
end
SDK-->>App: GenerateTextResult
- Compatibility: Full compatibility with Vercel AI SDK interfaces
- Type Safety: Comprehensive TypeScript types for all operations
- Error Resilience: Retryable error classification for high-level AI SDK retries
- Performance: Efficient request handling and response streaming
- Security: Secure authentication and credential management
This diagram details the responsibilities of each major component in the provider architecture, including the SAPAIProvider (factory and shared configuration), SAPAILanguageModel (request/response handling, tool calls), SAP SDK Client Configuration (deployment, resource group, and destination setup), Message Transformer (format conversion), API Client (HTTP communication), and Error Handling system.
graph TB
subgraph "Component Responsibilities"
Provider[SAPAIProvider<br/>━━━━━━━━━━━━━<br/>• Provider Factory<br/>• SAP SDK Client Config<br/>• Configuration<br/>• API Selection]
Model[SAPAILanguageModel<br/>━━━━━━━━━━━━━━━━━<br/>• doGenerate/doStream<br/>• API Resolution<br/>• Strategy Delegation<br/>• Late Binding]
Embedding[SAPAIEmbeddingModel<br/>━━━━━━━━━━━━━━━━━<br/>• doEmbed<br/>• API Resolution<br/>• Strategy Delegation]
Validation[API Validation<br/>━━━━━━━━━━━━━━<br/>• API Resolution<br/>• Feature Validation<br/>• API Switch Detection<br/>• Error Generation]
Strategy[Strategy Factory<br/>━━━━━━━━━━━━━━<br/>• Lazy Loading<br/>• Promise Caching<br/>• SDK Import<br/>• Race Prevention]
end
subgraph "API Strategies"
OrchLM[Orchestration<br/>Language Model<br/>━━━━━━━━━━━━━━<br/>• Masking<br/>• Filtering<br/>• Grounding<br/>• Templating]
FMLM[Foundation Models<br/>Language Model<br/>━━━━━━━━━━━━━━<br/>• Logprobs<br/>• Seed<br/>• Direct Access]
OrchEM[Orchestration<br/>Embedding Model]
FMEM[Foundation Models<br/>Embedding Model]
end
subgraph "SAP AI Core"
OrchAPI[Orchestration API<br/>Completion and embedding endpoints]
FMAPI[Foundation Models API<br/>Chat completion and embedding endpoints]
end
Provider -->|Creates| Model
Provider -->|Creates| Embedding
Model -->|Resolves| Validation
Embedding -->|Resolves| Validation
Validation -->|Gets Strategy| Strategy
Strategy -->|Lazy Load| OrchLM
Strategy -->|Lazy Load| FMLM
Strategy -->|Lazy Load| OrchEM
Strategy -->|Lazy Load| FMEM
OrchLM -->|Calls| OrchAPI
FMLM -->|Calls| FMAPI
OrchEM -->|Calls| OrchAPI
FMEM -->|Calls| FMAPI
style Provider fill:#e1f5ff
style Model fill:#ffe1f5
style Embedding fill:#ffe1f5
style Validation fill:#fff4e1
style Strategy fill:#f0ffe1
style OrchLM fill:#e1ffe1
style FMLM fill:#f5e1ff
style OrchAPI fill:#e1f5ff
style FMAPI fill:#f5e1ff
src/
│ # V3 Implementation (AI SDK 6; LanguageModelV3/EmbeddingModelV3)
├── index.ts # V3 public API exports (AI SDK 6)
├── sap-ai-provider.ts # V3 provider factory
├── sap-ai-language-model.ts # V3 language model (API-agnostic)
├── sap-ai-embedding-model.ts # V3 embedding model (API-agnostic)
│
│ # V4 Facade Layer (AI SDK 7; LanguageModelV4/EmbeddingModelV4)
├── index-v4.ts # V4 public API exports (AI SDK 7 facade)
├── sap-ai-provider-v4.ts # V4 facade provider factory
├── sap-ai-language-model-v4.ts # Native Responses and legacy API dispatch
├── sap-ai-embedding-model-v4.ts # V4 embedding model facade
├── sap-ai-adapters-v4-to-v3.ts # Legacy API prompt normalization
├── sap-ai-adapters-v3-to-v4.ts # Legacy API result conversion
│
│ # V2 Facade Layer (AI SDK 5; AI SDK 6 compatibility)
├── index-v2.ts # V2 public API exports (AI SDK 5 facade)
├── sap-ai-provider-v2.ts # V2 facade provider factory
├── sap-ai-language-model-v2.ts # V2 language model (wraps V3)
├── sap-ai-embedding-model-v2.ts # V2 embedding model (wraps V3)
├── sap-ai-adapters-v3-to-v2.ts # V3→V2 format conversion
│
│ # Shared Infrastructure
├── sap-ai-provider-options.ts # Provider options & Zod schemas
├── sap-ai-settings.ts # Settings and type definitions
├── sap-ai-error.ts # Error handling system
├── sap-ai-validation.ts # API resolution & validation
├── sap-ai-strategy.ts # Strategy factory (lazy loading)
├── language-model-invocation.ts # Shared per-call API preparation
├── strategy-utils.ts # Shared strategy utilities
├── stream-transformer.ts # Shared stream lifecycle, tool input, and metadata conversion
├── base-language-model-strategy.ts # Base class for language model strategies (Template Method)
├── base-embedding-model-strategy.ts # Base class for embedding model strategies (Template Method)
├── orchestration-language-model-strategy.ts # Orchestration API strategy
├── orchestration-embedding-model-strategy.ts # Orchestration embedding strategy
├── foundation-models-language-model-strategy.ts # Foundation Models API strategy
├── responses-language-model-strategy.ts # Native V4 Responses and V3 compatibility
├── responses-http-transport.ts # SAP transport for the Responses delegate
├── responses-prompt.ts # Native tagged-media and history preparation
├── foundation-models-embedding-model-strategy.ts # Foundation Models embedding strategy
├── convert-to-sap-messages.ts # Message format conversion
├── deep-merge.ts # Deep merge utility
└── version.ts # Package version constant
- Purpose: Factory for creating language and embedding model instances
- Responsibilities:
- SAP AI SDK client configuration
- Configuration validation
- Model instance creation (language and embedding)
- Deployment selection and destination configuration passed to SAP SDK clients
- Purpose: Implementation of Vercel AI SDK's
LanguageModelV3 - Responsibilities:
- Request/response transformation
- Streaming support
- Tool calling implementation
- Multi-modal input handling
- Purpose: Implementation of Vercel AI SDK's
EmbeddingModelV3 - Responsibilities:
- Embedding generation via
doEmbed() - Batch size validation (
maxEmbeddingsPerCall) - AbortSignal handling for request cancellation
- Uses Orchestration or Foundation Models embedding clients via strategies
- Embedding generation via
- Purpose: Configure SAP AI SDK clients for SAP AI Core calls
- Responsibilities:
- Pass deployment ID or resource group to SAP AI SDK clients
- Pass custom SAP Cloud SDK destination options when configured
- Set SAP Cloud SDK log level defaults
- Leave credential discovery, token acquisition, token caching, and token refresh to the SAP AI SDK and SAP Cloud SDK
- Purpose: Format translation between AI SDK and SAP AI Core
- Responsibilities:
- Prompt format conversion
- Multi-modal content handling
- Tool call format transformation
This detailed sequence diagram shows the complete flow for a standard text generation request, including all steps from application call through authentication, message transformation, SAP AI Core API communication, and response processing back to the application.
sequenceDiagram
participant App as Application
participant SDK as Vercel AI SDK
participant Provider as SAP AI Provider
participant SAPSDK as SAP AI SDK
participant Transform as Message Transformer
participant SAP as SAP AI Core
participant Model as AI Model (gpt-4.1, Claude, etc.)
rect rgb(230, 240, 255)
Note over App,SDK: 1. Application Layer
App->>SDK: generateText({<br/> model: provider('gpt-4.1'),<br/> prompt: 'Hello'<br/>})
SDK->>SDK: Validate options
end
rect rgb(255, 240, 230)
Note over SDK,Provider: 2. Provider Invocation
SDK->>Provider: doGenerate({<br/> prompt: [...],<br/> tools: [...],<br/> abortSignal: ...<br/>})
end
rect rgb(255, 245, 230)
Note over Provider,Transform: 3. Message Transformation
Provider->>Transform: convertToSAPMessages(prompt)
Transform->>Transform: Convert SDK format to SAP format<br/>• System messages<br/>• User messages (text + images)<br/>• Assistant messages<br/>• Tool calls/results
Transform-->>Provider: SAP format messages
end
rect rgb(240, 240, 255)
Note over Provider,SAPSDK: 4. Request and Client Configuration
Provider->>Provider: Build messages request and orchestration module configuration
Provider->>SAPSDK: Create client with module config,<br/>deployment config, and destination options
end
rect rgb(255, 240, 255)
Note over Provider,Model: 5. API Call & Processing
Provider->>SAPSDK: chatCompletion(request, requestConfig)
SAPSDK->>SAPSDK: Build wire request and resolve deployment,<br/>credentials, and cached or refreshed token
SAPSDK->>SAP: POST /v2/inference/deployments/{id}/v2/completion<br/>Headers: {<br/> Authorization: Bearer {token},<br/> AI-Resource-Group: {group}<br/>}
SAP->>SAP: Validate request<br/>Apply masking (if configured)
SAP->>Model: Route to model
Model->>Model: Generate response
Model-->>SAP: Model output
SAP->>SAP: Apply output unmasking<br/>Build orchestration response
SAP-->>SAPSDK: {<br/> request_id: "...",<br/> intermediate_results: {...},<br/> final_result: {...}<br/>}
SAPSDK-->>Provider: SDK response object
end
rect rgb(240, 255, 255)
Note over Provider,SDK: 6. Response Processing
Provider->>Provider: Parse response<br/>• Extract content<br/>• Extract tool calls<br/>• Calculate usage
Provider->>SAPSDK: Read final_result via response getters
SAPSDK-->>Provider: Content, tool calls, finish reason, and usage
Provider-->>SDK: {<br/> content: [...],<br/> usage: {...},<br/> finishReason: {unified: "stop", raw: "stop"},<br/> warnings: []<br/>}
end
rect rgb(230, 255, 240)
Note over SDK,App: 7. Result Delivery
SDK->>SDK: Transform to SDK format
SDK-->>App: {<br/> text: "...",<br/> usage: {...},<br/> finishReason: "stop"<br/>}
end
This diagram illustrates the streaming text generation flow using Server-Sent
Events (SSE). Unlike standard generation, streaming returns partial responses
incrementally as the AI model generates content, enabling real-time display of
results to users. The Orchestration and Foundation Models Chat Completions
strategies delegate event conversion to src/stream-transformer.ts: the SAP SDK
parses SSE, and the shared transformer maintains text/tool-input lifecycles,
usage, citations, and response metadata. Responses uses the OpenAI delegate's
SSE conversion instead; see
Strategy Pattern (API Selection).
sequenceDiagram
participant App as Application
participant SDK as Vercel AI SDK
participant Provider as SAP AI Provider
participant SAP as SAP AI Core
participant Model as AI Model
rect rgb(230, 240, 255)
Note over App,SDK: Stream Initiation
App->>SDK: streamText({<br/> model: provider('gpt-4.1'),<br/> prompt: 'Write a story'<br/>})
SDK->>Provider: doStream(options)
end
rect rgb(240, 255, 240)
Note over Provider,SAP: Request Setup
Provider->>Provider: Build streaming request<br/>{<br/> config: {<br/> stream: {enabled: true}<br/> }<br/>}
Provider->>SAP: POST /v2/completion<br/>Accept: text/event-stream
SAP->>Model: Start generation
Provider-->>SDK: {type: "stream-start", warnings: [...]}
end
rect rgb(255, 245, 230)
Note over Provider,App: Server-Sent Events Stream
loop For each token/chunk
Model->>SAP: Generate token
SAP-->>Provider: data: {<br/> final_result: {<br/> choices: [{<br/> delta: {content: "token"}<br/> }]<br/> }<br/>}
Provider->>Provider: Receive SDK-parsed SSE chunk
Provider->>Provider: Shared stream transformer emits V3 events
opt First Chunk or Updated Completion Metadata
Provider-->>SDK: {type: "response-metadata"}
end
opt First Nonempty Text Delta
Provider-->>SDK: {type: "text-start", id: "text-uuid"}
end
Provider-->>SDK: {<br/> type: "text-delta",<br/> id: "text-uuid",<br/> delta: "token"<br/>}
SDK-->>App: Stream chunk
App->>App: Display token
end
end
rect rgb(240, 255, 255)
Note over Model,App: Stream Completion
Model->>SAP: Generation complete
SAP-->>Provider: data: {<br/> final_result: {<br/> choices: [{<br/> finish_reason: "stop"<br/> }],<br/> usage: {...}<br/> }<br/>}
Provider-->>SDK: {type: "text-end", id: "text-uuid"}
Provider-->>SDK: {<br/> type: "finish",<br/> finishReason: {unified: "stop", raw: "stop"},<br/> usage: {...}<br/>}
SDK-->>App: Stream end
end
SAP AI Core Orchestration v2 introduces a more structured API with improved capabilities:
Default Path:
${AI_API_URL}/v2/inference/deployments/{deploymentId}/v2/completion
AI_API_URL is the service key's serviceurls.AI_API_URL value.
Deployment-relative v2 endpoint:
POST /v2/completionConfiguration:
// Default configuration
const automaticProvider = createSAPAIProvider({
resourceGroup: "default",
});
// With a specific deployment (resourceGroup is ignored when deploymentId is set)
const deployedProvider = createSAPAIProvider({
deploymentId: "d65d81e7c077e583",
});The v2 API uses a modular configuration structure:
{
config: {
modules: {
prompt_templating: {
prompt: {
template: [ /* messages */ ],
defaults: { /* placeholder defaults */ },
response_format: { /* text | json_object | json_schema */ },
tools: [ /* function definitions */ ]
},
model: {
name: "gpt-4.1",
version: "latest",
params: {
temperature: 0.7,
max_completion_tokens: 2000,
// ... other params
}
}
},
masking: { /* optional DPI configuration */ }
},
stream: { /* optional streaming config */ }
},
placeholder_values: { /* optional values for template placeholders */ },
messages_history: [ /* optional conversation history */ ]
}{
request_id: "uuid",
intermediate_results: {
templating: [ /* resolved messages */ ],
llm: {
id: "chatcmpl-xxx",
object: "chat.completion",
created: 1234567890,
model: "gpt-4.1-2024-08-06",
choices: [{
index: 0,
message: {
role: "assistant",
content: "response text",
tool_calls: [ /* if any */ ]
},
finish_reason: "stop"
}],
usage: {
prompt_tokens: 100,
completion_tokens: 50,
total_tokens: 150
}
},
output_unmasking: [ /* if masking enabled */ ]
},
final_result: { /* same structure as llm result */ }
}Prompt Templating:
- Messages are passed under
config.modules.prompt_templating.prompt.template - Supports system, user, assistant, tool, and developer roles
- Multi-modal content (text + images) supported
Response Format:
// Text (default when no tools)
response_format: { type: "text" }
// JSON object
response_format: { type: "json_object" }
// JSON schema (structured output)
response_format: {
type: "json_schema",
json_schema: {
name: "user_profile",
description: "User profile schema",
schema: {
type: "object",
properties: { /* JSON schema */ },
required: [ /* required fields */ ]
},
strict: true
}
}Tool Definitions:
tools: [
{
type: "function",
function: {
name: "calculator",
description: "Perform arithmetic operations",
parameters: {
type: "object",
properties: {
operation: { type: "string", enum: ["add", "subtract"] },
a: { type: "number" },
b: { type: "number" },
},
required: ["operation", "a", "b"],
},
},
},
];The masking module integrates with SAP Data Privacy Integration (DPI):
modules: {
prompt_templating: { /* ... */ },
masking: {
masking_providers: [{
type: "sap_data_privacy_integration",
method: "anonymization", // or "pseudonymization"
entities: [
{
type: "profile-email",
replacement_strategy: { method: "fabricated_data" }
},
{
type: "profile-person",
replacement_strategy: { method: "constant", value: "REDACTED" }
},
{
regex: "\\b[0-9]{4}-[0-9]{4}\\b",
replacement_strategy: { method: "constant", value: "ID_REDACTED" }
}
],
allowlist: ["SAP", "BTP"],
mask_grounding_input: { enabled: false }
}]
}
}Masking Flow:
- Input passes through masking module
- Sensitive data is anonymized/pseudonymized
- Masked data sent to LLM
- Response passes through output_unmasking (if configured)
- Original values restored in final output
The provider supports HTTP-level request cancellation via AbortSignal. The
per-call abortSignal is merged with the provider-level requestConfig (see
SAPAIProviderSettings.requestConfig)
via the internal mergeRequestConfig helper. Any signal present on
requestConfig is dropped so the AI SDK abortSignal always wins.
The snippets below illustrate Orchestration signal forwarding. The Foundation Models
path uses client.run() for non-streaming and a 3-argument
client.stream(request, abortSignal, requestConfig) for streaming; the same
mergeRequestConfig helper is applied in both cases.
abort-utils.ts cancels preparation waits independently of the SDK's transport
signal, observes late rejections, and releases late stream results without
starting their SSE iterators. SDK deployment discovery can continue because its
helpers expose no signal; the forwarded inference signal remains cancelled.
sap-http-stream.ts separates final-failure capture outside configured middleware
from transport lifecycle observation inside it. Cleanup retains original
body/request identities, not mutable response containers. Successful streams lease
those resources until iteration ends or cancellation closes them, so setup never
tears down a live recovered body or a wrapper around it. A lease-scoped abort
listener closes rejected requests after Axios has removed its own signal handler.
The bounded HTTP error-body reader is shared with Responses. Native Orchestration
and Foundation Models timeout observers cover failed responses only.
Responses owns successful-body adaptation, iterator/request cleanup, and timeout observation in its fetch-compatible transport. Its upgrade contract covers error-body reads and cancellation after HTTP error headers. The innermost lifecycle observer preserves socket inactivity timeouts before configured middleware can delay consumption. Fully received bodies remain available during that delay; active SSE traffic has no absolute duration limit.
Non-streaming (Orchestration):
const response = await client.chatCompletion(request, mergeRequestConfig(requestConfig, abortSignal));Streaming (Orchestration):
const stream = await client.stream(request, abortSignal, streamOptions, mergeRequestConfig(requestConfig, undefined));The signal is forwarded to the SAP AI SDK, which passes it to the underlying
Axios HTTP client to cancel the request. Canceling the returned provider stream
also aborts its SDK transport before closing the iterator. Already-aborted
language-model calls and in-flight stream aborts produce a non-retryable
APICallError (status 499), including with custom abort reasons. An aborted
stream does not emit a successful finish or complete a partial tool call.
Cancellation does not guarantee that SAP AI Core or the deployed model stops
server-side processing.
This diagram shows how tool calling (function calling) works. When the AI model
needs to call a tool, it returns structured tool call requests. Your application
executes the tools and provides results back, which the model uses to generate
the final response. The tools below provide execute functions, and
stopWhen: stepCountIs(2) allows the second model call after tool execution.
sequenceDiagram
participant App as Application
participant SDK as Vercel AI SDK
participant Provider as SAP AI Provider
participant SAP as SAP AI Core
participant Model as AI Model
participant Tool as Tool Function
rect rgb(230, 240, 255)
Note over App,SDK: 1. Initial Request with Tools
App->>SDK: generateText({<br/> model: provider('gpt-4.1'),<br/> prompt: 'What is 5+3 and weather in Tokyo?',<br/> stopWhen: stepCountIs(2),<br/> tools: {<br/> calculate: calculatorTool,<br/> getWeather: weatherTool<br/> }<br/>})
end
rect rgb(255, 240, 230)
Note over SDK,Provider: 2. Tool Registration
SDK->>Provider: doGenerate({<br/> prompt: [...],<br/> tools: [<br/> {type: "function", name: "calculate", ...},<br/> {type: "function", name: "getWeather", ...}<br/> ]<br/>})
Provider->>Provider: Build orchestration configuration<br/>{config: {modules: {prompt_templating: {<br/> prompt: {tools: [{type: "function", function: {name: "calculate", parameters: {...}}}, ...]},<br/> model: {name: "gpt-4.1", version: "latest", params: {...}}<br/>}}}}
end
rect rgb(240, 255, 240)
Note over Provider,Model: 3. Model Decides to Use Tools
Provider->>SAP: POST /v2/completion
SAP->>Model: Forward request with tools
Model->>Model: Analyze prompt<br/>Decide tool usage
Model-->>SAP: Response with tool_calls
SAP-->>Provider: {<br/> final_result: {<br/> choices: [{<br/> message: {<br/> role: "assistant",<br/> content: null,<br/> tool_calls: [<br/> {id: "call_1", function: {<br/> name: "calculate",<br/> arguments: '{"a":5,"b":3}'<br/> }},<br/> {id: "call_2", function: {<br/> name: "getWeather",<br/> arguments: '{"city":"Tokyo"}'<br/> }}<br/> ]<br/> },<br/> finish_reason: "tool_calls"<br/> }]<br/> }<br/>}
end
rect rgb(255, 245, 230)
Note over Provider,SDK: 4. Tool Call Extraction
Provider->>Provider: Parse tool calls<br/>Extract: name, id, arguments
Provider-->>SDK: {<br/> content: [<br/> {type: "tool-call", toolCallId: "call_1", ...},<br/> {type: "tool-call", toolCallId: "call_2", ...}<br/> ],<br/> finishReason: {unified: "tool-calls", raw: "tool_calls"}<br/>}
end
rect rgb(240, 240, 255)
Note over SDK,Tool: 5. Tool Execution
SDK->>App: Execute tools
par Parallel Execution (if enabled)
App->>Tool: calculate({a: 5, b: 3})
Tool-->>App: 8
and
App->>Tool: getWeather({city: "Tokyo"})
Tool-->>App: "sunny, 72°F"
end
App->>SDK: Tool results
end
rect rgb(255, 240, 255)
Note over SDK,Model: 6. Continue with Tool Results
SDK->>Provider: doGenerate with prior prompt,<br/>assistant tool-call content parts,<br/>and tool tool-result content parts
Provider->>Provider: Convert toolCallId / input / output<br/>to SAP tool_calls / tool_call_id / content
Provider->>SAP: POST with converted tool calls and results
SAP->>Model: Continue generation
Model->>Model: Process tool results<br/>Generate final response
Model-->>SAP: Final answer
SAP-->>Provider: {<br/> final_result: {<br/> choices: [{<br/> message: {<br/> role: "assistant",<br/> content: "5+3=8. Tokyo weather: sunny, 72°F"<br/> },<br/> finish_reason: "stop"<br/> }]<br/> }<br/>}
end
rect rgb(230, 255, 240)
Note over Provider,App: 7. Final Response
Provider-->>SDK: {<br/> content: [{type: "text", text: "..."}],<br/> finishReason: {unified: "stop", raw: "stop"}<br/>}
SDK-->>App: {<br/> text: "5+3=8. Tokyo weather: sunny, 72°F",<br/> steps: [tool-call step, final-answer step]<br/>}
end
This diagram illustrates how SAP Data Privacy Integration (DPI) works. When enabled, sensitive data in prompts is automatically masked before being sent to AI models, and the masked entities are tracked and unmasked in responses.
sequenceDiagram
participant App as Application
participant Provider as SAP AI Provider
participant SAP as SAP AI Core
participant DPI as Data Privacy Integration
participant Model as AI Model
rect rgb(255, 240, 240)
Note over App,Provider: 1. Request with Sensitive Data
App->>Provider: generateText with masking config<br/>prompt contains email + order ID
end
rect rgb(240, 255, 240)
Note over Provider,DPI: 2. Masking Module Processing
Provider->>SAP: POST /v2/completion<br/>{<br/> config: {<br/> modules: {<br/> prompt_templating: {...},<br/> masking: {<br/> masking_providers: [{...}]<br/> }<br/> }<br/> }<br/>}
SAP->>DPI: Apply masking
DPI->>DPI: Detect entities and replace<br/>with anonymized values
DPI-->>SAP: Masked prompt sent to LLM
end
rect rgb(240, 240, 255)
Note over SAP,Model: 3. LLM Processing
SAP->>Model: Send masked prompt
Model->>Model: Generate response<br/>(only sees masked data)
Model-->>SAP: Response with masked values
end
rect rgb(255, 240, 255)
Note over SAP,DPI: 4. Output Unmasking (optional)
SAP->>DPI: Unmask output
DPI->>DPI: Restore original values
DPI-->>SAP: Unmasked response
end
rect rgb(230, 255, 240)
Note over SAP,App: 5. Return Response
SAP-->>Provider: {<br/> intermediate_results: {<br/> templating: [masked messages],<br/> llm: {...},<br/> output_unmasking: [unmasked result]<br/> },<br/> final_result: {...}<br/>}
Provider-->>App: Final text with<br/>original sensitive data<br/>preserved (if unmasking enabled)
end
Authentication is handled by the SAP AI SDK packages and the SAP Cloud SDK. This provider doesn't implement an OAuth manager or token cache. It creates SAP SDK clients with the selected deployment configuration, resource group, and optional destination settings, then the SDK layers resolve credentials and manage tokens.
The SAP SDK layers read credentials from the standard SAP Cloud SDK sources:
- Local:
AICORE_SERVICE_KEYenvironment variable - SAP BTP:
VCAP_SERVICESservice binding - Custom destination:
destinationpassed tocreateSAPAIProvider()
sequenceDiagram
participant App as Application
participant Provider as SAP AI Provider
participant SAPSDK as SAP AI SDK / SAP Cloud SDK
participant OAuth as SAP OAuth2 Server
participant SAPAI as SAP AI Core API
App->>Provider: createSAPAIProvider(options)
Provider->>Provider: Store provider settings
App->>Provider: generateText() / streamText()
Provider->>SAPSDK: Create Orchestration or Foundation Models client
SAPSDK->>SAPSDK: Resolve credentials and cached token
alt Token missing or expired
SAPSDK->>OAuth: Request access token
OAuth-->>SAPSDK: access_token
SAPSDK->>SAPSDK: Cache token for reuse
end
SAPSDK->>SAPAI: Send authenticated request
SAPAI-->>SAPSDK: SAP AI Core response
SAPSDK-->>Provider: SDK response object
Provider-->>App: AI SDK result
This provider is responsible for:
- Selecting Orchestration or Foundation Models API
- Passing
deploymentId,resourceGroup, anddestinationto SAP SDK clients - Applying model settings and per-call provider options
- Converting messages and responses between AI SDK and SAP formats
- Converting SAP SDK errors to Vercel AI SDK error types
The SAP AI SDK and SAP Cloud SDK are responsible for credential discovery, token acquisition, token caching, token refresh, and authenticated HTTP calls.
The provider implements robust error handling by converting SAP AI SDK errors to standard Vercel AI SDK error types for consistent error handling across providers.
// Internal error handling in doGenerate/doStream
try {
const response = await client.chatCompletion({ messages });
// Process response...
} catch (error) {
// Convert to AI SDK standard errors
throw convertToAISDKError(error, {
operation: "doGenerate",
url: "sap-ai:orchestration",
requestBody: requestSummary,
});
}The convertToAISDKError() function handles error conversion with a clear
priority:
- Existing standard request/API error? → Preserve
APICallError,LoadAPIKeyError,NoSuchModelError,InvalidPromptError, andUnsupportedFunctionalityErroracross SDK package versions - Aborted request? → Non-retryable
APICallErrorwith status 499 - Structured SAP error? → Convert 401/403 to
LoadAPIKeyError, 404 toNoSuchModelError, and other statuses toAPICallError - HTTP response status? →
APICallErrorpreserving the status, even if the body is not a structured SAP error; successful headers do not mask a native connection failure while reading the body - Native parser failure? → Retain the enclosing SDK summary, or a generic parse-error message, instead of exposing parser input fragments
- Transient native connection code? → Retryable status 503, preserving the original cause and response diagnostics
- Recognized error message? → Classify authentication/deployment failures,
extract a status from
status code NNN, or apply a category-specific mapping - Unknown error? → Non-retryable
APICallErrorwith status 500
Converted APICallError instances carry the supplied URL and request summary,
plus response headers/body when available. Authentication and model errors do
not expose those HTTP-context fields; structured SAP request IDs are included
in their messages.
For structured SAP errors and statuses extracted from error messages, the provider classifies HTTP statuses as follows:
- 408 (Request Timeout):
isRetryable: true→ Retry after timeout - 409 (Conflict):
isRetryable: true→ Retry on transient conflicts - 429 (Rate Limit):
isRetryable: true→ Exponential backoff - 5xx (Server Errors):
isRetryable: true→ Exponential backoff - 400 (Bad Request):
isRetryable: false→ Client must fix request - 401/403 (Auth Errors): Non-retryable → Fix credentials
- 404 (Not Found): Non-retryable → Fix model/deployment
Message-based categories can override status-based retryability: for example,
unknown errors and stream-consumption errors use status 500 but are not
retryable. LoadAPIKeyError and NoSuchModelError have no isRetryable field.
High-level Vercel AI SDK calls handle retries based on isRetryable and
maxRetries. Direct provider calls do not add a retry loop, and failures after
streaming has begun require application handling.
For structured SAP error responses, this provider uses standard Vercel AI SDK error types:
- 401/403 (Authentication) →
LoadAPIKeyError - 404 (Model/Deployment not found) →
NoSuchModelError - Other HTTP errors →
APICallErrorwith SAP metadata inresponseBody
Generic SDK/Axios errors follow the message-based classification above. For
example, Request failed with status code 404 without a structured SAP body
becomes APICallError, not NoSuchModelError. Handle both forms.
Breaking change in v3.0.0: The custom SAPAIError class was removed to
ensure full compatibility with the AI SDK ecosystem and enable automatic retry
mechanisms.
For implementation details and code examples:
- API Reference - Error Handling Examples - Complete examples with all error types
- Troubleshooting Guide - Quick reference and common issues
For v2→v3 migration, see Migration Guide - v2 to v3.
Key types for model configuration:
SAPAIModelId: String union of supported models (e.g., "gpt-4.1", "anthropic--claude-4.5-sonnet", "gemini-2.5-pro") with flexibility for custom modelsSAPAISettings: Interface withmodelVersion,modelParams(maxTokens, temperature, topP, etc.),responseFormat,includeReasoning, nativeresponsesoptions, and API-specificdropUnsupportedParams, masking, filtering, grounding, and translation options
See src/sap-ai-settings.ts for complete type definitions.
Orchestration and Foundation Models Chat Completions use types from
@sap-ai-sdk/orchestration and @sap-ai-sdk/foundation-models. Key SAP types
include:
ChatCompletionRequest: Per-call messages, message history, and placeholder valuesOrchestrationModuleConfig: Model and module configuration passed to the client constructorOrchestrationResponse: API responses with module resultsChatMessage: Message format (role, content, tool calls)ChatCompletionTool: Function definitions and parameters
See src/sap-ai-settings.ts for the main settings interface and re-exported SAP
AI SDK types. Responses uses native V4 contracts and V3 compatibility adapters.
@ai-sdk/openai handles protocol conversion; SAP deployment and HTTP transport
types remain at the transport boundary. See
Strategy Pattern (API Selection) for that
separation and the Responses API contract for
its public options.
The provider implements the factory pattern for model creation:
interface SAPAIProvider extends ProviderV3 {
// Function call syntax
(modelId: SAPAIModelId, settings?: SAPAISettings): SAPAILanguageModel;
// Method call syntax
chat(modelId: SAPAIModelId, settings?: SAPAISettings): SAPAILanguageModel;
}The message conversion system adapts between Vercel AI SDK format and SAP AI
Core format. The convertToSAPMessages() function transforms prompt arrays,
handling text content, images, files, tool calls, and tool results across different
message formats.
The provider lazily selects Orchestration, Foundation Models Chat Completions, or Responses. API selection is explicit and follows provider, model, and invocation precedence; the default remains Orchestration.
Orchestration supplies optional native-reasoning and provider-field extractors to the shared V3 result builder and stream transformer. One reasoning part represents each SAP block; complete block metadata is replayed through the prompt converter under the configured provider namespace. The stream transformer preserves positional blocks until EOF, appends content, and replaces signatures according to SDK semantics. Foundation Models leaves these capabilities unset.
Provider-specific fields are captured from individual chunks because the SDK's final aggregate omits them. Unified finish reasons remain SAP-based; original provider reasons survive separately as raw diagnostics. Versioned facades retain the standard reasoning parts and their metadata without another conversion layer.
Responses implements the shared V3 strategy methods plus native V4 entrypoints,
because its request and event formats differ from Chat Completions.
@ai-sdk/openai handles native message conversion, SSE events, function calls, usage, and reasoning
history. responses-http-transport.ts adapts the SAP SDK HTTP client to its
fetch interface, preserving SAP authentication, deployment discovery and model
version selection, custom destinations, request configuration, and cancellation.
There is no second credential store or OpenAI API key.
The delegate serializes each request once. The transport passes no body to SAP's
executeRequest serializer and installs that string in its outer request
middleware before caller middleware. Caller middleware and request transforms
therefore receive the serialized string; retry middleware can retain body changes
between attempts. SAP still owns authentication and HTTP execution.
Transport context contains only cancellation, headers, the explicit generation operation, and a callback that computes a safe request summary once, only on failure. It does not inspect prompt types or parse the serialized request. Each invocation records only API errors emitted by its response-body read boundary in a private weak set. Recovery accepts a recorded direct cause of a successful-status API error, not delegate wording or arbitrary nested causes. Parser and schema failures remain distinct from transport failures.
language-model-invocation.ts resolves, parses, and validates API settings once
per invocation before the selected strategy prepares its prompt. A cached
discriminated strategy descriptor selects native V4 Responses or the existing
V3 Orchestration/Foundation Models strategies. The cache remains keyed only by
API, with shared pending loads and eviction after failed initialization.
responses-prompt.ts prepares native V4 tagged media, references, and provider
namespaces without copying file bytes. It rejects assistant file and
reasoning-file history, unsupported custom kinds, and compaction without an
item ID before discovery. Supported compaction and encrypted reasoning retain
their native history, including encrypted reasoning without an item ID.
Only legacy Responses entrypoints use responses-adapters-v3-to-v4.ts and
responses-adapters-v4-to-v3.ts. They reject output without a V3 equivalent and
map interrupted finish reasons and deprecated warnings to legacy values.
Compatibility conversion stays inside the existing disposal and stream-error
boundary; failures produce error events rather than raw stream rejections.
Native V4 preserves all delegate content and events, including custom content,
reasoning files, tagged generated files, citations, approvals, native warnings,
structuredOutputText, text tool-input encoding, and interrupted EOF.
The strategy translates metadata between the configured SAP namespace and the OpenAI delegate on every message and content part. This preserves response item IDs and encrypted reasoning across stateless tool conversations. It does not flatten reasoning into Chat Completions text. Responses has no embedding strategy, and validation rejects incompatible API-specific settings. See the Responses API contract for user-facing options.
responses-http-transport.ts imports only the cached deployment-ID resolver
getFoundationModelDeploymentId through @sap-ai-sdk/ai-api/internal.js; the
public SDK has no equivalent cached resolver. Resource groups come from normalized
deployment configuration, and the transport composes its deployment URL locally.
Destination URL composition follows SAP's existing policy: remove one trailing
slash, then append /v2 only when the remaining URL pathname is /.
The resolver, SAP HTTP middleware/error shapes, and OpenAI delegate stream behavior
form an upgrade-sensitive boundary. Passing the current suite does not establish
compatibility with later SDK versions.
When upgrading SAP or OpenAI SDK dependencies, run the contract regressions:
responses-adapters-v3-to-v4.test.tschecks tagged media, canonical URLs, and provider file references.responses-adapters-v4-to-v3.test.tschecks generated files, warning and finish-reason conversion, and rejection of output unrepresentable in V3.responses-prompt.test.tschecks native tagged media, byte identity, canonical URLs, namespace precedence, and history rejection.responses-native-contract.test.tsuses typed delegate doubles for native files, reasoning files, and deprecated warnings that the installed wire parser does not produce. It also checks native event fidelity and legacy conversion-error cancellation.responses-http-transport.node.test.tschecks deployment URLs, destinations, request configuration, header precedence, status policies, response backpressure, cancellation during pending SDK setup, listener cleanup, and disposal of late HTTP responses.responses-discovery-cancellation.node.test.tschecks that both public generation methods settle after cancellation while a real SAP deployment-discovery HTTP response remains pending. SAP's discovery helpers accept no signal; this verifies caller rejection, not upstream discovery cancellation.responses-http-errors.node.test.tschecks final HTTP error preservation after configured middleware retries, authentication errors, non-JSON and truncated error bodies, byte-bounded UTF-8 diagnostics, and caller aborts while reading those bodies. Oversized errors must close upstream and preserve their status, received prefix, request ID, and retry headers; caller cancellation remains status 499.responses-error-classification.node.test.tschecks transport errors beneath successful-response wrappers, diagnostic preservation, and recovery from a real TCP reset before output. The server sends a partial JSON/SSE body and closes its socket; high-level generation and streaming must recover on the second request withmaxRetries: 1. Cancellation and genuine parsing failures retain their separate classifications.responses-timeout.node.test.tschecks body-read inactivity timeouts with redirects disabled, active SSE traffic, delayed middleware, completed responses, HTTP-error diagnostics, cancellation, socket closure, and connection reuse after success or failure.responses-language-model.node.test.tsandresponses-language-model-strategy.test.tscheck deployment discovery, serialized string bodies through caller middleware, transforms and retries, native reasoning history, provider namespaces, late SSE error classification, and cancellation across the supported entrypoints. The versioned adapter suites check legacy compatibility separately from native V4 Responses.
An equivalent public SAP API may replace an internal helper only after it preserves destinations, deployment selection, request configuration, middleware ordering, HTTP diagnostics, and stream/request cleanup. Local HTTP fixtures establish client behavior; verify deployment-specific behavior against SAP AI Core separately. Edge source tests do not establish pure Edge deployability of the published Node.js package.
graph TB
subgraph "Application Layer"
App[Your Application]
SDK[Vercel AI SDK]
end
subgraph "Provider Layer"
Provider[SAPAIProvider]
LM[SAPAILanguageModel]
EM[SAPAIEmbeddingModel]
Validation[API Resolution<br/>& Validation]
end
subgraph "Strategy Layer"
Factory[Strategy Factory<br/>━━━━━━━━━━━━━<br/>• Lazy Loading<br/>• Promise Caching<br/>• SDK Import]
Cache[(Strategy Cache<br/>Key: API Type)]
end
subgraph "Language Model Strategies"
LMStrategy[LanguageModelAPIStrategy<br/>━━━━━━━━━━━━━━━━━━<br/>interface:<br/>• doGenerate#40;#41;<br/>• doStream#40;#41;]
BaseLM[BaseLanguageModelStrategy<br/>━━━━━━━━━━━━━━━━━━<br/>Template Method:<br/>• buildCommonParts#40;#41;<br/>• abstract buildRequest#40;#41;]
OrchLM[OrchestrationLanguageModelStrategy]
FMLM[FoundationModelsLanguageModelStrategy]
ResponsesLM[ResponsesLanguageModelStrategy<br/>Native V4 + V3 compatibility]
end
subgraph "Embedding Model Strategies"
EMStrategy[EmbeddingModelAPIStrategy<br/>━━━━━━━━━━━━━━━━━━<br/>interface:<br/>• doEmbed#40;#41;]
BaseEM[BaseEmbeddingModelStrategy<br/>━━━━━━━━━━━━━━━━━━<br/>Template Method:<br/>• doEmbed#40;#41;<br/>• abstract createClient#40;#41;<br/>• abstract executeCall#40;#41;<br/>• abstract extractEmbeddings#40;#41;<br/>• abstract extractTokenCount#40;#41;<br/>• abstract getUrl#40;#41;]
OrchEM[OrchestrationEmbeddingModelStrategy]
FMEM[FoundationModelsEmbeddingModelStrategy]
end
subgraph "SAP AI SDKs"
OrchSDK[Orchestration SDK<br/>OrchestrationClient]
FMSDK[Foundation Models SDK<br/>AzureOpenAiChatClient]
ResponsesSDK[OpenAI Responses Provider<br/>SAP SDK HTTP Transport]
end
App -->|generateText/streamText| SDK
SDK -->|doGenerate/doStream| LM
SDK -->|doEmbed| EM
Provider -->|creates| LM
Provider -->|creates| EM
LM -->|resolveApi| Validation
EM -->|resolveApi| Validation
Validation -->|api type| Factory
Factory -->|cache check| Cache
Factory -->|lazy import| OrchLM
Factory -->|lazy import| FMLM
Factory -->|lazy import| ResponsesLM
Factory -->|lazy import| OrchEM
Factory -->|lazy import| FMEM
BaseLM -.->|implements| LMStrategy
OrchLM -.->|extends| BaseLM
FMLM -.->|extends| BaseLM
ResponsesLM -.->|implements| LMStrategy
BaseEM -.->|implements| EMStrategy
OrchEM -.->|extends| BaseEM
FMEM -.->|extends| BaseEM
OrchLM -->|uses| OrchSDK
OrchEM -->|uses| OrchSDK
FMLM -->|uses| FMSDK
ResponsesLM -->|uses| ResponsesSDK
FMEM -->|uses| FMSDK
style Provider fill:#e1f5ff
style Factory fill:#fff4e1
style LMStrategy fill:#ffe1f5
style EMStrategy fill:#ffe1f5
style OrchSDK fill:#e1ffe1
style FMSDK fill:#f5e1ff
Strategies are loaded lazily at first invocation - not at provider creation time. This enables:
- Deferred client loading - API client packages are dynamically imported when a strategy is first needed; public helper re-exports may load other SDK code earlier
- Shared strategy instances - Cache one loading promise per API and model kind
- Runtime flexibility - Select APIs at provider, model, or call level, subject to API-specific feature validation
sequenceDiagram
participant App as Application
participant LM as SAPAILanguageModel
participant Val as API Validation
participant Factory as Strategy Factory
participant Cache as Strategy Cache
participant SDK as SAP AI SDK
rect rgb(240, 248, 255)
Note over App,LM: 1. First API Call
App->>LM: doGenerate(options)
LM->>Val: resolveApi(providerApi, modelApi, callApi)
Val-->>LM: effectiveApi = "orchestration"
end
rect rgb(255, 248, 240)
Note over LM,Cache: 2. Strategy Resolution (Lazy)
LM->>Factory: getOrCreateLanguageModelStrategy("orchestration")
Factory->>Cache: Check cache
Cache-->>Factory: Not found
end
rect rgb(248, 255, 240)
Note over Factory,SDK: 3. Lazy Import & Caching
Factory->>Factory: Cache Promise SYNCHRONOUSLY
Factory->>SDK: import("@sap-ai-sdk/orchestration")
SDK-->>Factory: { OrchestrationClient }
Factory->>Factory: new OrchestrationLanguageModelStrategy(OrchestrationClient)
Factory-->>LM: strategy
end
rect rgb(255, 240, 248)
Note over LM,SDK: 4. Execute via Strategy
LM->>Factory: strategy.doGenerate(config, settings, options)
Note right of Factory: Config passed per-call<br/>(tenant-specific, not cached)
Factory->>SDK: client.chatCompletion(...)
SDK-->>Factory: response
Factory-->>LM: LanguageModelV3GenerateResult
end
rect rgb(240, 255, 255)
Note over App,Cache: 5. Subsequent Calls (Cached)
App->>LM: doGenerate(options)
LM->>Factory: getOrCreateLanguageModelStrategy("orchestration")
Factory->>Cache: Check cache
Cache-->>Factory: Cached strategy (instant)
Factory-->>LM: strategy
end
Strategies implement stateless interfaces - all tenant-specific configuration flows through method parameters, never cached in strategy instances:
// Language model strategy interface
interface LanguageModelAPIStrategy {
doGenerate(
config: LanguageModelStrategyConfig, // Tenant config - passed per-call
settings: SAPAIModelSettings, // Merged model settings
options: LanguageModelV3CallOptions, // AI SDK options
): Promise<LanguageModelV3GenerateResult>;
doStream(config: LanguageModelStrategyConfig, settings: SAPAIModelSettings, options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult>;
}
// Embedding model strategy interface
interface EmbeddingModelAPIStrategy {
doEmbed(config: EmbeddingModelStrategyConfig, settings: SAPAIEmbeddingSettings, options: EmbeddingModelV3CallOptions, maxEmbeddingsPerCall: number): Promise<EmbeddingModelV3Result>;
}BaseEmbeddingModelStrategy centralizes
batch-size validation, embedding options, request configuration, result assembly,
and error conversion. Its API-specific subclasses supply these hooks:
createClient(config, settings, embeddingOptions): Creates the SAP SDK client.executeCall(client, values, embeddingType, requestConfig): Sends the request.extractEmbeddings(response): Extracts and normalizes embedding vectors.extractTokenCount(response): Retrieves token usage.getUrl(): Supplies the API identifier for error context.
The base class merges provider requestConfig, per-call headers, and
abortSignal before calling executeCall; cancellation is not a separate hook
argument. Optional resolveWarnings() and extractResponseMetadata() hooks
surface API-specific warnings, request IDs, and response headers.
BaseLanguageModelStrategy centralizes
message conversion, parameter precedence, cancellation, response assembly, and
error conversion for generation and streaming. The concrete Orchestration and
Foundation Models strategies build API-specific requests and clients.
For nonstreaming calls, executeApiCall(client, request, requestConfig) receives
the merged transport configuration, including per-call headers and cancellation.
Streaming uses the SDK
cancellation signatures and delegates event conversion
to the shared stream transformer.
The effective API is resolved with a clear priority order:
Call-time api > Model-time api > defaultSettings.api > Provider-time api > "orchestration"
// Provider-level default
const provider = createSAPAIProvider({ api: "orchestration" });
// Model-level override
const model = provider("gpt-4.1", { api: "foundation-models" });
// Call-level override (highest priority)
const result = await generateText({
model,
prompt: "Hello",
providerOptions: {
"sap-ai": { api: "orchestration" }, // Wins!
},
});defaultSettings.api participates when model settings omit api or set it to
undefined. Call-time selection does not discard incompatible model settings.
The validation layer ensures features are compatible with the resolved API:
- Orchestration-only features: masking, filtering, grounding, templating, translation
- Foundation Models-only feature:
dataSources - Common features: temperature, maxTokens, topP, seed, stop sequences, tools, streaming
Incompatible feature combinations throw UnsupportedFeatureError with helpful
suggestions for which API to use instead. A call-time language-model API switch
that conflicts with configured API-specific features instead throws
ApiSwitchError. Additional modelParams such as logprobs and logit_bias
are passed through; their support is determined by the SAP backend/model rather
than these API-feature checks.
- Connection Pooling: Reuse HTTP connections
- Request Batching: Group multiple requests when possible
- Caching: Reuse stateless strategy instances and let SAP Cloud SDK handle token caching; SAP SDK clients are created per call
- Compression: Enable gzip/deflate for requests/responses
- Stream Processing: Use streams for large responses
- Pull-Based TransformStream: SDK
AsyncIterable→ReadableStream→TransformStreampipeline matching the idiomatic Vercel AI SDK provider pattern, enabling natural backpressure propagation - Garbage Collection: Proper cleanup of resources
- Buffer Management: Efficient handling of binary data
Consider tracking:
- Request counts (total, successful, failed)
- Response times and token usage
- Error rates by status code
- SAP SDK authentication and service-binding errors
These are application-level recommendations, not built-in provider features:
- Horizontal Scaling: Support for multiple instances
- Load Balancing: Distribute requests across deployments
- Circuit Breaker: Prevent cascade failures
- Rate Limiting: Client-side rate limiting to prevent 429s (e.g., token bucket or sliding window algorithm)
This architecture ensures the SAP AI Provider is robust, scalable, and maintainable while providing a seamless integration experience with the Vercel AI SDK.
This repository publishes two npm packages from a single codebase. The main package exposes four entrypoints for three provider specifications; the standalone V2 package preserves the existing package name for consumers that cannot use subpath exports.
| Package export | Interface | Target users |
|---|---|---|
@jerome-benoit/sap-ai-provider |
LanguageModelV3 / EmbeddingModelV3 |
AI SDK 6 |
@jerome-benoit/sap-ai-provider/v2 |
LanguageModelV2 / EmbeddingModelV2 |
AI SDK 5; AI SDK 6 compatibility |
@jerome-benoit/sap-ai-provider/v3 |
Same V3 exports as the root | AI SDK 6 |
@jerome-benoit/sap-ai-provider/v4 |
LanguageModelV4 / EmbeddingModelV4 |
AI SDK 7 |
@jerome-benoit/sap-ai-provider-v2 |
LanguageModelV2 / EmbeddingModelV2 |
AI SDK 5; AI SDK 6 compatibility |
The root and /v3 share src/index.ts and the exact same export targets:
dist/index.js / dist/index.d.ts for ESM and dist/index.cjs /
dist/index.d.cts for CommonJS. There is no V3 facade or extra bundle. The
four package entrypoints use three artifact families: index.*,
index-v2.*, and index-v4.*.
V4 language calls share API preparation with V3, then dispatch Responses directly to its native V4 strategy. Orchestration and Foundation Models normalize V4 prompts to V3 and convert results back. V4 embeddings still wrap the V3 model. URL capabilities remain conservative because high-level SDK capability lookup precedes invocation-level API overrides; capabilities are not shared mutable state.
src/
├── index-v4.ts # V4 public API exports (AI SDK 7 facade)
├── sap-ai-provider-v4.ts # V4 provider factory
├── sap-ai-language-model-v4.ts # Native Responses and legacy API dispatch
├── sap-ai-embedding-model-v4.ts # V3 embedding facade
├── language-model-invocation.ts # Shared API preparation
├── responses-prompt.ts # Native V4 Responses history
├── sap-ai-adapters-v4-to-v3.ts # Legacy API prompt normalization
└── sap-ai-adapters-v3-to-v4.ts # Legacy API result and stream conversion
The V2 package uses a facade that wraps the internal V3 implementation and preserves AI SDK 5 result contracts. Its published declarations include the required V2 types.
V2 language-model inputs use the current upstream contracts, accepting both
provider-tool discriminators shipped with AI SDK 5 and 6. Warning declarations
reflect the other warnings that the adapters actually return. These are type-only
compatibility measures, not an additional runtime implementation.
The JSON type divergence remains in provider 2.0.4 and 4.0.13; see upstream PR #8537.
graph TB
subgraph "V2 Package (Facade)"
V2Provider[SAPAIProviderV2]
V2LM[SAPAILanguageModelV2]
V2EM[SAPAIEmbeddingModelV2]
Adapters[V3-to-V2 Adapters]
end
subgraph "Internal V3 Implementation"
V3LM[SAPAILanguageModel]
V3EM[SAPAIEmbeddingModel]
Strategies[API Strategies]
end
subgraph "SAP AI Core"
OrchAPI[Orchestration API]
FMAPI[Foundation Models API]
end
V2Provider -->|creates| V2LM
V2Provider -->|creates| V2EM
V2LM -->|delegates to| V3LM
V2EM -->|delegates to| V3EM
V2LM -->|uses| Adapters
V2EM -->|uses| Adapters
Adapters -->|converts V3 results| V2LM
Adapters -->|converts V3 results| V2EM
V3LM -->|uses| Strategies
V3EM -->|uses| Strategies
Strategies -->|calls| OrchAPI
Strategies -->|calls| FMAPI
style V2Provider fill:#ffe1f5
style V2LM fill:#ffe1f5
style V2EM fill:#ffe1f5
style Adapters fill:#fff4e1
style V3LM fill:#e1f5ff
style V3EM fill:#e1f5ff
src/
├── index-v2.ts # V2 public API exports (AI SDK 5 facade)
├── sap-ai-provider-v2.ts # V2 provider factory (facade)
├── sap-ai-language-model-v2.ts # V2 language model (delegates to V3)
├── sap-ai-embedding-model-v2.ts # V2 embedding model (delegates to V3)
└── sap-ai-adapters-v3-to-v2.ts # Type adapters (V3 results → V2 format)
The adapter layer (sap-ai-adapters-v3-to-v2.ts) handles conversion between V3 and V2 interfaces:
- Finish Reason:
{ unified, raw? }object → string ("stop","tool-calls", etc.) - Usage: Nested structure with
inputTokens.total→ flat{ inputTokens, outputTokens, totalTokens } - Stream Parts: Preserves text/reasoning block lifecycle and deltas; converts finish/warning payloads and drops unsupported V3-only content
- Warnings: V3
unsupported/compatibilitywarnings → V2otherwarnings with descriptive messages
The builds are sequential to the same dist/ directory:
# Main package build: root, /v2, /v3, /v4 using three artifact families
npm run build # tsup.config.ts → dist/
npm publish # @jerome-benoit/sap-ai-provider
# V2 publication (run from a separate clean checkout)
AI_SDK_VERSION=v2 npm publishWhy sequential? Both builds use clean: true and replace dist/. The
standalone publication also rewrites package.json and package-lock.json and
removes the /v2, /v3, and /v4 exports, leaving only the V2 root API.
Run it in a separate clean checkout. Do not run prepare:v2 manually before
npm publish: its lifecycle builds V2, prepares it, and verifies the prepared exports.
- Shared infrastructure: All entrypoints share SAP authentication, API validation, and strategy selection.
- Contract-specific dispatch: V2 wraps V3; V4 uses native Responses, V3-compatible language strategies for other APIs, and V3 embeddings.
- Versioned entrypoints: One main package supports AI SDK 5–7 without mixing model contracts
- Standalone V2 publication: Existing V2 consumers retain their dedicated package
- Adapter isolation: Version conversions remain centralized and independently testable
For getting started and basic usage, see the README.
Related Technical Documentation:
- API Reference - Complete type definitions and interfaces referenced in this architecture document
- cURL API Testing Guide - Low-level API debugging to understand request/response flows described above