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

together.ts

424 lines13.5 KB

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