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

together.ts

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