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

cohere.ts

206 lines6.1 KB

1/**
2 * Cohere — official OpenAPI YAML from cohere-ai/cohere-developer-experience
3 * (public). Models list requires COHERE_API_KEY.
4 */
5import type { Activity } from '#/db/schema.ts'
6import { cohereModelDocFacts } from '../cohere-model-docs.ts'
7import { cohereCommandPageFacts } from '../cohere-model-pages.ts'
8import { cohereModelPricing } from '../cohere-pricing.ts'
9import { openAiCompatModelFacts } from '../openai-compat.ts'
10import {
11 cohereModelReasoning,
12 listsReasoning,
13 overlayModelFacts,
14} from '../reasoning-config.ts'
15import { fetchJson, fetchOpenApi, skippedResult } from '../types.ts'
16import { bearerConnect } from '../connect.ts'
17import type {
18 ListModelsResult,
19 ModelInfo,
20 ProviderConfig,
21 ProviderSecrets,
22 SpecFetchResult,
23} from '../types.ts'
24​
25const COHERE_OPENAPI_URL =
26 'https://raw.githubusercontent.com/cohere-ai/cohere-developer-experience/main/cohere-openapi.yaml'
27const COHERE_MODELS_URL = 'https://api.cohere.com/v1/models'
28/** Public id of the synced `POST /v2/chat` schema. */
29const COHERE_CHAT_ENDPOINT = 'v2/chat'
30​
31/**
32 * Chat (v1/v2 + legacy generate/summarize) and embed. Audio transcriptions
33 * are generation; rerank/classify/datasets/finetune/batches/admin drop.
34 */
35function classify(path: string): Activity | null {
36 const bare = path.split('?')[0] ?? path
37 if (
38 bare === '/v1/chat' ||
39 bare === '/v2/chat' ||
40 bare === '/chat' ||
41 bare === '/v1/generate' ||
42 bare === '/v1/summarize'
43 ) {
44 return 'chat'
45 }
46 if (bare === '/v1/embed' || bare === '/v2/embed') return 'embeddings'
47 if (bare === '/v2/audio/transcriptions') return 'audio'
48 return null
50​
51async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
52 const { spec, hash } = await fetchOpenApi(COHERE_OPENAPI_URL)
53 return {
54 specs: [spec],
55 sources: [{ url: COHERE_OPENAPI_URL, hash }],
56 outputStrategy: 'post-200',
57 }
59​
60export interface CohereModel {
61 name?: string
62 is_deprecated?: boolean
63 endpoints?: Array<string>
64 context_length?: number
65 features?: Array<string> | null
67​
68interface CohereModelList {
69 models?: Array<CohereModel>
70 next_page_token?: string
72​
73function activityFromEndpoints(
74 endpoints: Array<string> | undefined,
75): Activity | null {
76 if (!endpoints?.length) return null
77 if (
78 endpoints.includes('chat') ||
79 endpoints.includes('generate') ||
80 endpoints.includes('summarize')
81 ) {
82 return 'chat'
83 }
84 if (endpoints.includes('embed')) return 'embeddings'
85 return null
87​
88/**
89 * Facts one listing row states. For a chat row `features` is the model's
90 * own list, so its flags are exact: every chat row binds the one `/v2/chat`
91 * body, and walking that would stamp `thinking` and `tools` on models that
92 * reject them. A row with no `features` states no flags and no modalities.
93 */
94export function listedFacts(m: CohereModel, rawId: string): ModelInfo {
95 const activity = activityFromEndpoints(m.endpoints)
96 const facts = openAiCompatModelFacts({
97 id: rawId,
98 context_length: m.context_length,
99 features: m.features ?? undefined,
100 })
101 const base: ModelInfo = {
102 rawId,
103 activity,
104 deprecated: m.is_deprecated ?? false,
105 ...facts,
106 }
107 if (activity !== 'chat') return base
108 const chat: ModelInfo = {
109 ...base,
110 exactCapabilities: true,
111 schemaEndpointId: m.endpoints?.includes('chat')
112 ? COHERE_CHAT_ENDPOINT
113 : null,
114 }
115 if (!m.features) return chat
116 const listed: Array<unknown> = Array.isArray(facts.capabilities)
117 ? facts.capabilities
118 : []
119 const flags = m.features.includes('logprobs')
120 ? [...listed, 'logprobs']
121 : listed
122 return {
123 ...chat,
124 ...(flags.length > 0 ? { capabilities: flags } : {}),
125 modalities: {
126 input: m.features.includes('vision') ? ['text', 'image'] : ['text'],
127 output: ['text'],
128 },
129 }
131​
132async function listModels(
133 env: ProviderSecrets,
134 kv?: KVNamespace,
135): Promise<ListModelsResult> {
136 const key = env.COHERE_API_KEY
137 if (!key) {
138 return { models: [], ...skippedResult('cohere', 'COHERE_API_KEY') }
139 }
140 const [docs, pricing, pages, reasoning] = await Promise.all([
141 cohereModelDocFacts(kv),
142 cohereModelPricing(kv),
143 cohereCommandPageFacts(kv),
144 cohereModelReasoning(kv),
145 ])
146 const models: ListModelsResult['models'] = []
147 let pageToken: string | undefined
148 do {
149 const url = new URL(COHERE_MODELS_URL)
150 url.searchParams.set('page_size', '1000')
151 if (pageToken) url.searchParams.set('page_token', pageToken)
152 const body = (await fetchJson(url.toString(), {
153 headers: { Authorization: `Bearer ${key}` },
154 signal: AbortSignal.timeout(30_000),
155 })) as CohereModelList
156 for (const m of body.models ?? []) {
157 if (typeof m.name !== 'string' || m.name.length === 0) continue
158 const listed = listedFacts(m, m.name)
159 const priced = pricing(m.name)
160 const page = pages(m.name)
161 // A pricing-page card stays sourced there. The model page fills a
162 // price only when that page is the one that states it.
163 const { pricing: pageCard, factSources: pageSources, ...pageRest } = page
164 const pagePatch =
165 priced.pricing || !pageCard
166 ? {
167 ...pageRest,
168 ...(pageSources?.knowledgeCutoff
169 ? {
170 factSources: {
171 knowledgeCutoff: pageSources.knowledgeCutoff,
172 },
173 }
174 : {}),
175 }
176 : page
177 models.push(
178 overlayModelFacts(
179 listed,
180 docs(m.name),
181 priced,
182 pagePatch,
183 reasoning(m.name, listsReasoning(listed.capabilities)),
184 ),
185 )
186 }
187 const next = body.next_page_token
188 pageToken = next && next !== pageToken ? next : undefined
189 } while (pageToken)
190 return { models }
192​
193export const provider: ProviderConfig = {
194 id: 'cohere',
195 // Cohere's Hugging Face org (`CohereLabs/command-a-vision-07-2025`).
196 modelNamespaces: ['CohereLabs'],
197 displayName: 'Cohere',
198 authEnvVar: 'COHERE_API_KEY',
199 specSourceUrl: COHERE_OPENAPI_URL,
200 modelsEndpoint: COHERE_MODELS_URL,
201 defaultDerivation: 'upstream-spec',
202 connect: bearerConnect('https://api.cohere.com'),
203 fetchSpec,
204 listModels,
205 classify,