import { b as getEnvString, i as logger_default, v as getEnvFloat, y as getEnvInt } from "./logger-BudIH0qK.js";
import { p as REQUEST_TIMEOUT_MS } from "./fetch-D70iPJNm.js";
import { a as fetchWithCache } from "./cache-BNI_7DxT.js";
import { t as OpenAiGenericProvider } from "./openai-0a7Nnw31.js";
import { a as calculateOpenAICost, c as getTokenUsage, n as OPENAI_COMPLETION_MODELS, s as formatOpenAiError } from "./util-CnHd9JAv.js";

//#region src/providers/openai/embedding.ts
var OpenAiEmbeddingProvider = class extends OpenAiGenericProvider {
	async callEmbeddingApi(text) {
		if (this.requiresApiKey() && !this.getApiKey()) return { error: `API key is not set. Set the ${this.config.apiKeyEnvar || "OPENAI_API_KEY"} environment variable or add \`apiKey\` to the provider config.` };
		if (typeof text !== "string") return { error: `Invalid input type for embedding API. Expected string, got ${typeof text}. Input: ${JSON.stringify(text)}` };
		const body = {
			input: text,
			model: this.modelName
		};
		let data;
		let status;
		let statusText;
		let deleteFromCache;
		let cached = false;
		let latencyMs;
		try {
			const response = await fetchWithCache(`${this.getApiUrl()}/embeddings`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bearer ${this.getApiKey()}`,
					...this.getOrganization() ? { "OpenAI-Organization": this.getOrganization() } : {},
					...this.config.headers
				},
				body: JSON.stringify(body)
			}, REQUEST_TIMEOUT_MS, "json", false, this.config.maxRetries);
			({data, cached, status, statusText, latencyMs, deleteFromCache} = response);
			if (status && (status < 200 || status >= 300)) return { error: `API error: ${status} ${statusText || "Unknown error"}\n${typeof data === "string" ? data : JSON.stringify(data)}` };
		} catch (err) {
			logger_default.error(`API call error: ${String(err)}`);
			await deleteFromCache?.();
			return { error: `API call error: ${String(err)}` };
		}
		try {
			const embedding = data?.data?.[0]?.embedding;
			if (!embedding) return { error: "No embedding found in OpenAI embeddings API response" };
			return {
				embedding,
				latencyMs,
				tokenUsage: getTokenUsage(data, cached)
			};
		} catch (err) {
			logger_default.error(`Response parsing error: ${String(err)}`);
			await deleteFromCache?.();
			return { error: `API error: ${String(err)}: ${JSON.stringify(data)}` };
		}
	}
};

//#endregion
//#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_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 = 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.getOrganization() ? { "OpenAI-Organization": this.getOrganization() } : {},
					...this.config.headers
				},
				body: JSON.stringify(body)
			}, REQUEST_TIMEOUT_MS, "json", context?.bustCache ?? context?.debug, this.config.maxRetries));
		} catch (err) {
			logger_default.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: 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
export { OpenAiEmbeddingProvider as n, OpenAiCompletionProvider as t };
//# sourceMappingURL=completion-DAe6fo0x.js.map