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