import { D as getEnvInt, E as getEnvFloat, O as getEnvString, o as logger } from "./logger-CtGm8dC_.js";
import { y as getRequestTimeoutMs } from "./fetch-AchwhzAC.js";
import { r as fetchWithCache } from "./cache-wQj0h878.js";
import { i as OPENAI_COMPLETION_MODELS, l as formatOpenAiError, u as getTokenUsage } from "./util-BKx_SQfl.js";
import { n as calculateOpenAIUsageCost } from "./billing-C9iWQIlz.js";
import { t as OpenAiGenericProvider } from "./openai-DWlt6qgx.js";
//#region src/providers/openai/completion.ts
var OpenAiCompletionProvider = class OpenAiCompletionProvider extends OpenAiGenericProvider {
	static OPENAI_COMPLETION_MODELS = OPENAI_COMPLETION_MODELS;
	static OPENAI_COMPLETION_MODEL_NAMES = OPENAI_COMPLETION_MODELS.map((model) => model.id);
	config;
	constructor(modelName, options = {}) {
		super(modelName, options);
		this.config = options.config || {};
		if (!OpenAiCompletionProvider.OPENAI_COMPLETION_MODEL_NAMES.includes(modelName) && this.getApiUrl() === this.getApiUrlDefault()) logger.warn(`FYI: Using unknown OpenAI completion model: ${modelName}`);
	}
	async callApi(prompt, context, callApiOptions) {
		if (this.requiresApiKey() && !this.getApiKey()) throw new Error(this.getMissingApiKeyErrorMessage());
		let stop;
		try {
			stop = getEnvString("OPENAI_STOP") ? JSON.parse(getEnvString("OPENAI_STOP") || "") : this.config?.stop || ["<|im_end|>", "<|endoftext|>"];
		} catch (err) {
			throw new Error(`OPENAI_STOP is not a valid JSON string: ${err}`);
		}
		const body = {
			model: this.modelName,
			prompt,
			seed: this.config.seed,
			max_tokens: this.config.max_tokens ?? getEnvInt("OPENAI_MAX_TOKENS", 1024),
			temperature: this.config.temperature ?? getEnvFloat("OPENAI_TEMPERATURE", 0),
			top_p: this.config.top_p ?? getEnvFloat("OPENAI_TOP_P", 1),
			presence_penalty: this.config.presence_penalty ?? getEnvFloat("OPENAI_PRESENCE_PENALTY", 0),
			frequency_penalty: this.config.frequency_penalty ?? getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0),
			best_of: this.config.best_of ?? getEnvInt("OPENAI_BEST_OF", 1),
			...callApiOptions?.includeLogProbs ? { logprobs: callApiOptions.includeLogProbs } : {},
			...stop ? { stop } : {},
			...this.config.passthrough || {}
		};
		let data, cached = false, latencyMs;
		try {
			({data, cached, latencyMs} = await fetchWithCache(`${this.getApiUrl()}/completions`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					...this.getApiKey() ? { Authorization: `Bearer ${this.getApiKey()}` } : {},
					...this.getOpenAiRequestHeaders()
				},
				body: JSON.stringify(body)
			}, getRequestTimeoutMs(), "json", context?.bustCache ?? context?.debug, this.config.maxRetries));
		} catch (err) {
			logger.error(`API call error: ${String(err)}`);
			return { error: `API call error: ${String(err)}` };
		}
		if (data.error) return { error: formatOpenAiError(data) };
		try {
			return {
				output: data.choices[0].text,
				tokenUsage: getTokenUsage(data, cached),
				cached,
				latencyMs,
				cost: calculateOpenAIUsageCost(this.modelName, this.config, data.usage, {
					cachedResponse: cached,
					serviceTier: data.service_tier ?? this.config.service_tier
				})
			};
		} catch (err) {
			return { error: `API error: ${String(err)}: ${JSON.stringify(data)}` };
		}
	}
};
//#endregion
export { OpenAiCompletionProvider as t };

//# sourceMappingURL=completion-BYcM8Rbb.js.map