This guide helps diagnose and resolve common issues when using the SAP AI Core
Provider.
Examples below use AI SDK 6 and the V3 root entrypoint. For AI SDK 7, use
@jerome-benoit/sap-ai-provider/v4; for AI SDK 5, use /v2 and
textEmbeddingModel() instead of embedding().
The explicit @jerome-benoit/sap-ai-provider/v3 subpath is identical to the
root V3 entrypoint. The standalone V2 package does not provide a /v3 subpath.
| Issue | Section |
|---|---|
| 401 Unauthorized | Authentication Issues |
| 403 Forbidden | Authentication Issues |
| 404 Not Found | Model and Deployment Issues |
| 400 Bad Request | API Errors |
| 400 Template errors | Problem: Template Placeholder Conflicts |
| 429 Rate Limit | API Errors |
| 500-504 Server Errors | API Errors |
| UnsupportedFeatureError | API-specific feature mismatch |
| ApiSwitchError | API switch conflict |
| TooManyEmbeddings | Embedding Issues |
| Tools not called | Tool Calling Issues |
| Stream issues | Streaming Issues |
| Slow responses | Performance Issues |
Quick solutions for the most frequent issues:
-
🔴 401 Unauthorized
- Cause: Missing or invalid
AICORE_SERVICE_KEY - Fix: Authentication Setup Guide
- ETA: 2 minutes
- Cause: Missing or invalid
-
🟠 404 Model Not Found
- Cause: Model not available in your tenant/region
- Fix: Model Availability Guide
- ETA: 5 minutes
-
🟡 429 Rate Limit Exceeded
- Cause: Too many requests
- Fix: Use bounded AI SDK retries and reduce request volume; see rate-limit guidance
- ETA: Depends on tenant quota and service limits
-
🟢 Streaming Not Working
- Cause: Incorrect iteration pattern
- Fix: Streaming Guide
- ETA: 2 minutes
-
🔵 Tools Not Being Called
- Cause: Vague tool descriptions
- Fix: Tool Calling Guide
- ETA: 5 minutes
For other issues, see the detailed Table of Contents below.
- Quick Reference
- Common Problems (Top 5)
- Authentication Issues
- API Errors
- Model and Deployment Issues
- Streaming Issues
- Tool Calling Issues
- Performance Issues
- Debugging Tools
- Getting Help
- Embedding Issues
- Known Limitations
- V2 Facade Package Issues
- Related Documentation
Symptoms: HTTP 401, "Invalid token", authentication fails when making a request,
LoadAPIKeyError or APICallError thrown depending on the error shape
Solutions:
- Verify
AICORE_SERVICE_KEYenvironment variable is set and contains valid JSON - → Complete setup guide: Environment Setup Guide
Solution: npm install dotenv and add import "dotenv/config"; at top of
entry file
Symptoms: HTTP 403, "Insufficient permissions"
Solutions:
- Verify service key has necessary permissions
- Check
AI-Resource-Groupheader matches deployment - Confirm SAP BTP account has SAP AI Core access
- Check model entitlements in tenant
For a complete error code reference, see API Reference - Error Handling.
v3.0.0 Breaking Change: SAPAIError removed. Use standard Vercel AI SDK
error types from @ai-sdk/provider.
For complete error handling examples with all error types and SAP-specific metadata fields, see API Reference - Error Handling.
Repository examples report error names, HTTP status and validated request IDs
without automatically printing backend messages. Raw error.message,
responseBody and nested transport diagnostics can contain credentials or prompt
data; inspect them privately and redact sensitive values before logging or sharing.
Common Causes: Invalid model parameters (temperature, maxTokens), malformed request, incompatible features
Solutions:
- Validate configuration against TypeScript types
- Check API Reference for valid parameter ranges
- Enable verbose SDK logging (
logLevel: 'debug'on the provider) for diagnostics; this does not guarantee the full request body is logged
Symptoms: HTTP 400 with error messages like:
"Unused parameters: [...]"- Template parsing errors when message content contains
{{,{%, or{#
Cause: SAP AI Core's orchestration API uses template syntax
({{variable}}, {{?variable}}, {% if %}, {# comment #}) for prompt templating. When tool results or
message content contains these patterns, the API incorrectly interprets them as template directives.
Solutions:
The escapeTemplatePlaceholders option is enabled by default,
which should prevent this issue. If you still encounter it, verify that you
haven't explicitly disabled escaping:
// Escaping is enabled by default - no configuration needed
const provider = createSAPAIProvider();
// If you need to disable escaping (e.g., to use SAP orchestration templating)
const provider = createSAPAIProvider({
defaultSettings: {
escapeTemplatePlaceholders: false, // Opt-out of automatic escaping
},
});How it works:
The option inserts a zero-width space (U+200B) between template opening delimiters
({{ becomes {\u200B{, {% becomes {\u200B%, {# becomes {\u200B#),
breaking the pattern while keeping content visually unchanged. JSON structures
with }} (closing braces) are preserved.
Manual escaping utilities:
import { escapeOrchestrationPlaceholders, unescapeOrchestrationPlaceholders } from "@jerome-benoit/sap-ai-provider";
const escaped = escapeOrchestrationPlaceholders("Use {{?question}} to prompt");
// Result: "Use {\u200B{?question}} to prompt"
const restored = unescapeOrchestrationPlaceholders(escaped);
// Result: "Use {{?question}} to prompt"Solutions:
- High-level AI SDK calls retry eligible errors with exponential backoff,
bounded by
maxRetries; direct provider calls do not retry automatically - Reduce request concurrency and honor service quota limits
- Cache reusable results and reduce
maxOutputTokens(or providermodelParams.maxTokens) where output-token quotas apply; streaming alone does not reduce request volume or token usage
Solutions:
- High-level AI SDK calls retry eligible errors with exponential backoff before a stream starts; handle failures after streaming begins in your app
- Check SAP AI Core service status
- Reduce request complexity: simplify prompts, remove optional features
Symptoms: "Model not found", "Deployment not found", HTTP 404,
NoSuchModelError or APICallError thrown depending on the error shape
Solutions:
-
Verify model availability in your SAP AI Core tenant/region (supported models)
-
Check resource group:
const provider = createSAPAIProvider({ resourceGroup: "default", // Must match deployment });
-
Verify deployment status: Ensure deployment is running, check deployment ID
-
Test with known model: Try
gpt-4.1- if it works, issue is model-specific
Example: "Tool calling not supported", "Streaming not available"
Solutions:
- Check the deployed model and SAP API support for the requested feature; see Model-Specific Tool Limitations for tool-calling references.
- Remove unsupported features or use alternatives (JSON mode instead of structured outputs)
Symptoms: UnsupportedFeatureError thrown at runtime with message like
"Content filtering is not supported with Foundation Models API"
Cause: Attempting to use features that are only available on one API with the other API:
- Orchestration-only features:
filtering,grounding,masking,translation,escapeTemplatePlaceholders - Foundation Models-only features:
dataSources(Azure OpenAI On Your Data)
Solutions:
-
Check which API you're using:
import { generateText } from "ai"; import { createSAPAIProvider, SAP_AI_PROVIDER_NAME } from "@jerome-benoit/sap-ai-provider"; // Provider-level (affects all models) const provider = createSAPAIProvider({ api: "orchestration" }); // default // Model-level (overrides provider) const model = provider("gpt-4.1", { api: "foundation-models" }); // Call-level (overrides model and provider) await generateText({ model, prompt: "Hello", providerOptions: { [SAP_AI_PROVIDER_NAME]: { api: "orchestration" } }, });
-
Match features to the correct API:
// ✅ Correct: Use filtering with Orchestration API (default) const provider = createSAPAIProvider({ defaultSettings: { filtering: { input: { filters: [...] } }, }, }); // ❌ Wrong: Using filtering with Foundation Models API const provider = createSAPAIProvider({ api: "foundation-models", defaultSettings: { filtering: { ... }, // Throws UnsupportedFeatureError! }, });
-
Handle the error gracefully:
import { UnsupportedFeatureError } from "@jerome-benoit/sap-ai-provider"; try { await generateText({ model, prompt: "Hello" }); } catch (error) { if (error instanceof UnsupportedFeatureError) { console.error("Feature:", error.feature); console.error("Current API:", error.api); console.error("Required API:", error.suggestedApi); } }
Reference: See API Reference - API Comparison for complete feature comparison.
Symptoms: ApiSwitchError thrown when calling generateText or streamText
with providerOptions that specify a different API than configured.
Cause: You're trying to switch APIs at call-time while using features that
require a specific API. For example, switching to foundation-models when
masking or filtering is configured (Orchestration-only features).
Solutions:
-
Create a provider/model without incompatible settings:
// Assume provider has masking configured in defaultSettings. // Switching the call API does not remove those model settings. const result = await generateText({ model: provider("gpt-4.1"), prompt: "Hello", providerOptions: { [SAP_AI_PROVIDER_NAME]: { api: "foundation-models", // Conflicts with provider-level masking }, }, }); // ✅ Correct: Create separate provider for foundation-models const fmProvider = createSAPAIProvider({ api: "foundation-models" }); const result = await generateText({ model: fmProvider("gpt-4.1"), prompt: "Hello", });
-
Handle the error gracefully:
import { ApiSwitchError } from "@jerome-benoit/sap-ai-provider"; try { await generateText({ model, prompt: "Hello", providerOptions: {...} }); } catch (error) { if (error instanceof ApiSwitchError) { console.error("Cannot switch to:", error.toApi); console.error("Reason:", error.message); // Consider creating a separate provider instance } }
Reference: See API Reference - Error Types for complete error details.
Architecture Details: For streaming implementation and SSE flow diagrams, see Architecture - Streaming Text Generation.
Symptoms: SAP returns 400 with "Streaming is not supported for this model",
or text generation works but tool calling reports that Responses is required.
Check the selected API and model deployment before disabling streaming. A model can support streaming through Responses even when an Orchestration or Chat Completions route rejects the request. For a Responses-capable Azure OpenAI deployment, select the API explicitly:
const provider = createSAPAIProvider({ api: "responses" });
const model = provider("gpt-6.1-sol", {
responses: { reasoningEffort: "low" },
});Use the model's supported reasoning levels; setting reasoning to none does
not replace Responses support and may itself be rejected. Keep Orchestration
modules and Foundation Models dataSources out of this model's settings.
See Responses API and run
npx tsx examples/example-responses.ts to exercise streaming and a tool round trip.
If an application such as OpenCode wraps this provider, verify that it forwards
api and model options to the provider. A configuration entry cannot change the
transport when the application's provider loader discards those options.
Symptoms: No chunks, stream ends early, chunks appear all at once
Solutions:
-
Iterate correctly:
import "dotenv/config"; // Load environment variables import { streamText } from "ai"; import { createSAPAIProvider } from "@jerome-benoit/sap-ai-provider"; const provider = createSAPAIProvider(); const result = streamText({ model: provider("gpt-4.1"), prompt: "Write a story", }); for await (const chunk of result.textStream) { process.stdout.write(chunk); }
-
Don't mix: Use
streamTextfor streaming,generateTextfor complete responses -
Check buffering: Set HTTP headers for streaming:
"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"
-
Handle errors: Use
onErrorfor generation and stream failures. IteratingtextStreamdoes not expose error parts, so a surroundingtry/catchalone can miss these failures.const result = streamText({ model: provider("gpt-4.1"), prompt: "Write a story", onError({ error }) { // Whole errors may contain response bodies or transport credentials. console.error("Stream error:", error instanceof Error ? error.name : "Unknown error"); }, }); for await (const chunk of result.textStream) { process.stdout.write(chunk); }
Symptoms: Model doesn't use tools, generates text instead
Solutions:
-
Improve descriptions: Be specific in tool descriptions and parameter descriptions
const weatherTool = tool({ description: "Get current weather for a specific location", inputSchema: z.object({ location: z.string().describe("City name, e.g., 'Tokyo'"), }), });
-
Make prompt explicit: "What's the weather in Tokyo? Use the weather tool to check."
-
Check compatibility: See Model-Specific Tool Limitations for supported models and restrictions.
Solutions:
- Validate arguments: Use schema validation before executing
- Handle errors gracefully: Wrap execute in try-catch, return
{ error: message } - Return structured data: JSON-serializable only, avoid complex objects
Solutions:
- Use
streamTextfor long outputs (faster perceived performance) - Limit output with AI SDK
maxOutputTokens(or providermodelParams.maxTokens) and choose a smaller model (gpt-4.1-mini) - Reduce prompt size: Concise history, remove unnecessary context, summarize periodically
Solutions:
- Set appropriate
maxOutputTokens(estimate actual response length) - Optimize prompts: Be concise, remove redundancy, use system messages effectively
- Monitor usage:
console.log(result.usage)
The SAP AI SDK may emit informational messages (e.g., service key usage notices). You can control the verbosity:
import { createSAPAIProvider } from "@jerome-benoit/sap-ai-provider";
const provider = createSAPAIProvider({
logLevel: "warn", // 'error' | 'warn' | 'info' | 'debug' (default: 'warn')
});export SAP_CLOUD_SDK_LOG_LEVEL=error # Suppress all but errorsLog levels:
error- Only critical errorswarn- Errors and warnings (default)info- Include informational messages (e.g., "Using service key for local testing")debug- Verbose SDK debugging
Note: The SAP_CLOUD_SDK_LOG_LEVEL environment variable takes precedence
over the logLevel provider option. Without that environment override, each
provider creation sets the process-wide SAP Cloud SDK log level, using warn
when logLevel is omitted. Logging is not isolated per provider instance.
See cURL API Testing Guide for comprehensive direct API testing.
Decode JWT token:
printf '%s\n' "$ACCESS_TOKEN" | jq -R 'split(".")[1] | gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson'Check: exp (expiration), subaccountid, scope. This decodes the
Base64URL payload for inspection; it does not verify the token signature.
Start simple, add features gradually:
import "dotenv/config"; // Load environment variables
import { generateText } from "ai";
import { createSAPAIProvider } from "@jerome-benoit/sap-ai-provider";
const provider = createSAPAIProvider();
const result = await generateText({
model: provider("gpt-4.1"),
prompt: "Hello",
});
console.log(result.text);import "dotenv/config"; // Load environment variables
console.log("Node:", process.version);
console.log("Service key set:", !!process.env.AICORE_SERVICE_KEY);
const key = JSON.parse(process.env.AICORE_SERVICE_KEY || "{}");
console.log("OAuth URL:", key.url);
console.log("AI API URL:", key.serviceurls?.AI_API_URL);If issues persist:
-
Check documentation: README, API Reference, Environment Setup
-
Review examples: Compare your code with
examples/directory -
Open an issue: GitHub Issues - Include error messages, code snippets (redact credentials)
-
SAP Support: For SAP AI Core service issues - SAP AI Core Docs
Symptoms: TooManyEmbeddingValuesForCallError from a direct
embeddingModel.doEmbed({ values }) call exceeding the configured limit.
Cause: Direct provider calls do not split input arrays. The provider defaults
to 2048 values per call for every model; this is configurable with the model's
maxEmbeddingsPerCall setting, not discovered from SAP model capabilities.
Choose a value supported by your deployment.
Solutions:
-
Configure the per-call limit:
const embeddingModel = provider.embedding("text-embedding-3-small", { maxEmbeddingsPerCall: 128, // Example limit; match your deployment }); console.log("Max per call:", embeddingModel.maxEmbeddingsPerCall);
-
Use automatic batching in the high-level API:
import { embedMany } from "ai"; const { embeddings } = await embedMany({ model: embeddingModel, values: largeArray, maxParallelCalls: 1, // Bound concurrency independently of batch size });
embedMany()splits values according tomaxEmbeddingsPerCalland returns embeddings in input order. Manual batching around it is not required.embed()submits one value. -
If calling
doEmbed()directly, split inputs into batches no larger thanembeddingModel.maxEmbeddingsPerCall, or handleTooManyEmbeddingValuesForCallErrorand retry with smaller batches.
Reference: See API Reference - Embeddings for embedding model configuration.
Symptoms: Calls to provider.embedding() or provider.embeddingModel() fail with V2.
Cause: V2 only exposes textEmbeddingModel() per the ProviderV2 spec.
Solution: Use provider.textEmbeddingModel(), or use the V3 root (or its
/v3 subpath) with AI SDK 6 / V4 subpath with AI SDK 7.
Reference: Architecture - Versioned Packages
Symptoms: TypeScript errors related to LanguageModelV2 or EmbeddingModelV2 types when using @jerome-benoit/sap-ai-provider-v2.
Cause: The selected provider specification does not match the installed AI SDK major. V2 targets AI SDK 5 and is also supported by AI SDK 6 through its V2 compatibility layer, but not by AI SDK 7.
Solution: Use /v2 or the standalone -v2 package with AI SDK 5; use the
V3 root or identical /v3 subpath, or V2 compatibility, with
AI SDK 6; use /v4 with AI SDK 7. See Installation
for matching install commands.
Reference: Check package.json for AI SDK version. See the Migration Guide for V2/V3 compatibility.
Symptoms: A successful embedding request is followed by a TypeError when
the SDK reads warnings.length.
Cause: AI SDK 6.0.0 does not default the optional warnings absent from the V2 embedding contract. This is an SDK consumer bug, not a SAP transport failure.
Solution: Upgrade to a current AI SDK 6 patch (verified with 6.0.282), or use
the V3 root or /v3 entrypoint. No V2-specific provider workaround is required.
Symptoms: npm run prepare:v2 fails with ENOENT because dist/ does not exist.
Cause: The prepare:v2 script requires the build:v2 script to be run first.
Solution: For local V2 build checks, run npm run build:v2 then
npm run check-build:v2. For standalone publication, run
AI_SDK_VERSION=v2 npm publish from a separate clean checkout: the lifecycle
builds and prepares V2, then verifies the prepared exports. Do not manually run
prepare:v2 before publishing; it rewrites the package manifests.
Reference: See Architecture - Build Process.
This section documents known limitations of the SAP AI Provider that are either inherent to the underlying SAP AI SDK or are planned for future resolution.
Behavior: The response-metadata.id in streaming responses is extracted
from the server's completion response when available, with a client-side UUID
fallback. The x-request-id header is exposed via providerMetadata for
server-side log correlation in both streaming and non-streaming responses.
Reference: See API Reference - Provider Metadata for field details and examples.
- README - Getting started
- API Reference - Complete API reference
- Environment Setup - Authentication setup
- Architecture - Internal architecture
- cURL API Testing Guide - Direct API testing