import {
  escapeOrchestrationPlaceholders,
  unescapeOrchestrationPlaceholders
} from "./chunk-G2BVB5LB.js";
import {
  ApiSwitchError,
  SAP_AI_PROVIDER_NAME,
  UnsupportedFeatureError,
  VERSION,
  __toESM,
  deepMerge,
  getProviderName,
  require_dist,
  sapAIEmbeddingProviderOptions,
  sapAILanguageModelProviderOptions,
  validateEmbeddingModelParamsSettings,
  validateModelParamsSettings
} from "./chunk-7VLWN7WJ.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-OTU7URXF.js");
    return new FoundationModelsEmbeddingModelStrategy(AzureOpenAiEmbeddingClient);
  }
  const { OrchestrationEmbeddingClient: OrchestrationEmbeddingClient2 } = await import("@sap-ai-sdk/orchestration");
  const { OrchestrationEmbeddingModelStrategy } = await import("./orchestration-embedding-model-strategy-AGED2P35.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-KVEFWA62.js");
    return new FoundationModelsLanguageModelStrategy(AzureOpenAiChatClient);
  }
  const { OrchestrationClient: OrchestrationClient2 } = await import("@sap-ai-sdk/orchestration");
  const { OrchestrationLanguageModelStrategy } = await import("./orchestration-language-model-strategy-QN56X3Z2.js");
  return new OrchestrationLanguageModelStrategy(OrchestrationClient2);
}

// src/sap-ai-validation.ts
function validateEscapeTemplatePlaceholders(api, escapeTemplatePlaceholders) {
  if (api === "foundation-models" && escapeTemplatePlaceholders === true) {
    throw new UnsupportedFeatureError(
      ESCAPE_TEMPLATE_PLACEHOLDERS_DESCRIPTION,
      "foundation-models",
      "orchestration"
    );
  }
}
function validateFoundationModelsOnlyOptions(settings) {
  if (!settings) return;
  const fmSettings = settings;
  for (const feature of FOUNDATION_MODELS_ONLY_FEATURE_KEYS) {
    if (fmSettings[feature] !== void 0) {
      throw new UnsupportedFeatureError(
        FOUNDATION_MODELS_ONLY_FEATURES[feature],
        "orchestration",
        "foundation-models"
      );
    }
  }
}
function validateOrchestrationOnlyEmbeddingOptions(settings) {
  if (!settings) return;
  for (const feature of ORCHESTRATION_ONLY_EMBEDDING_FEATURE_KEYS) {
    if (settings[feature] !== void 0) {
      throw new UnsupportedFeatureError(
        ORCHESTRATION_ONLY_EMBEDDING_FEATURES[feature],
        "foundation-models",
        "orchestration"
      );
    }
  }
}
function validateOrchestrationOnlyOptions(settings) {
  if (!settings) return;
  const orchSettings = settings;
  for (const feature of ORCHESTRATION_ONLY_FEATURE_KEYS) {
    if (orchSettings[feature] !== void 0) {
      throw new UnsupportedFeatureError(
        ORCHESTRATION_ONLY_FEATURES[feature],
        "foundation-models",
        "orchestration"
      );
    }
  }
}
var ORCHESTRATION_ONLY_FEATURE_KEYS = [
  "filtering",
  "grounding",
  "masking",
  "orchestrationConfigRef",
  "placeholderValues",
  "promptTemplateRef",
  "tools",
  "translation"
];
var ORCHESTRATION_ONLY_FEATURES = {
  filtering: "Content filtering",
  grounding: "Document grounding",
  masking: "Data masking",
  orchestrationConfigRef: "Orchestration config reference (orchestrationConfigRef)",
  placeholderValues: "Placeholder values (placeholderValues)",
  promptTemplateRef: "Prompt template reference (promptTemplateRef)",
  tools: "SAP-format tool definitions (use AI SDK tools instead)",
  translation: "Translation"
};
var FOUNDATION_MODELS_ONLY_FEATURE_KEYS = ["dataSources"];
var FOUNDATION_MODELS_ONLY_FEATURES = {
  dataSources: "Azure On Your Data (dataSources)"
};
var ORCHESTRATION_ONLY_INVOCATION_FEATURE_KEYS = [
  "orchestrationConfigRef",
  "placeholderValues",
  "promptTemplateRef"
];
var ORCHESTRATION_ONLY_EMBEDDING_FEATURE_KEYS = ["masking"];
var ORCHESTRATION_ONLY_EMBEDDING_FEATURES = {
  masking: ORCHESTRATION_ONLY_FEATURES.masking
};
var ESCAPE_TEMPLATE_PLACEHOLDERS_DESCRIPTION = "escapeTemplatePlaceholders (Jinja2 template escaping)";
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_FEATURE_KEYS) {
      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_FEATURE_KEYS) {
      if (fmSettings[feature] !== void 0) {
        throw new ApiSwitchError(fromApi, toApi, feature);
      }
    }
  }
}
var VALID_API_TYPES = ["orchestration", "foundation-models"];
function mergeSettingsWithApi(defaultSettings, callSettings, fallbackApi) {
  return {
    ...deepMerge(defaultSettings, callSettings),
    api: callSettings.api ?? defaultSettings?.api ?? fallbackApi
  };
}
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, embeddingSettings, 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);
    validateOrchestrationOnlyInvocationOptions(invocationSettings);
    validateOrchestrationOnlyEmbeddingOptions(embeddingSettings);
  } else {
    validateFoundationModelsOnlyOptions(modelSettings);
  }
  const modelEscape = modelSettings?.escapeTemplatePlaceholders;
  const invocationEscape = invocationSettings?.escapeTemplatePlaceholders;
  const effectiveEscape = invocationEscape ?? modelEscape;
  validateEscapeTemplatePlaceholders(api, effectiveEscape);
}
function validateOrchestrationOnlyInvocationOptions(invocationSettings) {
  if (!invocationSettings) return;
  for (const feature of ORCHESTRATION_ONLY_INVOCATION_FEATURE_KEYS) {
    if (invocationSettings[feature] !== void 0) {
      throw new UnsupportedFeatureError(
        ORCHESTRATION_ONLY_FEATURES[feature],
        "foundation-models",
        "orchestration"
      );
    }
  }
}

// src/sap-ai-embedding-model.ts
var DEFAULT_MAX_EMBEDDINGS_PER_CALL = 2048;
var SAPAIEmbeddingModel = class {
  maxEmbeddingsPerCall;
  modelId;
  provider;
  specificationVersion = "v3";
  supportsParallelCalls = true;
  config;
  settings;
  /**
   * @param modelId - Model identifier.
   * @param settings - Model settings.
   * @param config - Model configuration.
   * @internal
   */
  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;
  }
  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,
      embeddingSettings: this.settings,
      invocationSettings: sapOptions ? { api: sapOptions.api } : void 0,
      modelApi: this.settings.api
    });
    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 {
  modelId;
  specificationVersion = "v3";
  supportsImageUrls = true;
  supportsMultipleCompletions = true;
  supportsParallelToolCalls = true;
  supportsStreaming = true;
  supportsStructuredOutputs = true;
  supportsToolCalls = true;
  get provider() {
    return this.config.provider;
  }
  get supportedUrls() {
    return {
      "image/*": [/^https:\/\/.+$/i, /^data:image\/.*$/]
    };
  }
  /** @internal */
  config;
  /** @internal */
  settings;
  /**
   * @param modelId - Model identifier.
   * @param settings - Model settings.
   * @param config - Model configuration.
   * @internal
   */
  constructor(modelId, settings, config) {
    if (settings.modelParams) {
      validateModelParamsSettings(settings.modelParams);
    }
    this.settings = settings;
    this.config = config;
    this.modelId = modelId;
  }
  async doGenerate(options) {
    const { strategy, strategyConfig } = await this.prepareInvocation(options);
    return strategy.doGenerate(strategyConfig, this.settings, options);
  }
  async doStream(options) {
    const { strategy, strategyConfig } = await this.prepareInvocation(options);
    return strategy.doStream(strategyConfig, this.settings, options);
  }
  supportsUrl(url) {
    if (url.protocol === "https:") return true;
    if (url.protocol === "data:") {
      return /^data:image\//i.test(url.href);
    }
    return false;
  }
  /**
   * Prepares common invocation context for doGenerate and doStream.
   * @param options - AI SDK call options.
   * @returns Strategy and configuration for the invocation.
   * @internal
   */
  async prepareInvocation(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,
        orchestrationConfigRef: sapOptions.orchestrationConfigRef,
        placeholderValues: sapOptions.placeholderValues,
        promptTemplateRef: sapOptions.promptTemplateRef
      } : 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, strategyConfig };
  }
};

// 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 = mergeSettingsWithApi(
      options.defaultSettings,
      settings,
      providerApi
    );
    return new SAPAILanguageModel(modelId, mergedSettings, {
      deploymentConfig,
      destination: options.destination,
      provider: `${providerName}.chat`,
      providerApi
    });
  };
  const createEmbeddingModel = (modelId, settings = {}) => {
    const mergedSettings = mergeSettingsWithApi(
      options.defaultSettings,
      settings,
      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