Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

rerank.ts

178 lines5.2 KB

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 } }
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 )
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 ? { billed: { quantity: searchUnits, unit: 'units' } }
124 : {}),
125 }
126​
127 return {
128 id: json.id ?? this.generateId(),
129 ranking: json.results.map((r) => ({
130 index: r.index,
131 score: r.relevance_score,
132 })),
133 usage,
134 }
135 }
137​
138/**
139 * Creates a Cohere rerank adapter with an explicit API key. Type resolution
140 * (per-model provider options) happens here at the call site.
141 *
142 * @example
143 * ```typescript
144 * const adapter = createCohereRerank('rerank-v3.5', 'co-...')
145 * ```
146 */
147export function createCohereRerank<TModel extends CohereRerankModel>(
148 model: TModel,
149 apiKey: string,
150 config?: Omit<CohereClientConfig, 'apiKey'>,
151): CohereRerankAdapter<TModel> {
152 return new CohereRerankAdapter({ apiKey, ...config }, model)
154​
155/**
156 * Creates a Cohere rerank adapter, reading `COHERE_API_KEY` from the
157 * environment.
158 *
159 * @throws Error if `COHERE_API_KEY` is not found.
160 *
161 * @example
162 * ```typescript
163 * import { rerank } from '@tanstack/ai'
164 * import { cohereRerank } from '@tanstack/ai-cohere'
165 *
166 * const { rerankedDocuments } = await rerank({
167 * adapter: cohereRerank('rerank-v3.5'),
168 * query: 'talk about rain',
169 * documents: ['sunny day', 'rainy afternoon'],
170 * })
171 * ```
172 */
173export function cohereRerank<TModel extends CohereRerankModel>(
174 model: TModel,
175 config?: Omit<CohereClientConfig, 'apiKey'>,
176): CohereRerankAdapter<TModel> {
177 return createCohereRerank(model, getCohereApiKeyFromEnv(), config)