Open History to see the last commit
1import { getApiKeyFromEnv } from '@tanstack/ai-utils'
2
3/**
4 * Configuration for the Cohere HTTP client used by the adapters in this
5 * package. Requests are made with plain `fetch` — no Cohere SDK dependency.
6 */
7export interface CohereClientConfig {
8 /** Cohere API key. */
9 apiKey: string
10
11 /**
12 * Base URL for every request (defaults to `https://api.cohere.com`). Same
13 * option name as the other adapters, so a gateway config can be spread into
14 * any of them. Wins over `baseUrl` when both are set.
15 */
16 baseURL?: string
17
18 /** Alias of `baseURL`. */
19 baseUrl?: string
20
21 /**
22 * Headers sent with every request. Same option name as the other adapters.
23 * Wins over `headers` when both are set.
24 */
25 defaultHeaders?: Record<string, string>
26
27 /** Alias of `defaultHeaders`. */
28 headers?: Record<string, string>
29
30 /**
31 * Cohere's embed API does not fetch remote image URLs itself. When this is
32 * enabled the adapter downloads http(s) image URLs and inlines them as
33 * base64 `data:` URIs before sending the request. Disabled by default.
34 */
35 allowUrlFetch?: boolean
36
37 /** Request timeout in milliseconds for API and image URL fetches (default: 30_000). */
38 timeout?: number
39}
40
41export const COHERE_DEFAULT_BASE_URL = 'https://api.cohere.com'
42
43/** Resolve the effective base URL (no trailing slash) and headers. */
44export function resolveCohereTransport(config: CohereClientConfig): {
45 baseUrl: string
46 headers: Record<string, string>
47} {
48 return {
49 baseUrl: (
50 config.baseURL ??
51 config.baseUrl ??
52 COHERE_DEFAULT_BASE_URL
53 ).replace(/\/+$/, ''),
54 headers: config.defaultHeaders ?? config.headers ?? {},
55 }
56}
57
58/**
59 * Gets Cohere API key from environment variables.
60 *
61 * Looks for `COHERE_API_KEY` in:
62 * - `process.env` (Node.js)
63 * - `window.env` (Browser with injected env)
64 *
65 * @throws Error if COHERE_API_KEY is not found
66 */
67export function getCohereApiKeyFromEnv(): string {
68 return getApiKeyFromEnv('COHERE_API_KEY')
69}