const require_logger = require('./logger-q_xXORhb.cjs');
require('./esm-D3hKBIJw.cjs');
require('./pythonUtils-CA-U67vF.cjs');
require('./types-DxNbVAX2.cjs');
const require_util = require('./util-C-nJy5yZ.cjs');
const require_fetch = require('./fetch--6dTWCD4.cjs');
const require_cache = require('./cache-BrwLt6g7.cjs');
const require_chat = require('./chat-BbQFtNh7.cjs');
require('./transform-DFn8CyvR.cjs');
const require_voyage = require('./voyage-CelKlDom.cjs');
const require_util$1 = require('./util-IPzLzpX6.cjs');
require('./openai-DLwm54eV.cjs');
const require_util$2 = require('./util-DdYfVi1z.cjs');
const require_embedding = require('./embedding-7FmJs2RM.cjs');
let __adaline_anthropic = require("@adaline/anthropic");
let __adaline_azure = require("@adaline/azure");
let __adaline_gateway = require("@adaline/gateway");
let __adaline_google = require("@adaline/google");
let __adaline_groq = require("@adaline/groq");
let __adaline_open_router = require("@adaline/open-router");
let __adaline_openai = require("@adaline/openai");
let __adaline_together_ai = require("@adaline/together-ai");
let __adaline_vertex = require("@adaline/vertex");

//#region src/providers/adaline.gateway.ts
var AdalineGatewayCachePlugin = class {
	async get(key) {
		return (await require_cache.getCache()).get(key);
	}
	async set(key, value) {
		(await require_cache.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 __adaline_gateway.Gateway({
			queueOptions: {
				maxConcurrentTasks: 4,
				retryCount: 2,
				retry: {
					initialDelay: require_logger.getEnvInt("PROMPTFOO_REQUEST_BACKOFF_MS", 5e3),
					exponentialFactor: 2
				},
				timeout: require_fetch.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 __adaline_openai.OpenAI();
				const parentClass = new require_embedding.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 __adaline_vertex.Vertex();
				const parentClass = new require_voyage.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 __adaline_anthropic.Anthropic();
				const apiKey = new require_voyage.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 __adaline_azure.Azure();
				const parentClass = new require_voyage.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: require_cache.isCacheEnabled(),
					customHeaders: this.config.headers
				}
			};
			require_logger.logger_default.debug("Adaline Gateway Embedding API Request", { request: gatewayRequest });
			const response = await this.gateway.getEmbeddings(gatewayRequest);
			require_logger.logger_default.debug(`Adaline Gateway Embedding API Response: ${require_logger.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) {
			require_logger.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;
			require_logger.logger_default.debug(`Calling Adaline Gateway Chat API with prompt format: ${formatType}`);
			if (formatType === "openai") {
				const { body } = await new require_chat.OpenAiChatCompletionProvider(this.modelName, this.providerOptions).getOpenAiBody(prompt, context, callApiOptions);
				const gatewayRequest$1 = new __adaline_openai.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 = require_fetch.parseChatPrompt(prompt, [{
					role: "user",
					content: [{
						modality: "text",
						value: prompt
					}]
				}]);
				gatewayTools = _config.tools ? await require_util.maybeLoadToolsFromExternalFile(_config.tools) : void 0;
			}
			if (this.providerName === "openai") {
				const provider = new __adaline_openai.OpenAI();
				const parentClass = new require_chat.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 ?? require_logger.getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? require_logger.getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? require_logger.getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? require_logger.getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "vertex") {
				const provider = new __adaline_vertex.Vertex();
				const parentClass = new require_voyage.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 __adaline_google.Google();
				const parentClass = new require_voyage.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 __adaline_azure.Azure();
				const parentClass = new require_voyage.AzureChatCompletionProvider(this.modelName, this.providerOptions);
				const apiKey = parentClass.getApiKeyOrThrow();
				gatewayChatModel = provider.chatModel({
					apiKey,
					deploymentId: this.modelName,
					baseUrl: parentClass.getApiBaseUrl()
				});
				gatewayConfig.temperature = gatewayConfig.temperature ?? require_logger.getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.topP = gatewayConfig.topP ?? require_logger.getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? require_logger.getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? require_logger.getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "anthropic") {
				const provider = new __adaline_anthropic.Anthropic();
				const apiKey = new require_voyage.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 ?? require_logger.getEnvFloat("ANTHROPIC_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("ANTHROPIC_MAX_TOKENS", 1024);
			} else if (this.providerName === "groq") {
				const provider = new __adaline_groq.Groq();
				const apiKey = new require_voyage.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 __adaline_open_router.OpenRouter();
				const apiKey = this.config.apiKey || require_logger.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 ?? require_logger.getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? require_logger.getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? require_logger.getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? require_logger.getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else if (this.providerName === "togetherai") {
				const provider = new __adaline_together_ai.TogetherAI();
				const apiKey = this.config.apiKey || require_logger.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 ?? require_logger.getEnvFloat("OPENAI_TEMPERATURE", 0);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_TOKENS", 1024);
				gatewayConfig.maxTokens = gatewayConfig.maxTokens ?? require_logger.getEnvFloat("OPENAI_MAX_COMPLETION_TOKENS");
				gatewayConfig.topP = gatewayConfig.topP ?? require_logger.getEnvFloat("OPENAI_TOP_P", 1);
				gatewayConfig.frequencyPenalty = gatewayConfig.frequencyPenalty ?? require_logger.getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0);
				gatewayConfig.presencePenalty = gatewayConfig.presencePenalty ?? require_logger.getEnvFloat("OPENAI_PRESENCE_PENALTY", 0);
			} else throw new Error(`Unsupported provider on Adaline Gateway: ${this.providerName}`);
		} catch (error) {
			require_logger.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: require_cache.isCacheEnabled(),
				customHeaders: this.config.headers
			}
		};
		require_logger.logger_default.debug("Adaline Gateway Chat API request", { request: gatewayRequest });
		try {
			response = await this.gateway.completeChat(gatewayRequest);
			require_logger.logger_default.debug(`Adaline Gateway Chat API response: ${require_logger.safeJsonStringify(response)}`);
		} catch (error) {
			require_logger.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 = require_util$2.calculateOpenAICost(this.modelName, costConfig, response.response.usage?.promptTokens, response.response.usage?.completionTokens);
			else if (this.providerName === "azureopenai") cost = require_voyage.calculateAzureCost(this.modelName, {}, response.response.usage?.promptTokens, response.response.usage?.completionTokens);
			else if (this.providerName === "anthropic") cost = require_util$1.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) {
			require_logger.logger_default.error(`Adaline Gateway Chat API post response error: ${String(error)}`);
			return { error: `API post response error: ${String(error)} : ${require_logger.safeJsonStringify(response)}` };
		}
	}
};

//#endregion
exports.AdalineGatewayChatProvider = AdalineGatewayChatProvider;
exports.AdalineGatewayEmbeddingProvider = AdalineGatewayEmbeddingProvider;
//# sourceMappingURL=adaline.gateway-8hpGXLDL.cjs.map