| 35 | } |
| 36 | |
| 37 | export async function embedCohereQuery( |
| 38 | text: string, |
| 39 | cfg: EmbeddingConfig, |
| 40 | log: Logger, |
| 41 | ): Promise<number[]> { |
| 42 | const endpoint = cfg.endpoint ?? "https://api.cohere.ai/v1/embed"; |
| 43 | const model = cfg.model ?? "embed-english-v3.0"; |
| 44 | const headers: Record<string, string> = { |
| 45 | "Content-Type": "application/json", |
| 46 | Authorization: `Bearer ${cfg.apiKey}`, |
| 47 | ...cfg.headers, |
| 48 | }; |
| 49 | |
| 50 | const resp = await fetch(endpoint, { |
| 51 | method: "POST", |
| 52 | headers, |
| 53 | body: JSON.stringify({ |
| 54 | texts: [text], |
| 55 | model, |
| 56 | input_type: "search_query", |
| 57 | truncate: "END", |
| 58 | }), |
| 59 | signal: AbortSignal.timeout(cfg.timeoutMs ?? 30_000), |
| 60 | }); |
| 61 | |
| 62 | if (!resp.ok) { |
| 63 | const body = await resp.text(); |
| 64 | throw new Error(`Cohere query embedding failed (${resp.status}): ${body}`); |
| 65 | } |
| 66 | |
| 67 | const json = (await resp.json()) as { embeddings: number[][] }; |
| 68 | return json.embeddings[0]; |
| 69 | } |