Skip to content

Latest commit

 

History

History
759 lines (557 loc) · 27.5 KB

TROUBLESHOOTING.md

File metadata and controls

759 lines (557 loc) · 27.5 KB

Troubleshooting Guide

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.

Quick Reference

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

Common Problems (Top 5)

Quick solutions for the most frequent issues:

  1. 🔴 401 Unauthorized

  2. 🟠 404 Model Not Found

  3. 🟡 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
  4. 🟢 Streaming Not Working

  5. 🔵 Tools Not Being Called

For other issues, see the detailed Table of Contents below.

Table of Contents

Authentication Issues

Problem: "Authentication failed" or 401 errors

Symptoms: HTTP 401, "Invalid token", authentication fails when making a request, LoadAPIKeyError or APICallError thrown depending on the error shape

Solutions:

  1. Verify AICORE_SERVICE_KEY environment variable is set and contains valid JSON
  2. → Complete setup guide: Environment Setup Guide

Problem: "Cannot find module 'dotenv'"

Solution: npm install dotenv and add import "dotenv/config"; at top of entry file

Problem: 403 Forbidden

Symptoms: HTTP 403, "Insufficient permissions"

Solutions:

  1. Verify service key has necessary permissions
  2. Check AI-Resource-Group header matches deployment
  3. Confirm SAP BTP account has SAP AI Core access
  4. Check model entitlements in tenant

API Errors

For a complete error code reference, see API Reference - Error Handling.

Parsing SAP Error Metadata (v3.0.0+)

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.

Problem: 400 Bad Request

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

Problem: Template Placeholder Conflicts

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"

Problem: 429 Rate Limit Exceeded

Solutions:

  1. High-level AI SDK calls retry eligible errors with exponential backoff, bounded by maxRetries; direct provider calls do not retry automatically
  2. Reduce request concurrency and honor service quota limits
  3. Cache reusable results and reduce maxOutputTokens (or provider modelParams.maxTokens) where output-token quotas apply; streaming alone does not reduce request volume or token usage

Problem: 500/502/503/504 Server Errors

Solutions:

  1. High-level AI SDK calls retry eligible errors with exponential backoff before a stream starts; handle failures after streaming begins in your app
  2. Check SAP AI Core service status
  3. Reduce request complexity: simplify prompts, remove optional features

Model and Deployment Issues

Problem: 404 Model/Deployment Not Found

Symptoms: "Model not found", "Deployment not found", HTTP 404, NoSuchModelError or APICallError thrown depending on the error shape

Solutions:

  1. Verify model availability in your SAP AI Core tenant/region (supported models)

  2. Check resource group:

    const provider = createSAPAIProvider({
      resourceGroup: "default", // Must match deployment
    });
  3. Verify deployment status: Ensure deployment is running, check deployment ID

  4. Test with known model: Try gpt-4.1 - if it works, issue is model-specific

Problem: Model doesn't support features

Example: "Tool calling not supported", "Streaming not available"

Solutions:

  1. Check the deployed model and SAP API support for the requested feature; see Model-Specific Tool Limitations for tool-calling references.
  2. Remove unsupported features or use alternatives (JSON mode instead of structured outputs)

Problem: API-specific feature mismatch (UnsupportedFeatureError)

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:

  1. 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" } },
    });
  2. 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!
      },
    });
  3. 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.

Problem: API switch conflict (ApiSwitchError)

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:

  1. 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",
    });
  2. 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.

Streaming Issues

Architecture Details: For streaming implementation and SSE flow diagrams, see Architecture - Streaming Text Generation.

Problem: Model requires Responses

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.

Problem: Streaming not working or incomplete

Symptoms: No chunks, stream ends early, chunks appear all at once

Solutions:

  1. 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);
    }
  2. Don't mix: Use streamText for streaming, generateText for complete responses

  3. Check buffering: Set HTTP headers for streaming:

    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive"
  4. Handle errors: Use onError for generation and stream failures. Iterating textStream does not expose error parts, so a surrounding try/catch alone 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);
    }

Tool Calling Issues

Problem: Tools not being called

Symptoms: Model doesn't use tools, generates text instead

Solutions:

  1. 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'"),
      }),
    });
  2. Make prompt explicit: "What's the weather in Tokyo? Use the weather tool to check."

  3. Check compatibility: See Model-Specific Tool Limitations for supported models and restrictions.

Problem: Tool execution errors

Solutions:

  1. Validate arguments: Use schema validation before executing
  2. Handle errors gracefully: Wrap execute in try-catch, return { error: message }
  3. Return structured data: JSON-serializable only, avoid complex objects

Performance Issues

Problem: Slow response times

Solutions:

  1. Use streamText for long outputs (faster perceived performance)
  2. Limit output with AI SDK maxOutputTokens (or provider modelParams.maxTokens) and choose a smaller model (gpt-4.1-mini)
  3. Reduce prompt size: Concise history, remove unnecessary context, summarize periodically

Problem: High token usage / costs

Solutions:

  1. Set appropriate maxOutputTokens (estimate actual response length)
  2. Optimize prompts: Be concise, remove redundancy, use system messages effectively
  3. Monitor usage: console.log(result.usage)

Debugging Tools

Control SAP Cloud SDK Log Level

The SAP AI SDK may emit informational messages (e.g., service key usage notices). You can control the verbosity:

Option 1: Via provider configuration (recommended)

import { createSAPAIProvider } from "@jerome-benoit/sap-ai-provider";

const provider = createSAPAIProvider({
  logLevel: "warn", // 'error' | 'warn' | 'info' | 'debug' (default: 'warn')
});

Option 2: Via environment variable

export SAP_CLOUD_SDK_LOG_LEVEL=error  # Suppress all but errors

Log levels:

  • error - Only critical errors
  • warn - 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.

Use cURL for Direct API Testing

See cURL API Testing Guide for comprehensive direct API testing.

Check Token Validity

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.

Test with Minimal Request

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);

Verify Configuration

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);

Getting Help

If issues persist:

  1. Check documentation: README, API Reference, Environment Setup

  2. Review examples: Compare your code with examples/ directory

  3. Open an issue: GitHub Issues - Include error messages, code snippets (redact credentials)

  4. SAP Support: For SAP AI Core service issues - SAP AI Core Docs

Embedding Issues

Problem: Too many embedding values (TooManyEmbeddingValuesForCallError)

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:

  1. 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);
  2. 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 to maxEmbeddingsPerCall and returns embeddings in input order. Manual batching around it is not required. embed() submits one value.

  3. If calling doEmbed() directly, split inputs into batches no larger than embeddingModel.maxEmbeddingsPerCall, or handle TooManyEmbeddingValuesForCallError and retry with smaller batches.

Reference: See API Reference - Embeddings for embedding model configuration.

V2 Facade Package Issues

Problem: Method not found on provider

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

Problem: Type mismatch with AI SDK

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.

Problem: V2 embeddings fail with AI SDK 6.0.0

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.

Problem: Missing build directory during V2 preparation

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.

Known Limitations

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.

Streaming Response ID Source

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.

Related Documentation