import "./chunk-BYW8Mqxw.js";
import { b as getEnvString, i as logger_default, m as safeJsonStringify, v as getEnvFloat, y as getEnvInt } from "./logger-CATn0kWr.js";
import "./esm-tl6dENiB.js";
import "./pythonUtils-D5rGzOeH.js";
import "./types-CHrVA-1r.js";
import { u as maybeLoadToolsFromExternalFile } from "./util-B4XoCK-L.js";
import { f as REQUEST_TIMEOUT_MS, h as parseChatPrompt } from "./fetch-BhuDaSn5.js";
import { o as getCache, s as isCacheEnabled } from "./cache-C2ESUUfo.js";
import { t as OpenAiChatCompletionProvider } from "./chat-CL4dYB-g.js";
import "./transform-BYdhQ9OB.js";
import { E as AnthropicMessagesProvider, _ as AzureChatCompletionProvider, c as VertexChatProvider, g as AzureEmbeddingProvider, l as VertexEmbeddingProvider, r as GroqProvider, t as VoyageEmbeddingProvider, u as AIStudioChatProvider, y as calculateAzureCost } from "./voyage-Dzv5Phzl.js";
import { n as calculateAnthropicCost } from "./util-BIRxnULT.js";
import "./openai-BH2FsThj.js";
import { a as calculateOpenAICost } from "./util-DUayzR6E.js";
import { t as OpenAiEmbeddingProvider } from "./embedding-Bo_7FjBa.js";
import { Anthropic } from "@adaline/anthropic";
import { Azure } from "@adaline/azure";
import { Gateway } from "@adaline/gateway";
import { Google } from "@adaline/google";
import { Groq } from "@adaline/groq";
import { OpenRouter } from "@adaline/open-router";
import { OpenAI } from "@adaline/openai";
import { TogetherAI } from "@adaline/together-ai";
import { Vertex } from "@adaline/vertex";

//#region src/providers/adaline.gateway.ts
var AdalineGatewayCachePlugin = class {
	async get(key) {
		return (await getCache()).get(key);
	}
	async set(key, value) {
		(await getCache()).set(key, value);
	}
	async delete(_key) {
		throw new Error("Not implemented");
	}
	async clear() {
		throw new Error("Not implemented");
	}
};
var AdalineGateway = class {
	gateway;
	getGateway() {
		if (!this.gateway) this.gateway = new Gateway({
			queueOptions: {
				maxConcurrentTasks: 4,
				retryCount: 2,
				retry: {
					initialDelay: getEnvInt("PROMPTFOO_REQUEST_BACKOFF_MS", 5e3),
					exponentialFactor: 2
				},
				timeout: REQUEST_TIMEOUT_MS
			},
			completeChatCache: new AdalineGatewayCachePlugin(),
			getEmbeddingsCache: new AdalineGatewayCachePlugin()
		});
		return this.gateway;
	}
};
const adalineGateway = new AdalineGateway();
var AdalineGatewayGenericProvider = class {
	gateway;
	modelName;
	providerName;
	env;
	config;
	providerOptions;
	constructor(providerName, modelName, options = {}) {
		this.modelName = modelName;
		this.providerName = providerName;
		this.providerOptions = options;
		const { config, id, env } = options;
		this.env = env;
		this.config = config || {};
		this.id = id ? () => id : this.id;
		this.gateway = adalineGateway.getGateway();
	}
	id() {
		return `adaline:${this.providerName}:${this.modelName}`;
	}
	toString() {
		return `[Adaline Gateway ${this.providerName}:${this.modelName}]`;
	}
	async callApi(_prompt, _context, _callApiOptions) {
		throw new Error("Not implemented");
	}
};
var AdalineGatewayEmbeddingProvider = class extends AdalineGatewayGenericProvider {
	async callEmbeddingApi(text) {
		try {
			let gatewayEmbeddingModel;
			const gatewayEmbeddingRequests = {
				modality: "text",
				requests: [text]
			};
			if (this.providerName === "openai") {
				const provider = new OpenAI();
				const parentClass = new OpenAiEmbeddingProvider(this.modelName, this.providerOptions);
				const apiKey = parentClass.getApiKey();
				if (!apiKey) throw new Error("OpenAI API key is not set. Set the OPENAI_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayEmbeddingModel = provider.embeddingModel({
					apiKey,
					modelName: this.modelName,
					baseUrl: parentClass.getApiUrl()
				});
			} else if (this.providerName === "vertex") {
				const provider = new Vertex();
				const parentClass = new VertexEmbeddingProvider(this.modelName, {
					config: this.config,
					env: this.env
				});
				const client = await parentClass.getClientWithCredentials();
				const projectId = await parentClass.getProjectId();
				const token = await client.getAccessToken();
				gatewayEmbeddingModel = provider.embeddingModel({
					modelName: this.modelName,
					accessToken: token.token,
					location: parentClass.getRegion(),
					projectId
				});
			} else if (this.providerName === "voyage") {
				const provider = new Anthropic();
				const apiKey = new VoyageEmbeddingProvider(this.modelName, this.providerOptions).getApiKey();
				if (!apiKey) throw new Error("Voyage API key is not set. Set the VOYAGE_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayEmbeddingModel = provider.embeddingModel({
					apiKey,
					modelName: this.modelName
				});
			} else if (this.providerName === "azureopenai") {
				const provider = new Azure();
				const parentClass = new AzureEmbeddingProvider(this.modelName, this.providerOptions);
				gatewayEmbeddingModel = provider.embeddingModel({
					apiKey: parentClass.getApiKeyOrThrow(),
					deploymentId: this.modelName,
					baseUrl: parentClass.getApiBaseUrl()
				});
			} else throw new Error(`Unsupported provider: ${this.providerName} on Adaline Gateway`);
			const gatewayRequest = {
				model: gatewayEmbeddingModel,
				config: {},
				embeddingRequests: gatewayEmbeddingRequests,
				options: {
					enableCache: isCacheEnabled(),
					customHeaders: this.config.headers
				}
			};
			logger_default.debug("Adaline Gateway Embedding API Request", { request: gatewayRequest });
			const response = await this.gateway.getEmbeddings(gatewayRequest);
			logger_default.debug(`Adaline Gateway Embedding API Response: ${safeJsonStringify(response)}`);
			return {
				embedding: response.response.embeddings[0].embedding,
				tokenUsage: {
					total: response.response.usage?.totalTokens,
					cached: response.cached ? response.response.usage?.totalTokens : 0,
					numRequests: 1
				}
			};
		} catch (error) {
			logger_default.error(`Error calling embedding API on Adaline Gateway: ${error}`);
			throw error;
		}
	}
};
var AdalineGatewayChatProvider = class extends AdalineGatewayGenericProvider {
	config;
	constructor(providerName, modelName, options = {}) {
		super(providerName, modelName, options);
		this.config = options.config || {};
	}
	checkRequestFormat(prompt) {
		const checkFormatRequestUsingConfig = () => {
			if (this.config.tools && this.config.tools.length > 0) {
				if ("definition" in this.config.tools[0]) return { formatType: "gateway" };
				else if ("function" in this.config.tools[0]) return { formatType: "openai" };
			}
			if ("maxTokens" in this.config || "topP" in this.config || "topK" in this.config || "minP" in this.config || "frequencyPenalty" in this.config || "presencePenalty" in this.config || "repetitionPenalty" in this.config || "logProbs" in this.config || "responseFormat" in this.config || "responseSchema" in this.config || "toolChoice" in this.config) return { formatType: "gateway" };
			return { formatType: "openai" };
		};
		const trimmedPrompt = prompt.trim();
		try {
			const objPrompt = JSON.parse(trimmedPrompt);
			if (Array.isArray(objPrompt) && objPrompt.length > 0) if ("content" in objPrompt[0]) {
				if (typeof objPrompt[0].content === "string" || Array.isArray(objPrompt[0].content) && objPrompt[0].content.length > 0 && "type" in objPrompt[0].content[0]) return { formatType: "openai" };
				else if (Array.isArray(objPrompt[0].content) && objPrompt[0].content.length > 0 && "modality" in objPrompt[0].content[0]) return { formatType: "gateway" };
			} else return checkFormatRequestUsingConfig();
			return checkFormatRequestUsingConfig();
		} catch {
			return checkFormatRequestUsingConfig();
		}
	}
	async callApi(prompt, context, callApiOptions) {
		let gatewayChatModel;
		let gatewayConfig;
		let gatewayMessages;
		let gatewayTools;
		let formatType;
		try {
			formatType = this.checkRequestFormat(prompt).formatType;
			logger_default.debug(`Calling Adaline Gateway Chat API with prompt format: ${formatType}`);
			if (formatType === "openai") {
				const { body } = await new OpenAiChatCompletionProvider(this.modelName, this.providerOptions).getOpenAiBody(prompt, context, callApiOptions);
				const gatewayRequest$1 = new OpenAI().chatModel({
					modelName: "gpt-4o",
					apiKey: "random-api-key"
				}).transformModelRequest(body);
				gatewayConfig = gatewayRequest$1.config;
				gatewayMessages = gatewayRequest$1.messages;
				gatewayTools = gatewayRequest$1.tools;
			} else {
				const _config = this.config;
				gatewayConfig = {
					maxTokens: _config.maxTokens,
					temperature: _config.temperature,
					topP: _config.topP,
					topK: _config.topK,
					minP: _config.minP,
					frequencyPenalty: _config.frequencyPenalty,
					presencePenalty: _config.presencePenalty,
					repetitionPenalty: _config.repetitionPenalty,
					stop: _config.stop,
					seed: _config.seed,
					logProbs: callApiOptions?.includeLogProbs === true || _config.logProbs,
					toolChoice: _config.toolChoice,
					responseFormat: _config.responseFormat,
					responseSchema: _config.responseSchema,
					safetySettings: _config.safetySettings
				};
				gatewayMessages = parseChatPrompt(prompt, [{
					role: "user",
					content: [{
						modality: "text",
						value: prompt
					}]
				}]);
				gatewayTools = _config.tools ? await maybeLoadToolsFromExternalFile(_config.tools) : void 0;
			}
			if (this.providerName === "openai") {
				const provider = new OpenAI();
				const parentClass = new OpenAiChatCompletionProvider(this.modelName, this.providerOptions);
				const apiKey = parentClass.getApiKey();
				if (!apiKey) throw new Error("OpenAI API key is not set. Set the OPENAI_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName,
					baseUrl: parentClass.getApiUrl(),
					organization: parentClass.getOrganization()
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "vertex") {
				const provider = new Vertex();
				const parentClass = new VertexChatProvider(this.modelName, {
					config: this.config,
					env: this.env
				});
				const client = await parentClass.getClientWithCredentials();
				const projectId = await parentClass.getProjectId();
				const token = await client.getAccessToken();
				if (token === null) throw new Error("Vertex API token is not set. Please configure the Google Cloud SDK");
				gatewayChatModel = provider.chatModel({
					authType: "accessToken",
					modelName: this.modelName,
					accessToken: token.token,
					location: parentClass.getRegion(),
					projectId
				});
			} else if (this.providerName === "google") {
				const provider = new Google();
				const parentClass = new AIStudioChatProvider(this.modelName, this.providerOptions);
				const apiKey = parentClass.getApiKey();
				if (!apiKey) throw new Error("Google API key is not set. Set the GOOGLE_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName,
					baseUrl: `https://${parentClass.getApiHost()}/v1beta`
				});
			} else if (this.providerName === "azureopenai") {
				const provider = new Azure();
				const parentClass = new AzureChatCompletionProvider(this.modelName, this.providerOptions);
				const apiKey = parentClass.getApiKeyOrThrow();
				gatewayChatModel = provider.chatModel({
					apiKey,
					deploymentId: this.modelName,
					baseUrl: parentClass.getApiBaseUrl()
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.topP = gatewayConfig.topP ?? getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "anthropic") {
				const provider = new Anthropic();
				const apiKey = new AnthropicMessagesProvider(this.modelName, this.providerOptions).getApiKey();
				if (!apiKey) throw new Error("Anthropic API key is not set. Set the ANTHROPIC_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? getEnvFloat("ANTHROPIC_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("ANTHROPIC_MAX_TOKENS", 1024);
			} else if (this.providerName === "groq") {
				const provider = new Groq();
				const apiKey = new GroqProvider(this.modelName, this.providerOptions).getApiKey();
				if (!apiKey) throw new Error("Groq API key is not set. Set the GROQ_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName
				});
			} else if (this.providerName === "openrouter") {
				const provider = new OpenRouter();
				const apiKey = this.config.apiKey || getEnvString("OPENROUTER_API_KEY");
				if (!apiKey) throw new Error("OpenRouter API key is not set. Set the OPENROUTER_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "togetherai") {
				const provider = new TogetherAI();
				const apiKey = this.config.apiKey || getEnvString("TOGETHER_API_KEY");
				if (!apiKey) throw new Error("TogetherAI API key is not set. Set the TOGETHER_API_KEY environment variable or add `apiKey` to the provider config.");
				gatewayChatModel = provider.chatModel({
					apiKey,
					modelName: this.modelName
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else throw new Error(`Unsupported provider on Adaline Gateway: ${this.providerName}`);
		} catch (error) {
			logger_default.error(`Adaline Gateway Chat API request error: ${String(error)}`);
			return { error: `request error: ${String(error)}` };
		}
		let response;
		const gatewayRequest = {
			model: gatewayChatModel,
			config: gatewayConfig,
			messages: gatewayMessages,
			tools: gatewayTools,
			options: {
				enableCache: isCacheEnabled(),
				customHeaders: this.config.headers
			}
		};
		logger_default.debug("Adaline Gateway Chat API request", { request: gatewayRequest });
		try {
			response = await this.gateway.completeChat(gatewayRequest);
			logger_default.debug(`Adaline Gateway Chat API response: ${safeJsonStringify(response)}`);
		} catch (error) {
			logger_default.error("Adaline Gateway Chat API response error", {
				error: String(error),
				request: gatewayRequest
			});
			return { error: `API response error: ${String(error)}` };
		}
		try {
			let output = "";
			if (response.response.messages[0].content.length === 1 && response.response.messages[0].content[0].modality === "text") {
				output = response.response.messages[0].content[0].value;
				if (gatewayConfig.responseFormat === "json_schema" && typeof output === "string") try {
					output = JSON.parse(output);
				} catch (error) {
					throw new Error(`Failed to parse JSON output: ${error}`);
				}
			} else if (formatType === "openai") if (response.response.messages[0].content.filter((content) => content.modality === "text").length > 0) output = {
				content: response.response.messages[0].content.filter((content) => content.modality === "text").map((content) => content.value).join(" "),
				tool_calls: response.response.messages[0].content.filter((content) => content.modality === "tool-call").map((content) => {
					return {
						id: content.id,
						type: "function",
						function: {
							name: content.name,
							arguments: content.arguments
						}
					};
				})
			};
			else output = response.response.messages[0].content.filter((content) => content.modality === "tool-call").map((content) => {
				return {
					id: content.id,
					type: "function",
					function: {
						name: content.name,
						arguments: content.arguments
					}
				};
			});
			else output = response.response.messages[0].content;
			let cost;
			const costConfig = { cost: this.config.cost };
			if (this.providerName === "openai") cost = calculateOpenAICost(this.modelName, costConfig, response.response.usage?.promptTokens, response.response.usage?.completionTokens);
			else if (this.providerName === "azureopenai") cost = calculateAzureCost(this.modelName, {}, response.response.usage?.promptTokens, response.response.usage?.completionTokens);
			else if (this.providerName === "anthropic") cost = calculateAnthropicCost(this.modelName, costConfig, response.response.usage?.promptTokens, response.response.usage?.completionTokens);
			const logProbs = response.response.logProbs?.map((logProb) => logProb.logProb);
			const tokenUsage = { numRequests: 1 };
			if (response.cached) {
				tokenUsage.cached = response.response.usage?.totalTokens;
				tokenUsage.total = response.response.usage?.totalTokens;
			} else {
				tokenUsage.prompt = response.response.usage?.promptTokens;
				tokenUsage.completion = response.response.usage?.completionTokens;
				tokenUsage.total = response.response.usage?.totalTokens;
			}
			return {
				output,
				tokenUsage,
				cached: response.cached,
				cost,
				logProbs
			};
		} catch (error) {
			logger_default.error(`Adaline Gateway Chat API post response error: ${String(error)}`);
			return { error: `API post response error: ${String(error)} : ${safeJsonStringify(response)}` };
		}
	}
};

//#endregion
export { AdalineGatewayChatProvider, AdalineGatewayEmbeddingProvider };
//# sourceMappingURL=adaline.gateway-Bxi6DfoO.js.map