import { b as getEnvString, i as logger_default, v as getEnvFloat, y as getEnvInt } from "./logger-BudIH0qK.js";
import { d as maybeLoadResponseFormatFromExternalFile, f as maybeLoadToolsFromExternalFile } from "./util-BaEBV99n.js";
import { o as getCache, s as isCacheEnabled } from "./cache-BNI_7DxT.js";
import { n as withGenAISpan } from "./genaiTracer-C6LxD3Ij.js";
import { i as normalizeFinishReason, n as MCPClient } from "./chat-F6Hy65LQ.js";
import { a as createEmptyTokenUsage } from "./tokenUsageUtils-BCCamZKN.js";
import { n as transformMCPToolsToAnthropic } from "./transform-kOrXspJM.js";
import { a as parseMessages, i as outputFromMessage, n as calculateAnthropicCost, o as processAnthropicTools, r as getTokenUsage, t as ANTHROPIC_MODELS } from "./util-V4vuCcPQ.js";
import Anthropic, { APIError } from "@anthropic-ai/sdk";

//#region src/providers/anthropic/generic.ts
/**
* Generic provider class for Anthropic APIs
* Serves as a base class with shared functionality for all Anthropic providers
*/
var AnthropicGenericProvider = class {
	modelName;
	config;
	env;
	apiKey;
	anthropic;
	constructor(modelName, options = {}) {
		const { config, id, env } = options;
		this.env = env;
		this.modelName = modelName;
		this.config = config || {};
		this.apiKey = this.getApiKey();
		this.anthropic = new Anthropic({
			apiKey: this.apiKey,
			baseURL: this.getApiBaseUrl()
		});
		this.id = id ? () => id : this.id;
	}
	id() {
		return `anthropic:${this.modelName}`;
	}
	toString() {
		return `[Anthropic Provider ${this.modelName}]`;
	}
	getApiKey() {
		return this.config?.apiKey || this.env?.ANTHROPIC_API_KEY || getEnvString("ANTHROPIC_API_KEY");
	}
	getApiBaseUrl() {
		return this.config?.apiBaseUrl || this.env?.ANTHROPIC_BASE_URL || getEnvString("ANTHROPIC_BASE_URL");
	}
	/**
	* Base implementation - should be overridden by specific provider implementations
	*/
	async callApi(_prompt, _context) {
		throw new Error("Not implemented: callApi must be implemented by subclasses");
	}
};

//#endregion
//#region src/providers/anthropic/messages.ts
var AnthropicMessagesProvider = class AnthropicMessagesProvider extends AnthropicGenericProvider {
	mcpClient = null;
	initializationPromise = null;
	static ANTHROPIC_MODELS = ANTHROPIC_MODELS;
	static ANTHROPIC_MODELS_NAMES = ANTHROPIC_MODELS.map((model) => model.id);
	constructor(modelName, options = {}) {
		if (!AnthropicMessagesProvider.ANTHROPIC_MODELS_NAMES.includes(modelName)) logger_default.warn(`Using unknown Anthropic model: ${modelName}`);
		super(modelName, options);
		const { id } = options;
		this.id = id ? () => id : this.id;
		if (this.config.mcp?.enabled) this.initializationPromise = this.initializeMCP();
	}
	async initializeMCP() {
		this.mcpClient = new MCPClient(this.config.mcp);
		await this.mcpClient.initialize();
	}
	async cleanup() {
		if (this.mcpClient) {
			await this.initializationPromise;
			await this.mcpClient.cleanup();
			this.mcpClient = null;
		}
	}
	toString() {
		if (!this.modelName) throw new Error("Anthropic model name is not set. Please provide a valid model name.");
		return `[Anthropic Messages Provider ${this.modelName}]`;
	}
	async callApi(prompt, context) {
		if (this.initializationPromise) await this.initializationPromise;
		if (!this.apiKey) throw new Error("Anthropic API key is not set. Set the ANTHROPIC_API_KEY environment variable or add `apiKey` to the provider config.");
		if (!this.modelName) throw new Error("Anthropic model name is not set. Please provide a valid model name.");
		const spanContext = {
			system: "anthropic",
			operationName: "chat",
			model: this.modelName,
			providerId: this.id(),
			maxTokens: this.config.max_tokens,
			temperature: this.config.temperature,
			testIndex: context?.test?.vars?.__testIdx,
			promptLabel: context?.prompt?.label,
			traceparent: context?.traceparent,
			requestBody: prompt
		};
		const resultExtractor = (response) => {
			const result = {};
			if (response.tokenUsage) result.tokenUsage = {
				prompt: response.tokenUsage.prompt,
				completion: response.tokenUsage.completion,
				total: response.tokenUsage.total,
				cached: response.tokenUsage.cached
			};
			if (response.finishReason) result.finishReasons = [response.finishReason];
			if (response.cached !== void 0) result.cacheHit = response.cached;
			if (response.output !== void 0) result.responseBody = typeof response.output === "string" ? response.output : JSON.stringify(response.output);
			return result;
		};
		return withGenAISpan(spanContext, () => this.callApiInternal(prompt, context), resultExtractor);
	}
	/**
	* Internal implementation of callApi without tracing wrapper.
	*/
	async callApiInternal(prompt, context) {
		const config = {
			...this.config,
			...context?.prompt?.config
		};
		const { system, extractedMessages, thinking } = parseMessages(prompt);
		let mcpTools = [];
		if (this.mcpClient) mcpTools = transformMCPToolsToAnthropic(this.mcpClient.getAllTools());
		const { processedTools: processedConfigTools, requiredBetaFeatures } = processAnthropicTools(await maybeLoadToolsFromExternalFile(config.tools, context?.vars) || []);
		const allTools = [...mcpTools, ...processedConfigTools];
		const processedOutputFormat = maybeLoadResponseFormatFromExternalFile(config.output_format, context?.vars);
		const shouldStream = config.stream ?? false;
		const params = {
			model: this.modelName,
			...system ? { system } : {},
			max_tokens: config?.max_tokens || getEnvInt("ANTHROPIC_MAX_TOKENS", config.thinking || thinking ? 2048 : 1024),
			messages: extractedMessages,
			stream: shouldStream,
			temperature: config.thinking || thinking ? config.temperature : config.temperature || getEnvFloat("ANTHROPIC_TEMPERATURE", 0),
			...allTools.length > 0 ? { tools: allTools } : {},
			...config.tool_choice ? { tool_choice: config.tool_choice } : {},
			...config.thinking || thinking ? { thinking: config.thinking || thinking } : {},
			...processedOutputFormat ? { output_format: processedOutputFormat } : {},
			...typeof config?.extra_body === "object" && config.extra_body ? config.extra_body : {}
		};
		logger_default.debug("Calling Anthropic Messages API", { params });
		const headers = { ...config.headers || {} };
		let allBetaFeatures = [...config.beta || [], ...requiredBetaFeatures];
		if (processedOutputFormat && !allBetaFeatures.includes("structured-outputs-2025-11-13")) allBetaFeatures.push("structured-outputs-2025-11-13");
		allBetaFeatures = [...new Set(allBetaFeatures)];
		if (allBetaFeatures.length > 0) headers["anthropic-beta"] = allBetaFeatures.join(",");
		const cache = await getCache();
		const cacheKey = `anthropic:${JSON.stringify(params)}`;
		if (isCacheEnabled()) {
			const cachedResponse = await cache.get(cacheKey);
			if (cachedResponse) {
				logger_default.debug(`Returning cached response for ${prompt}: ${cachedResponse}`);
				try {
					const parsedCachedResponse = JSON.parse(cachedResponse);
					const finishReason = normalizeFinishReason(parsedCachedResponse.stop_reason);
					let output = outputFromMessage(parsedCachedResponse, config.showThinking ?? true);
					if (processedOutputFormat?.type === "json_schema" && typeof output === "string") try {
						output = JSON.parse(output);
					} catch (error) {
						logger_default.error(`Failed to parse JSON output from structured outputs: ${error}`);
					}
					return {
						output,
						tokenUsage: getTokenUsage(parsedCachedResponse, true),
						...finishReason && { finishReason },
						cost: calculateAnthropicCost(this.modelName, config, parsedCachedResponse.usage?.input_tokens, parsedCachedResponse.usage?.output_tokens),
						cached: true
					};
				} catch {
					return {
						output: cachedResponse,
						tokenUsage: createEmptyTokenUsage()
					};
				}
			}
		}
		try {
			if (shouldStream) {
				const finalMessage = await (await this.anthropic.messages.stream(params, { ...typeof headers === "object" && Object.keys(headers).length > 0 ? { headers } : {} })).finalMessage();
				logger_default.debug(`Anthropic Messages API streaming complete`, { finalMessage });
				if (isCacheEnabled()) try {
					await cache.set(cacheKey, JSON.stringify(finalMessage));
				} catch (err) {
					logger_default.error(`Failed to cache response: ${String(err)}`);
				}
				const finishReason = normalizeFinishReason(finalMessage.stop_reason);
				let output = outputFromMessage(finalMessage, config.showThinking ?? true);
				if (processedOutputFormat?.type === "json_schema" && typeof output === "string") try {
					output = JSON.parse(output);
				} catch (error) {
					logger_default.error(`Failed to parse JSON output from structured outputs: ${error}`);
				}
				return {
					output,
					tokenUsage: getTokenUsage(finalMessage, false),
					...finishReason && { finishReason },
					cost: calculateAnthropicCost(this.modelName, config, finalMessage.usage?.input_tokens, finalMessage.usage?.output_tokens)
				};
			} else {
				const response = await this.anthropic.messages.create(params, { ...typeof headers === "object" && Object.keys(headers).length > 0 ? { headers } : {} });
				logger_default.debug(`Anthropic Messages API response`, { response });
				if (isCacheEnabled()) try {
					await cache.set(cacheKey, JSON.stringify(response));
				} catch (err) {
					logger_default.error(`Failed to cache response: ${String(err)}`);
				}
				const finishReason = normalizeFinishReason(response.stop_reason);
				let output = outputFromMessage(response, config.showThinking ?? true);
				if (processedOutputFormat?.type === "json_schema" && typeof output === "string") try {
					output = JSON.parse(output);
				} catch (error) {
					logger_default.error(`Failed to parse JSON output from structured outputs: ${error}`);
				}
				return {
					output,
					tokenUsage: getTokenUsage(response, false),
					...finishReason && { finishReason },
					cost: calculateAnthropicCost(this.modelName, config, response.usage?.input_tokens, response.usage?.output_tokens)
				};
			}
		} catch (err) {
			logger_default.error(`Anthropic Messages API call error: ${err instanceof Error ? err.message : String(err)}`);
			if (err instanceof APIError && err.error) {
				const errorDetails = err.error;
				return { error: `API call error: ${errorDetails.error.message}, status ${err.status}, type ${errorDetails.error.type}` };
			}
			return { error: `API call error: ${err instanceof Error ? err.message : String(err)}` };
		}
	}
};

//#endregion
export { AnthropicGenericProvider as n, AnthropicMessagesProvider as t };
//# sourceMappingURL=messages-on3QD6rz.js.map