const require_logger = require('./logger-B3t6CmTC.cjs');
const require_fetch = require('./fetch-COTDhwC8.cjs');
const require_util = require('./util-CtKyTm4Y.cjs');
const require_cache = require('./cache-CGY-3N8E.cjs');
const require_openai = require('./openai-DFnuahhK.cjs');

//#region src/providers/openai/completion.ts
var OpenAiCompletionProvider = class OpenAiCompletionProvider extends require_openai.OpenAiGenericProvider {
	static OPENAI_COMPLETION_MODELS = require_util.OPENAI_COMPLETION_MODELS;
	static OPENAI_COMPLETION_MODEL_NAMES = require_util.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()) require_logger.logger_default.warn(`FYI: Using unknown OpenAI completion model: ${modelName}`);
	}
	async callApi(prompt, context, callApiOptions) {
		if (this.requiresApiKey() && !this.getApiKey()) throw new Error("OpenAI API key is not set. Set the OPENAI_API_KEY environment variable or add `apiKey` to the provider config.");
		let stop;
		try {
			stop = require_logger.getEnvString("OPENAI_STOP") ? JSON.parse(require_logger.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 ?? require_logger.getEnvInt("OPENAI_MAX_TOKENS", 1024),
			temperature: this.config.temperature ?? require_logger.getEnvFloat("OPENAI_TEMPERATURE", 0),
			top_p: this.config.top_p ?? require_logger.getEnvFloat("OPENAI_TOP_P", 1),
			presence_penalty: this.config.presence_penalty ?? require_logger.getEnvFloat("OPENAI_PRESENCE_PENALTY", 0),
			frequency_penalty: this.config.frequency_penalty ?? require_logger.getEnvFloat("OPENAI_FREQUENCY_PENALTY", 0),
			best_of: this.config.best_of ?? require_logger.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 require_cache.fetchWithCache(`${this.getApiUrl()}/completions`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					...this.getApiKey() ? { Authorization: `Bearer ${this.getApiKey()}` } : {},
					...this.getOrganization() ? { "OpenAI-Organization": this.getOrganization() } : {},
					...this.config.headers
				},
				body: JSON.stringify(body)
			}, require_fetch.REQUEST_TIMEOUT_MS, "json", context?.bustCache ?? context?.debug, this.config.maxRetries));
		} catch (err) {
			require_logger.logger_default.error(`API call error: ${String(err)}`);
			return { error: `API call error: ${String(err)}` };
		}
		if (data.error) return { error: require_util.formatOpenAiError(data) };
		try {
			return {
				output: data.choices[0].text,
				tokenUsage: require_util.getTokenUsage(data, cached),
				cached,
				latencyMs,
				cost: require_util.calculateOpenAICost(this.modelName, this.config, data.usage?.prompt_tokens, data.usage?.completion_tokens)
			};
		} catch (err) {
			return { error: `API error: ${String(err)}: ${JSON.stringify(data)}` };
		}
	}
};

//#endregion
Object.defineProperty(exports, 'OpenAiCompletionProvider', {
  enumerable: true,
  get: function () {
    return OpenAiCompletionProvider;
  }
});
//# sourceMappingURL=completion-CH5DJDLM.cjs.map