Open History to see the last commit
1/**
2 * Together AI — public OpenAPI 3.1 at docs.together.ai/openapi.yaml.
3 * Generation: chat/completions, embeddings, images, video, audio.
4 * Platform/admin (files, fine-tunes, endpoints, batches, rerank) classify
5 * null. listModels requires TOGETHER_API_KEY; Together returns a bare array.
6 */
7import {
8 togetherNativeThinking,
9 applyTogetherNativeThinking,
10} from '../together-native-thinking.ts'
11import { compileTokenCard } from '@modelschemas/rate-card'
12
13import type { Activity } from '#/db/schema.ts'
14import { docsReport, docsRun, tryDocs } from '../model-facts.ts'
15import {
16 TOGETHER_REASONING_QUICKSTARTS,
17 TOGETHER_REASONING_URL,
18 applyTogetherDocs,
19 loadTogetherQuickstart,
20 loadTogetherReasoningPage,
21 togetherGptOssFamilyMatches,
22 togetherNamedHybridMatches,
23 loadTogetherServerlessChat,
24 reasoningHit,
25 supportedFactSources,
26} from '../together-facts.ts'
27import { togetherMediaPricing } from '../together-pricing.ts'
28import { fetchJson, fetchOpenApi, sha256Text, skippedResult } from '../types.ts'
29import { bearerConnect } from '../connect.ts'
30import type { RateCard } from '@modelschemas/rate-card'
31import type {
32 FactSource,
33 ListModelsResult,
34 ModelFactSources,
35 ModelInfo,
36 ProviderConfig,
37 ProviderSecrets,
38 SpecFetchResult,
39} from '../types.ts'
40
41const TOGETHER_OPENAPI_URL = 'https://docs.together.ai/openapi.yaml'
42const TOGETHER_MODELS_URL = 'https://api.together.xyz/v1/models'
43const TOGETHER_SUPPORTED_URL = 'https://api.together.ai/v2/supported-models'
44
45const MODEL_TYPE_ACTIVITY: Record<string, Activity> = {
46 chat: 'chat',
47 language: 'chat',
48 code: 'chat',
49 image: 'image',
50 video: 'video',
51 audio: 'audio',
52 embedding: 'embeddings',
53 embeddings: 'embeddings',
54 moderation: 'moderation',
55}
56
57function barePath(path: string): string {
58 return path.replace(/^\/v\d+/, '')
59}
60
61const TOGETHER_MODALITY: Record<string, string> = {
62 MODALITY_TEXT: 'text',
63 MODALITY_IMAGE: 'image',
64 MODALITY_AUDIO: 'audio',
65 MODALITY_VIDEO: 'video',
66}
67
68const TOGETHER_FEATURES: Record<string, Array<string>> = {
69 FEATURE_TOOL_CALLING: ['tools'],
70 FEATURE_STRUCTURED_OUTPUT: ['structured_outputs', 'response_format'],
71 FEATURE_REASONING: ['reasoning'],
72}
73
74function togetherModalities(values: Array<string> | undefined): Array<string> {
75 return (values ?? []).flatMap((value) =>
76 TOGETHER_MODALITY[value] ? [TOGETHER_MODALITY[value]] : [],
77 )
78}
79
80interface TogetherSupportedModel {
81 name?: string
82 inputModalities?: Array<string>
83 outputModalities?: Array<string>
84 features?: Array<string>
85}
86
87/** Page through v2 supported-models. `name` matches a v1 catalog id. */
88async function togetherSupportedFacts(
89 key: string,
90): Promise<
91 Map<string, Pick<ModelInfo, 'modalities' | 'capabilities' | 'factSources'>>
92> {
93 const facts = new Map<
94 string,
95 Pick<ModelInfo, 'modalities' | 'capabilities' | 'factSources'>
96 >()
97 let after: string | undefined
98 for (let page = 0; page < 20; page += 1) {
99 const url = new URL(TOGETHER_SUPPORTED_URL)
100 url.searchParams.set('limit', '100')
101 if (after) url.searchParams.set('after', after)
102 const body = (await fetchJson(url.toString(), {
103 headers: { Authorization: `Bearer ${key}` },
104 })) as { data?: Array<TogetherSupportedModel>; next_cursor?: string | null }
105 for (const row of body.data ?? []) {
106 if (!row.name) continue
107 const input = togetherModalities(row.inputModalities)
108 const output = togetherModalities(row.outputModalities)
109 const capabilities = (row.features ?? []).flatMap(
110 (feature) => TOGETHER_FEATURES[feature] ?? [],
111 )
112 const modalities =
113 input.length > 0 || output.length > 0 ? { input, output } : null
114 facts.set(row.name, {
115 ...(modalities ? { modalities } : {}),
116 ...(capabilities.length > 0 ? { capabilities } : {}),
117 factSources: supportedFactSources({
118 ...(modalities ? { modalities } : {}),
119 ...(capabilities.length > 0 ? { capabilities } : {}),
120 }),
121 })
122 }
123 if (!body.next_cursor) break
124 after = body.next_cursor
125 }
126 return facts
127}
128
129function classify(path: string): Activity | null {
130 const bare = barePath(path)
131 if (bare === '/chat/completions' || bare === '/completions') return 'chat'
132 if (bare === '/embeddings') return 'embeddings'
133 if (bare === '/images/generations') return 'image'
134 if (bare === '/videos') return 'video'
135 if (
136 bare === '/audio/speech' ||
137 bare === '/audio/transcriptions' ||
138 bare === '/audio/translations'
139 ) {
140 return 'audio'
141 }
142 return null
143}
144
145async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
146 const { spec, hash } = await fetchOpenApi(TOGETHER_OPENAPI_URL)
147 return {
148 specs: [spec],
149 sources: [{ url: TOGETHER_OPENAPI_URL, hash }],
150 outputStrategy: 'post-200',
151 }
152}
153
154function isRecord(value: unknown): value is Record<string, unknown> {
155 return value !== null && typeof value === 'object' && !Array.isArray(value)
156}
157
158function asModels(body: unknown): Array<Record<string, unknown>> {
159 if (Array.isArray(body)) {
160 return body.filter((item): item is Record<string, unknown> =>
161 isRecord(item),
162 )
163 }
164 if (isRecord(body) && Array.isArray(body.data)) {
165 return body.data.filter((item): item is Record<string, unknown> =>
166 isRecord(item),
167 )
168 }
169 return []
170}
171
172/**
173 * Together prices per million tokens on the listing (`{ input: 0.88,
174 * output: 0.88, cached_input: 0.2, hourly: 0, base: 0, finetune: 0 }`).
175 * An all-zero object is a model it does not quote per token (dedicated
176 * endpoints, or no published serverless rate) — unknown, not free, so it
177 * compiles to null rather than a $0 card. `hourly`/`base`/`finetune` are
178 * dedicated-endpoint and training rates, not per-request levers. A zero
179 * `cached_input` is unpublished, not a free cache read. Image, video, and
180 * audio prices come from the serverless catalog, not this token object.
181 */
182export async function togetherRateCard(
183 pricing: unknown,
184): Promise<RateCard | null> {
185 if (!isRecord(pricing)) return null
186 const perToken = (key: string): number | null =>
187 typeof pricing[key] === 'number' ? pricing[key] / 1e6 : null
188 const rates: Record<string, number> = {}
189 const input = perToken('input')
190 const output = perToken('output')
191 const cached = perToken('cached_input')
192 if (input !== null) rates.input_tokens = input
193 if (output !== null) rates.output_tokens = output
194 if (cached !== null && cached > 0) rates.cache_read_tokens = cached
195 return compileTokenCard(rates, [], {
196 url: TOGETHER_MODELS_URL,
197 hash: await sha256Text(JSON.stringify(pricing)),
198 extractedAt: new Date().toISOString(),
199 })
200}
201
202const MEDIA_ACTIVITIES = new Set(['image', 'video', 'audio'])
203
204function listingFact(path: string): FactSource {
205 return { derivation: 'listing', sourceUrl: TOGETHER_MODELS_URL, path }
206}
207
208function positiveNumber(value: unknown): number | null {
209 return typeof value === 'number' && Number.isFinite(value) && value > 0
210 ? value
211 : null
212}
213
214function mergeSources(
215 base: ModelFactSources | undefined,
216 extra: ModelFactSources | undefined,
217): ModelFactSources | undefined {
218 if (!extra) return base
219 const capabilities =
220 base?.capabilities || extra.capabilities
221 ? { ...base?.capabilities, ...extra.capabilities }
222 : undefined
223 const merged: ModelFactSources = { ...base, ...extra }
224 if (capabilities) merged.capabilities = capabilities
225 else delete merged.capabilities
226 return merged
227}
228
229async function listModels(
230 env: ProviderSecrets,
231 kv?: KVNamespace,
232): Promise<ListModelsResult> {
233 const key = env.TOGETHER_API_KEY
234 if (!key) {
235 return { models: [], ...skippedResult('together', 'TOGETHER_API_KEY') }
236 }
237 const body = await fetchJson(TOGETHER_MODELS_URL, {
238 headers: { Authorization: `Bearer ${key}` },
239 })
240 const rows = asModels(body).flatMap((item) => {
241 if (typeof item.id !== 'string' || item.id.length === 0) return []
242 const type = item.type
243 const activity =
244 typeof type === 'string' ? (MODEL_TYPE_ACTIVITY[type] ?? null) : null
245 return [{ item, activity }]
246 })
247 const media = rows.some((row) =>
248 row.activity ? MEDIA_ACTIVITIES.has(row.activity) : false,
249 )
250 ? await togetherMediaPricing(kv)
251 : null
252 const models: Array<ModelInfo> = []
253 for (const { item, activity } of rows) {
254 const contextWindow = positiveNumber(item.context_length)
255 const config = isRecord(item.config) ? item.config : null
256 const maxOutput = positiveNumber(config?.max_output_length)
257 const factSources: ModelFactSources = {}
258 if (contextWindow != null) {
259 factSources.contextWindow = listingFact('context_length')
260 }
261 if (maxOutput != null)
262 factSources.maxOutput = listingFact('config.max_output_length')
263 const model: ModelInfo = {
264 rawId: item.id as string,
265 requestMap: null,
266 displayName:
267 typeof item.display_name === 'string' ? item.display_name : null,
268 activity,
269 contextWindow,
270 maxOutput,
271 releasedAt: typeof item.created === 'number' ? item.created : null,
272 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
273 }
274 if (media && activity && MEDIA_ACTIVITIES.has(activity)) {
275 const priced = media(item.id as string, activity)
276 Object.assign(model, priced)
277 // The catalog was read and rates no price for this row, so a card
278 // stored from the listing's token object is stale (issue #258).
279 if (!priced.pricing) model.absent = { pricing: 'cleared' }
280 } else {
281 const card = await togetherRateCard(item.pricing)
282 if (card) {
283 model.pricing = card
284 model.factSources = {
285 ...model.factSources,
286 pricing: listingFact('pricing'),
287 }
288 }
289 }
290 models.push(model)
291 }
292 const nativeThinking = models.some((model) => model.activity === 'chat')
293 ? await togetherNativeThinking(kv)
294 : []
295 const supported = await togetherSupportedFacts(key)
296 const docs = docsRun()
297 const [chatDocs, reasoningPage, quickstarts] = await Promise.all([
298 tryDocs(
299 docs,
300 'https://docs.together.ai/docs/serverless/models.md',
301 (cached) => loadTogetherServerlessChat(kv, cached),
302 ),
303 tryDocs(docs, TOGETHER_REASONING_URL, (cached) =>
304 loadTogetherReasoningPage(kv, cached),
305 ),
306 Promise.all(
307 TOGETHER_REASONING_QUICKSTARTS.map((url) =>
308 tryDocs(docs, url, (cached) => loadTogetherQuickstart(kv, cached, url)),
309 ),
310 ),
311 ])
312 const reasoning = new Map<string, ReturnType<typeof reasoningHit>>()
313 if (reasoningPage) {
314 for (const [id, mode] of Object.entries(reasoningPage.byId)) {
315 reasoning.set(
316 id,
317 reasoningHit(mode, TOGETHER_REASONING_URL, reasoningPage.hash),
318 )
319 }
320 if (reasoningPage.gptOssFamily) {
321 for (const model of models) {
322 if (
323 model.activity !== 'chat' ||
324 !togetherGptOssFamilyMatches(model.displayName ?? null) ||
325 reasoning.has(model.rawId)
326 )
327 continue
328 reasoning.set(
329 model.rawId,
330 reasoningHit(
331 reasoningPage.gptOssFamily,
332 TOGETHER_REASONING_URL,
333 reasoningPage.hash,
334 reasoningPage.familyThinking.effort,
335 ),
336 )
337 }
338 }
339 if (reasoningPage.namedHybrid) {
340 for (const model of models) {
341 if (
342 model.activity !== 'chat' ||
343 !togetherNamedHybridMatches(
344 model.rawId,
345 reasoningPage.namedHybrid.nativeBasename,
346 ) ||
347 reasoning.has(model.rawId)
348 )
349 continue
350 reasoning.set(
351 model.rawId,
352 reasoningHit(
353 reasoningPage.namedHybrid.reasoning,
354 TOGETHER_REASONING_URL,
355 reasoningPage.hash,
356 reasoningPage.familyThinking.hybrid,
357 ),
358 )
359 }
360 }
361 }
362 TOGETHER_REASONING_QUICKSTARTS.forEach((url, index) => {
363 const page = quickstarts[index]
364 if (!page) return
365 for (const [id, mode] of Object.entries(page.byId)) {
366 reasoning.set(id, reasoningHit(mode, url, page.hash))
367 }
368 })
369 const pageMeta = reasoningPage
370 ? { loaded: true, hash: reasoningPage.hash }
371 : { loaded: false, hash: '' }
372 return {
373 models: models.map((model) => {
374 const extra = supported.get(model.rawId)
375 const withSupported: ModelInfo = {
376 ...model,
377 ...(extra?.modalities ? { modalities: extra.modalities } : {}),
378 ...(extra?.capabilities ? { capabilities: extra.capabilities } : {}),
379 }
380 const merged = mergeSources(model.factSources, extra?.factSources)
381 if (merged) withSupported.factSources = merged
382 return applyTogetherNativeThinking(
383 applyTogetherDocs(
384 withSupported,
385 chatDocs,
386 reasoning,
387 pageMeta.loaded ? pageMeta : null,
388 ),
389 nativeThinking,
390 )
391 }),
392 docsFailures: docsReport(docs),
393 }
394}
395
396export const provider: ProviderConfig = {
397 id: 'together',
398 // LLM Gateway route name (providers[].providerId).
399 modelNamespaces: ['together-ai'],
400 displayName: 'Together AI',
401 authEnvVar: 'TOGETHER_API_KEY',
402 specSourceUrl: TOGETHER_OPENAPI_URL,
403 modelsEndpoint: TOGETHER_MODELS_URL,
404 defaultDerivation: 'upstream-spec',
405 connect: bearerConnect('https://api.together.ai'),
406 fetchSpec,
407 listModels,
408 classify,
409 // The shared chat body publishes `reasoning` and `reasoning_effort` for
410 // every model on the route. Together only states those per model.
411 perModelSchemaFlags: ['reasoning', 'reasoning_effort'],
412 generationEndpointId: ({ activity }) => {
413 switch (activity) {
414 case 'chat':
415 return 'chat/completions'
416 case 'embeddings':
417 return 'embeddings'
418 case 'image':
419 return 'images/generations'
420 case 'video':
421 return 'videos'
422 case 'audio':
423 return 'audio/speech'
424 default:
425 return null
426 }
427 },
428}