import {
  convertToSAPMessages
} from "./chunk-G2BVB5LB.js";
import {
  StreamIdGenerator,
  buildGenerateResult,
  buildModelParams,
  convertResponseFormat,
  convertToolsToSAPFormat,
  createAISDKRequestBodySummary,
  createStreamTransformer,
  mapToolChoice
} from "./chunk-24QM3M77.js";
import {
  VERSION,
  convertToAISDKError,
  getProviderName,
  normalizeHeaders,
  sapAILanguageModelProviderOptions
} from "./chunk-LSTAKB2E.js";

// src/orchestration-language-model-strategy.ts
import { parseProviderOptions } from "@ai-sdk/provider-utils";
function isTemplateRefById(ref) {
  return "id" in ref;
}
var PARAM_MAPPINGS = [
  { camelCaseKey: "maxTokens", optionKey: "maxOutputTokens", outputKey: "max_tokens" },
  { camelCaseKey: "temperature", optionKey: "temperature", outputKey: "temperature" },
  { camelCaseKey: "topP", optionKey: "topP", outputKey: "top_p" },
  { camelCaseKey: "topK", optionKey: "topK", outputKey: "top_k" },
  {
    camelCaseKey: "frequencyPenalty",
    optionKey: "frequencyPenalty",
    outputKey: "frequency_penalty"
  },
  { camelCaseKey: "presencePenalty", optionKey: "presencePenalty", outputKey: "presence_penalty" },
  { camelCaseKey: "seed", optionKey: "seed", outputKey: "seed" },
  { camelCaseKey: "parallel_tool_calls", outputKey: "parallel_tool_calls" }
];
var OrchestrationLanguageModelStrategy = class {
  ClientClass;
  constructor(ClientClass) {
    this.ClientClass = ClientClass;
  }
  async doGenerate(config, settings, options) {
    try {
      const { messages, orchestrationConfig, placeholderValues, toolChoice, warnings } = await this.buildOrchestrationConfig(config, settings, options);
      const client = this.createClient(config, orchestrationConfig);
      const requestBody = this.buildRequestBody(
        messages,
        orchestrationConfig,
        placeholderValues,
        toolChoice
      );
      const response = await client.chatCompletion(
        requestBody,
        options.abortSignal ? { signal: options.abortSignal } : void 0
      );
      return buildGenerateResult({
        modelId: config.modelId,
        providerName: getProviderName(config.provider),
        requestBody,
        response,
        responseHeaders: normalizeHeaders(response.rawResponse.headers),
        version: VERSION,
        warnings
      });
    } catch (error) {
      throw convertToAISDKError(error, {
        operation: "doGenerate",
        requestBody: createAISDKRequestBodySummary(options),
        url: "sap-ai:orchestration"
      });
    }
  }
  async doStream(config, settings, options) {
    try {
      const { messages, orchestrationConfig, placeholderValues, toolChoice, warnings } = await this.buildOrchestrationConfig(config, settings, options);
      const client = this.createClient(config, orchestrationConfig);
      const requestBody = this.buildRequestBody(
        messages,
        orchestrationConfig,
        placeholderValues,
        toolChoice
      );
      const streamResponse = await client.stream(requestBody, options.abortSignal, {
        promptTemplating: { include_usage: true }
      });
      const idGenerator = new StreamIdGenerator();
      const responseId = idGenerator.generateResponseId();
      const transformedStream = createStreamTransformer({
        convertToAISDKError,
        idGenerator,
        includeRawChunks: options.includeRawChunks ?? false,
        modelId: config.modelId,
        options,
        providerName: getProviderName(config.provider),
        responseId,
        sdkStream: streamResponse.stream,
        streamResponseGetFinishReason: () => streamResponse.getFinishReason(),
        streamResponseGetTokenUsage: () => streamResponse.getTokenUsage(),
        url: "sap-ai:orchestration",
        version: VERSION,
        warnings
      });
      return {
        request: {
          body: requestBody
        },
        stream: transformedStream
      };
    } catch (error) {
      throw convertToAISDKError(error, {
        operation: "doStream",
        requestBody: createAISDKRequestBodySummary(options),
        url: "sap-ai:orchestration"
      });
    }
  }
  async buildOrchestrationConfig(config, settings, options) {
    const providerName = getProviderName(config.provider);
    const sapOptions = await parseProviderOptions({
      provider: providerName,
      providerOptions: options.providerOptions,
      schema: sapAILanguageModelProviderOptions
    });
    const warnings = [];
    const orchSettings = settings;
    const messages = convertToSAPMessages(options.prompt, {
      escapeTemplatePlaceholders: sapOptions?.escapeTemplatePlaceholders ?? orchSettings.escapeTemplatePlaceholders ?? true,
      includeReasoning: sapOptions?.includeReasoning ?? orchSettings.includeReasoning ?? false
    });
    let tools;
    const settingsTools = orchSettings.tools;
    const optionsTools = options.tools;
    if (settingsTools && settingsTools.length > 0 && optionsTools && optionsTools.length > 0) {
      warnings.push({
        message: "Both settings.tools and call options.tools were provided; preferring call options.tools.",
        type: "other"
      });
    }
    if (settingsTools && settingsTools.length > 0 && (!optionsTools || optionsTools.length === 0)) {
      tools = settingsTools;
    } else if (optionsTools && optionsTools.length > 0) {
      const toolsResult = convertToolsToSAPFormat(optionsTools);
      tools = toolsResult.tools;
      warnings.push(...toolsResult.warnings);
    }
    const { modelParams: baseModelParams, warnings: paramWarnings } = buildModelParams({
      options,
      paramMappings: PARAM_MAPPINGS,
      providerModelParams: sapOptions?.modelParams,
      settingsModelParams: orchSettings.modelParams
    });
    const modelParams = baseModelParams;
    warnings.push(...paramWarnings);
    const toolChoice = mapToolChoice(options.toolChoice);
    const { responseFormat, warning: responseFormatWarning } = convertResponseFormat(
      options.responseFormat,
      orchSettings.responseFormat
    );
    if (responseFormatWarning) {
      warnings.push(responseFormatWarning);
    }
    const promptTemplateRef = sapOptions?.promptTemplateRef ?? orchSettings.promptTemplateRef;
    const promptConfig = promptTemplateRef ? {
      template_ref: isTemplateRefById(promptTemplateRef) ? {
        id: promptTemplateRef.id,
        ...promptTemplateRef.scope && { scope: promptTemplateRef.scope }
      } : {
        name: promptTemplateRef.name,
        scenario: promptTemplateRef.scenario,
        version: promptTemplateRef.version,
        ...promptTemplateRef.scope && { scope: promptTemplateRef.scope }
      },
      ...tools && tools.length > 0 ? { tools } : {},
      ...responseFormat ? { response_format: responseFormat } : {}
    } : {
      template: [],
      ...tools && tools.length > 0 ? { tools } : {},
      ...responseFormat ? { response_format: responseFormat } : {}
    };
    const orchestrationConfig = {
      promptTemplating: {
        model: {
          name: config.modelId,
          params: modelParams,
          ...orchSettings.modelVersion ? { version: orchSettings.modelVersion } : {}
        },
        prompt: promptConfig
      },
      ...orchSettings.masking && Object.keys(orchSettings.masking).length > 0 ? { masking: orchSettings.masking } : {},
      ...orchSettings.filtering && Object.keys(orchSettings.filtering).length > 0 ? { filtering: orchSettings.filtering } : {},
      ...orchSettings.grounding && Object.keys(orchSettings.grounding).length > 0 ? { grounding: orchSettings.grounding } : {},
      ...orchSettings.translation && Object.keys(orchSettings.translation).length > 0 ? { translation: orchSettings.translation } : {}
    };
    const mergedPlaceholderValues = orchSettings.placeholderValues || sapOptions?.placeholderValues ? {
      ...orchSettings.placeholderValues,
      ...sapOptions?.placeholderValues
    } : void 0;
    const placeholderValues = mergedPlaceholderValues && Object.keys(mergedPlaceholderValues).length > 0 ? mergedPlaceholderValues : void 0;
    return {
      messages,
      orchestrationConfig,
      placeholderValues,
      toolChoice,
      warnings
    };
  }
  buildRequestBody(messages, orchestrationConfig, placeholderValues, toolChoice) {
    const promptTemplating = orchestrationConfig.promptTemplating;
    return {
      messages,
      model: {
        ...orchestrationConfig.promptTemplating.model
      },
      ...placeholderValues ? { placeholderValues } : {},
      ...promptTemplating.prompt.template_ref ? { template_ref: promptTemplating.prompt.template_ref } : {},
      ...promptTemplating.prompt.tools ? { tools: promptTemplating.prompt.tools } : {},
      ...toolChoice ? { tool_choice: toolChoice } : {},
      ...promptTemplating.prompt.response_format ? { response_format: promptTemplating.prompt.response_format } : {},
      ...orchestrationConfig.masking && Object.keys(orchestrationConfig.masking).length > 0 ? { masking: orchestrationConfig.masking } : {},
      ...orchestrationConfig.filtering && Object.keys(orchestrationConfig.filtering).length > 0 ? { filtering: orchestrationConfig.filtering } : {},
      ...orchestrationConfig.grounding && Object.keys(orchestrationConfig.grounding).length > 0 ? { grounding: orchestrationConfig.grounding } : {},
      ...orchestrationConfig.translation && Object.keys(orchestrationConfig.translation).length > 0 ? { translation: orchestrationConfig.translation } : {}
    };
  }
  createClient(config, orchConfig) {
    return new this.ClientClass(orchConfig, config.deploymentConfig, config.destination);
  }
};
export {
  OrchestrationLanguageModelStrategy
};
//# sourceMappingURL=orchestration-language-model-strategy-NNQ7KFNH.js.map