import fetch from "node-fetch";
export class CohereReranker {
    params;
    name = "cohere";
    static defaultOptions = {
        apiBase: "https://api.cohere.ai/v1/",
        model: "rerank-english-v3.0",
    };
    constructor(params) {
        this.params = params;
    }
    async rerank(query, chunks) {
        let apiBase = this.params.apiBase ?? CohereReranker.defaultOptions.apiBase;
        if (!apiBase.endsWith("/")) {
            apiBase += "/";
        }
        const resp = await fetch(new URL("rerank", apiBase), {
            method: "POST",
            headers: {
                Authorization: `Bearer ${this.params.apiKey}`,
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                model: this.params.model ?? CohereReranker.defaultOptions.model,
                query,
                documents: chunks.map((chunk) => chunk.content),
            }),
        });
        if (!resp.ok) {
            throw new Error(await resp.text());
        }
        const data = (await resp.json());
        const results = data.results.sort((a, b) => a.index - b.index);
        return results.map((result) => result.relevance_score);
    }
}
