import {
  escapeOrchestrationPlaceholders,
  unescapeOrchestrationPlaceholders
} from "./chunk-QO36FSA3.js";
import {
  ApiSwitchError,
  SAP_AI_PROVIDER_NAME,
  UnsupportedFeatureError,
  VERSION,
  __toESM,
  deepMerge,
  getProviderName,
  require_dist,
  sapAIEmbeddingProviderOptions,
  sapAILanguageModelProviderOptions,
  validateEmbeddingModelParamsSettings,
  validateModelParamsSettings
} from "./chunk-6RYKBAYB.js";

// src/sap-ai-embedding-model.ts
import { parseProviderOptions } from "@ai-sdk/provider-utils";

// src/sap-ai-strategy.ts
var languageModelStrategyCache = /* @__PURE__ */ new Map();
var embeddingModelStrategyCache = /* @__PURE__ */ new Map();
function getOrCreateEmbeddingModelStrategy(api) {
  const cached = embeddingModelStrategyCache.get(api);
  if (cached) {
    return cached;
  }
  const strategyPromise = createEmbeddingModelStrategy(api);
  embeddingModelStrategyCache.set(api, strategyPromise);
  strategyPromise.catch(() => {
    embeddingModelStrategyCache.delete(api);
  });
  return strategyPromise;
}
function getOrCreateLanguageModelStrategy(api) {
  const cached = languageModelStrategyCache.get(api);
  if (cached) {
    return cached;
  }
  const strategyPromise = createLanguageModelStrategy(api);
  languageModelStrategyCache.set(api, strategyPromise);
  strategyPromise.catch(() => {
    languageModelStrategyCache.delete(api);
  });
  return strategyPromise;
}
async function createEmbeddingModelStrategy(api) {
  if (api === "foundation-models") {
    const { AzureOpenAiEmbeddingClient } = await import("@sap-ai-sdk/foundation-models");
    const { FoundationModelsEmbeddingModelStrategy } = await import("./foundation-models-embedding-model-strategy-HXF3JQP5.js");
    return new FoundationModelsEmbeddingModelStrategy(AzureOpenAiEmbeddingClient);
  }
  const { OrchestrationEmbeddingClient: OrchestrationEmbeddingClient2 } = await import("@sap-ai-sdk/orchestration");
  const { OrchestrationEmbeddingModelStrategy } = await import("./orchestration-embedding-model-strategy-RHNYULEI.js");
  return new OrchestrationEmbeddingModelStrategy(OrchestrationEmbeddingClient2);
}
async function createLanguageModelStrategy(api) {
  if (api === "foundation-models") {
    const { AzureOpenAiChatClient } = await import("@sap-ai-sdk/foundation-models");
    const { FoundationModelsLanguageModelStrategy } = await import("./foundation-models-language-model-strategy-U47ATXIF.js");
    return new FoundationModelsLanguageModelStrategy(AzureOpenAiChatClient);
  }
  const { OrchestrationClient: OrchestrationClient2 } = await import("@sap-ai-sdk/orchestration");
  const { OrchestrationLanguageModelStrategy } = await import("./orchestration-language-model-strategy-7W4CC2NK.js");
  return new OrchestrationLanguageModelStrategy(OrchestrationClient2);
}

// src/sap-ai-validation.ts
function validateEscapeTemplatePlaceholders(api, escapeTemplatePlaceholders) {
  if (api === "foundation-models" && escapeTemplatePlaceholders === true) {
    throw new UnsupportedFeatureError(
      "escapeTemplatePlaceholders (Jinja2 template escaping)",
      "foundation-models",
      "orchestration"
    );
  }
}
function validateFoundationModelsOnlyOptions(settings) {
  if (!settings) return;
  const fmSettings = settings;
  if (fmSettings.dataSources !== void 0) {
    throw new UnsupportedFeatureError(
      "Azure On Your Data (dataSources)",
      "orchestration",
      "foundation-models"
    );
  }
}
function validateOrchestrationOnlyOptions(settings) {
  if (!settings) return;
  const orchSettings = settings;
  if (orchSettings.filtering !== void 0) {
    throw new UnsupportedFeatureError("Content filtering", "foundation-models", "orchestration");
  }
  if (orchSettings.grounding !== void 0) {
    throw new UnsupportedFeatureError("Document grounding", "foundation-models", "orchestration");
  }
  if (orchSettings.masking !== void 0) {
    throw new UnsupportedFeatureError("Data masking", "foundation-models", "orchestration");
  }
  if (orchSettings.translation !== void 0) {
    throw new UnsupportedFeatureError("Translation", "foundation-models", "orchestration");
  }
  if (orchSettings.tools !== void 0) {
    throw new UnsupportedFeatureError(
      "SAP-format tool definitions (use AI SDK tools instead)",
      "foundation-models",
      "orchestration"
    );
  }
}
var ORCHESTRATION_ONLY_FEATURES = [
  "filtering",
  "grounding",
  "masking",
  "translation",
  "tools"
];
var FOUNDATION_MODELS_ONLY_FEATURES = ["dataSources"];
function validateApiSwitch(fromApi, toApi, modelSettings) {
  if (fromApi === toApi) return;
  if (!modelSettings) return;
  if (fromApi === "orchestration" && toApi === "foundation-models") {
    const orchSettings = modelSettings;
    for (const feature of ORCHESTRATION_ONLY_FEATURES) {
      if (orchSettings[feature] !== void 0) {
        throw new ApiSwitchError(fromApi, toApi, feature);
      }
    }
  }
  if (fromApi === "foundation-models" && toApi === "orchestration") {
    const fmSettings = modelSettings;
    for (const feature of FOUNDATION_MODELS_ONLY_FEATURES) {
      if (fmSettings[feature] !== void 0) {
        throw new ApiSwitchError(fromApi, toApi, feature);
      }
    }
  }
}
var VALID_API_TYPES = ["orchestration", "foundation-models"];
function resolveApi(providerApi, modelApi, invocationApi) {
  return invocationApi ?? modelApi ?? providerApi ?? "orchestration";
}
function validateApiInput(api) {
  if (api === void 0) return;
  if (typeof api !== "string" || !VALID_API_TYPES.includes(api)) {
    throw new Error(
      `Invalid API type: ${JSON.stringify(api)}. Valid values are: ${VALID_API_TYPES.map((t) => `"${t}"`).join(", ")}`
    );
  }
}
function validateSettings(options) {
  const { api, invocationSettings, modelApi, modelSettings } = options;
  validateApiInput(api);
  if (invocationSettings?.api !== void 0) {
    validateApiInput(invocationSettings.api);
  }
  if (invocationSettings?.api !== void 0) {
    const effectiveModelApi = modelApi ?? "orchestration";
    if (effectiveModelApi !== invocationSettings.api) {
      validateApiSwitch(effectiveModelApi, invocationSettings.api, modelSettings);
    }
  }
  if (api === "foundation-models") {
    validateOrchestrationOnlyOptions(modelSettings);
  } else {
    validateFoundationModelsOnlyOptions(modelSettings);
  }
  const modelEscape = modelSettings?.escapeTemplatePlaceholders;
  const invocationEscape = invocationSettings?.escapeTemplatePlaceholders;
  const effectiveEscape = invocationEscape ?? modelEscape;
  validateEscapeTemplatePlaceholders(api, effectiveEscape);
}

// src/sap-ai-embedding-model.ts
var DEFAULT_MAX_EMBEDDINGS_PER_CALL = 2048;
var SAPAIEmbeddingModel = class {
  /** Maximum number of embeddings per API call. */
  maxEmbeddingsPerCall;
  /** The model identifier. */
  modelId;
  /** The provider identifier string. */
  provider;
  /** The Vercel AI SDK specification version. */
  specificationVersion = "v3";
  /** Whether the model supports parallel API calls. */
  supportsParallelCalls = true;
  config;
  settings;
  /**
   * Creates a new SAP AI Embedding Model instance.
   *
   * This is the main implementation that handles all SAP AI Core embedding logic.
   * @param modelId - The model identifier (e.g., 'text-embedding-ada-002', 'text-embedding-3-small').
   * @param settings - Model configuration settings (embedding type, model parameters, etc.).
   * @param config - SAP AI Core deployment and destination configuration.
   */
  constructor(modelId, settings = {}, config) {
    if (settings.modelParams) {
      validateEmbeddingModelParamsSettings(settings.modelParams);
    }
    this.modelId = modelId;
    this.settings = settings;
    this.config = config;
    this.provider = config.provider;
    this.maxEmbeddingsPerCall = settings.maxEmbeddingsPerCall ?? DEFAULT_MAX_EMBEDDINGS_PER_CALL;
  }
  /**
   * Generates embeddings for the given input values.
   *
   * Implements late-binding: resolves API at invocation time, validates settings,
   * gets the appropriate strategy, and delegates the call.
   * @param options - The Vercel AI SDK V3 embedding call options.
   * @returns The embedding result with vectors, usage data, and warnings.
   */
  async doEmbed(options) {
    const providerName = getProviderName(this.config.provider);
    const sapOptions = await parseProviderOptions({
      provider: providerName,
      providerOptions: options.providerOptions,
      schema: sapAIEmbeddingProviderOptions
    });
    const effectiveApi = resolveApi(this.config.providerApi, this.settings.api, sapOptions?.api);
    validateSettings({
      api: effectiveApi,
      invocationSettings: sapOptions ? { api: sapOptions.api } : void 0,
      modelApi: this.settings.api,
      modelSettings: this.settings.api ? { api: this.settings.api } : void 0
    });
    const strategy = await getOrCreateEmbeddingModelStrategy(effectiveApi);
    const strategyConfig = {
      deploymentConfig: this.config.deploymentConfig,
      destination: this.config.destination,
      modelId: this.modelId,
      provider: this.config.provider
    };
    return strategy.doEmbed(strategyConfig, this.settings, options, this.maxEmbeddingsPerCall);
  }
};

// src/sap-ai-language-model.ts
import { parseProviderOptions as parseProviderOptions2 } from "@ai-sdk/provider-utils";
var SAPAILanguageModel = class {
  /** The model identifier. */
  modelId;
  /** The Vercel AI SDK specification version. */
  specificationVersion = "v3";
  /** Whether the model supports image URLs in prompts. */
  supportsImageUrls = true;
  /** Whether the model supports generating multiple completions. */
  supportsMultipleCompletions = true;
  /** Whether the model supports parallel tool calls. */
  supportsParallelToolCalls = true;
  /** Whether the model supports streaming responses. */
  supportsStreaming = true;
  /** Whether the model supports structured JSON outputs. */
  supportsStructuredOutputs = true;
  /** Whether the model supports tool/function calling. */
  supportsToolCalls = true;
  /**
   * Gets the provider identifier string.
   * @returns The provider identifier.
   */
  get provider() {
    return this.config.provider;
  }
  /**
   * Gets the supported URL patterns for image input.
   * @returns A mapping of MIME type patterns to URL regex patterns.
   */
  get supportedUrls() {
    return {
      "image/*": [/^https:\/\/.+$/i, /^data:image\/.*$/]
    };
  }
  /** @internal */
  config;
  /** @internal */
  settings;
  /**
   * Creates a new SAP AI Language Model instance.
   *
   * This is the main implementation that handles all SAP AI Core orchestration logic.
   * @param modelId - The model identifier (e.g., 'gpt-4o', 'claude-3-5-sonnet', 'gemini-2.0-flash').
   * @param settings - Model configuration settings (temperature, max tokens, filtering, etc.).
   * @param config - SAP AI Core deployment and destination configuration.
   * @internal
   */
  constructor(modelId, settings, config) {
    if (settings.modelParams) {
      validateModelParamsSettings(settings.modelParams);
    }
    this.settings = settings;
    this.config = config;
    this.modelId = modelId;
  }
  /**
   * Generates a single completion (non-streaming).
   *
   * Implements late-binding: resolves API at invocation time, validates settings,
   * gets the appropriate strategy, and delegates the call.
   * Supports request cancellation via AbortSignal at the HTTP transport layer.
   * @param options - The Vercel AI SDK V3 generation call options.
   * @returns The generation result with content, usage, warnings, and provider metadata.
   */
  async doGenerate(options) {
    const providerName = getProviderName(this.config.provider);
    const sapOptions = await parseProviderOptions2({
      provider: providerName,
      providerOptions: options.providerOptions,
      schema: sapAILanguageModelProviderOptions
    });
    const effectiveApi = resolveApi(this.config.providerApi, this.settings.api, sapOptions?.api);
    validateSettings({
      api: effectiveApi,
      invocationSettings: sapOptions ? { api: sapOptions.api, escapeTemplatePlaceholders: sapOptions.escapeTemplatePlaceholders } : void 0,
      modelApi: this.settings.api,
      modelSettings: this.settings
    });
    const strategy = await getOrCreateLanguageModelStrategy(effectiveApi);
    const strategyConfig = {
      deploymentConfig: this.config.deploymentConfig,
      destination: this.config.destination,
      modelId: this.modelId,
      provider: this.config.provider
    };
    return strategy.doGenerate(strategyConfig, this.settings, options);
  }
  /**
   * Generates a streaming completion.
   *
   * Implements late-binding: resolves API at invocation time, validates settings,
   * gets the appropriate strategy, and delegates the call.
   * Supports request cancellation via AbortSignal at the HTTP transport layer.
   * @param options - The Vercel AI SDK V3 generation call options.
   * @returns A stream result with async iterable stream parts.
   */
  async doStream(options) {
    const providerName = getProviderName(this.config.provider);
    const sapOptions = await parseProviderOptions2({
      provider: providerName,
      providerOptions: options.providerOptions,
      schema: sapAILanguageModelProviderOptions
    });
    const effectiveApi = resolveApi(this.config.providerApi, this.settings.api, sapOptions?.api);
    validateSettings({
      api: effectiveApi,
      invocationSettings: sapOptions ? { api: sapOptions.api, escapeTemplatePlaceholders: sapOptions.escapeTemplatePlaceholders } : void 0,
      modelApi: this.settings.api,
      modelSettings: this.settings
    });
    const strategy = await getOrCreateLanguageModelStrategy(effectiveApi);
    const strategyConfig = {
      deploymentConfig: this.config.deploymentConfig,
      destination: this.config.destination,
      modelId: this.modelId,
      provider: this.config.provider
    };
    return strategy.doStream(strategyConfig, this.settings, options);
  }
  /**
   * Checks if a URL is supported for image input (HTTPS or data:image/*).
   * @param url - The URL to check.
   * @returns True if the URL is supported for image input.
   */
  supportsUrl(url) {
    if (url.protocol === "https:") return true;
    if (url.protocol === "data:") {
      return /^data:image\//i.test(url.href);
    }
    return false;
  }
};

// src/sap-ai-provider.ts
var import_util = __toESM(require_dist(), 1);
import { NoSuchModelError } from "@ai-sdk/provider";
function createSAPAIProvider(options = {}) {
  if (options.defaultSettings?.modelParams) {
    validateModelParamsSettings(options.defaultSettings.modelParams);
  }
  const providerName = options.name ?? SAP_AI_PROVIDER_NAME;
  const resourceGroup = options.resourceGroup ?? "default";
  const warnOnAmbiguousConfig = options.warnOnAmbiguousConfig ?? true;
  if (warnOnAmbiguousConfig && options.deploymentId && options.resourceGroup) {
    console.warn(
      "createSAPAIProvider: both 'deploymentId' and 'resourceGroup' were provided; using 'deploymentId' and ignoring 'resourceGroup'."
    );
  }
  if (!process.env.SAP_CLOUD_SDK_LOG_LEVEL) {
    const logLevel = options.logLevel ?? "warn";
    (0, import_util.setGlobalLogLevel)(logLevel);
  }
  const providerApi = options.api ?? "orchestration";
  const deploymentConfig = options.deploymentId ? { deploymentId: options.deploymentId } : { resourceGroup };
  const createModel = (modelId, settings = {}) => {
    const mergedSettings = {
      ...options.defaultSettings,
      ...settings,
      // Model-level api takes precedence over provider-level
      api: settings.api ?? options.defaultSettings?.api ?? providerApi,
      filtering: settings.filtering ?? options.defaultSettings?.filtering,
      masking: settings.masking ?? options.defaultSettings?.masking,
      modelParams: deepMerge(
        options.defaultSettings?.modelParams ?? {},
        settings.modelParams ?? {}
      ),
      tools: settings.tools ?? options.defaultSettings?.tools
    };
    return new SAPAILanguageModel(modelId, mergedSettings, {
      deploymentConfig,
      destination: options.destination,
      provider: `${providerName}.chat`,
      providerApi
    });
  };
  const createEmbeddingModel = (modelId, settings = {}) => {
    const mergedSettings = {
      ...settings,
      api: settings.api ?? providerApi
    };
    return new SAPAIEmbeddingModel(modelId, mergedSettings, {
      deploymentConfig,
      destination: options.destination,
      provider: `${providerName}.embedding`,
      providerApi
    });
  };
  const provider = function(modelId, settings) {
    if (new.target) {
      throw new Error("The SAP AI provider function cannot be called with the new keyword.");
    }
    return createModel(modelId, settings);
  };
  provider.specificationVersion = "v3";
  provider.chat = createModel;
  provider.languageModel = createModel;
  provider.embedding = createEmbeddingModel;
  provider.textEmbeddingModel = createEmbeddingModel;
  provider.embeddingModel = createEmbeddingModel;
  provider.imageModel = (modelId) => {
    throw new NoSuchModelError({
      message: `SAP AI Core does not support image generation. Model '${modelId}' is not available.`,
      modelId,
      modelType: "imageModel"
    });
  };
  return provider;
}
var sapai = createSAPAIProvider();

// src/sap-ai-settings.ts
import {
  buildAzureContentSafetyFilter,
  buildDocumentGroundingConfig,
  buildDpiMaskingProvider,
  buildLlamaGuard38BFilter,
  buildTranslationConfig
} from "@sap-ai-sdk/orchestration";
import {
  OrchestrationEmbeddingResponse,
  OrchestrationResponse,
  OrchestrationStream,
  OrchestrationStreamChunkResponse,
  OrchestrationStreamResponse
} from "@sap-ai-sdk/orchestration";

// src/index.ts
import { OrchestrationClient, OrchestrationEmbeddingClient } from "@sap-ai-sdk/orchestration";
export {
  ApiSwitchError,
  OrchestrationClient,
  OrchestrationEmbeddingClient,
  OrchestrationEmbeddingResponse,
  OrchestrationResponse,
  OrchestrationStream,
  OrchestrationStreamChunkResponse,
  OrchestrationStreamResponse,
  SAPAIEmbeddingModel,
  SAPAILanguageModel,
  SAP_AI_PROVIDER_NAME,
  UnsupportedFeatureError,
  VERSION,
  buildAzureContentSafetyFilter,
  buildDocumentGroundingConfig,
  buildDpiMaskingProvider,
  buildLlamaGuard38BFilter,
  buildTranslationConfig,
  createSAPAIProvider,
  escapeOrchestrationPlaceholders,
  getProviderName,
  resolveApi,
  sapAIEmbeddingProviderOptions,
  sapAILanguageModelProviderOptions,
  sapai,
  unescapeOrchestrationPlaceholders,
  validateSettings
};
//# sourceMappingURL=index.js.map