Open History to see the last commit
1import { BaseRerankAdapter } from '@tanstack/ai/adapters'
2import { resolveCohereTransport, getCohereApiKeyFromEnv } from '../utils/client'
3import type { CohereClientConfig } from '../utils/client'
4import type {
5 CohereRerankModel,
6 InferCohereRerankProviderOptions,
7} from '../model-meta'
8import type {
9 RerankAdapterResult,
10 RerankOptions,
11 TokenUsage,
12} from '@tanstack/ai'
13
14/** Shape of the Cohere `/v2/rerank` response we depend on. */
15interface CohereRerankResponse {
16 id?: string
17 results: Array<{ index: number; relevance_score: number }>
18 meta?: { billed_units?: { search_units?: number } }
19}
20
21function isCohereRerankResponse(value: unknown): value is CohereRerankResponse {
22 if (typeof value !== 'object' || value === null) return false
23 const results = (value as { results?: unknown }).results
24 return (
25 Array.isArray(results) &&
26 results.every(
27 (r) =>
28 typeof r === 'object' &&
29 r !== null &&
30 typeof (r as { index?: unknown }).index === 'number' &&
31 typeof (r as { relevance_score?: unknown }).relevance_score ===
32 'number',
33 )
34 )
35}
36
37/**
38 * Cohere rerank adapter.
39 *
40 * Talks to Cohere's `/v2/rerank` endpoint over raw `fetch` — no SDK. Returns
41 * scored indices into the submitted documents; the `rerank()` activity maps
42 * those back to the caller's original documents.
43 */
44export class CohereRerankAdapter<
45 TModel extends CohereRerankModel,
46> extends BaseRerankAdapter<TModel, InferCohereRerankProviderOptions<TModel>> {
47 readonly name = 'cohere' as const
48
49 private readonly apiKey: string
50 private readonly baseUrl: string
51 private readonly headers: Record<string, string>
52
53 constructor(config: CohereClientConfig, model: TModel) {
54 super({}, model)
55 this.apiKey = config.apiKey
56 const transport = resolveCohereTransport(config)
57 this.baseUrl = transport.baseUrl
58 this.headers = transport.headers
59 }
60
61 async rerank(
62 options: RerankOptions<InferCohereRerankProviderOptions<TModel>>,
63 ): Promise<RerankAdapterResult> {
64 const { model, query, documents, topN, modelOptions, abortSignal, logger } =
65 options
66
67 const body: Record<string, unknown> = { model, query, documents }
68 if (topN !== undefined) body['top_n'] = topN
69 if (modelOptions?.maxTokensPerDoc !== undefined) {
70 body['max_tokens_per_doc'] = modelOptions.maxTokensPerDoc
71 }
72
73 logger.request(
74 `activity=rerank provider=${this.name} model=${model} documents=${documents.length}`,
75 { provider: this.name, model },
76 )
77
78 let response: Response
79 try {
80 response = await fetch(`${this.baseUrl}/v2/rerank`, {
81 method: 'POST',
82 headers: {
83 Authorization: `Bearer ${this.apiKey}`,
84 'Content-Type': 'application/json',
85 ...this.headers,
86 },
87 body: JSON.stringify(body),
88 ...(abortSignal ? { signal: abortSignal } : {}),
89 })
90 } catch (error) {
91 logger.errors(`${this.name}.rerank fatal`, {
92 error,
93 source: `${this.name}.rerank`,
94 })
95 throw error
96 }
97
98 if (!response.ok) {
99 const detail = await response.text().catch(() => '')
100 const error = new Error(
101 `Cohere rerank request failed: ${response.status} ${response.statusText}${
102 detail ? ` — ${detail}` : ''
103 }`,
104 )
105 logger.errors(`${this.name}.rerank fatal`, {
106 error,
107 source: `${this.name}.rerank`,
108 })
109 throw error
110 }
111
112 const json: unknown = await response.json()
113 if (!isCohereRerankResponse(json)) {
114 throw new Error('Cohere rerank response had an unexpected shape')
115 }
116
117 const searchUnits = json.meta?.billed_units?.search_units
118 const usage: TokenUsage = {
119 promptTokens: 0,
120 completionTokens: 0,
121 totalTokens: 0,
122 ...(searchUnits !== undefined
123 ? {
124 billed: { quantity: searchUnits, unit: 'units' },
125 unitsBilled: searchUnits,
126 }
127 : {}),
128 }
129
130 return {
131 id: json.id ?? this.generateId(),
132 ranking: json.results.map((r) => ({
133 index: r.index,
134 score: r.relevance_score,
135 })),
136 usage,
137 }
138 }
139}
140
141/**
142 * Creates a Cohere rerank adapter with an explicit API key. Type resolution
143 * (per-model provider options) happens here at the call site.
144 *
145 * @example
146 * ```typescript
147 * const adapter = createCohereRerank('rerank-v3.5', 'co-...')
148 * ```
149 */
150export function createCohereRerank<TModel extends CohereRerankModel>(
151 model: TModel,
152 apiKey: string,
153 config?: Omit<CohereClientConfig, 'apiKey'>,
154): CohereRerankAdapter<TModel> {
155 return new CohereRerankAdapter({ apiKey, ...config }, model)
156}
157
158/**
159 * Creates a Cohere rerank adapter, reading `COHERE_API_KEY` from the
160 * environment.
161 *
162 * @throws Error if `COHERE_API_KEY` is not found.
163 *
164 * @example
165 * ```typescript
166 * import { rerank } from '@tanstack/ai'
167 * import { cohereRerank } from '@tanstack/ai-cohere'
168 *
169 * const { rerankedDocuments } = await rerank({
170 * adapter: cohereRerank('rerank-v3.5'),
171 * query: 'talk about rain',
172 * documents: ['sunny day', 'rainy afternoon'],
173 * })
174 * ```
175 */
176export function cohereRerank<TModel extends CohereRerankModel>(
177 model: TModel,
178 config?: Omit<CohereClientConfig, 'apiKey'>,
179): CohereRerankAdapter<TModel> {
180 return createCohereRerank(model, getCohereApiKeyFromEnv(), config)
181}