1const BASE = "https://ai.mongodb.com/v1"; // Voyage via MongoDB Atlas
2
3async function post<T>(path: string, body: unknown): Promise<T> {
4 const res = await fetch(BASE + path, {
5 method: "POST",
6 headers: {
7 "content-type": "application/json",
8 authorization: `Bearer ${process.env.VOYAGE_API_KEY}`,
9 },
10 body: JSON.stringify(body),
11 });
12 if (!res.ok) throw new Error(`Voyage ${path}: ${res.status} ${await res.text()}`);
13 return (await res.json()) as T;
14}
15
16export async function embed(texts: string[], inputType: "query" | "document") {
17 const json = await post<{ data: { embedding: number[] }[] }>("/embeddings", {
18 input: texts, model: "voyage-4", input_type: inputType,
19 });
20 return json.data.map((d) => d.embedding);
21}
22
23export async function rerank(query: string, documents: string[], topK: number) {
24 const json = await post<{ data: { index: number; relevance_score: number }[] }>("/rerank", {
25 query, documents, model: "rerank-3", top_k: topK,
26 });
27 return json.data; // best first
28}