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

byteplus.ts

549 lines17.8 KB

1/**
2 * BytePlus (ModelArk + Seed Speech) — SDK-generated specs, live models.
3 *
4 * BytePlus publishes no OpenAPI document: `/openapi.json`, `/swagger.json`
5 * and `/docs` on the Ark data plane all answer 200 with an EMPTY body (a
6 * catch-all, not a document — re-probed with a real key 2026-08-12), and the
7 * genuine per-action documents live behind the console's API Explorer, which
8 * needs an interactive login.
9 *
10 * It does, however, publish an official Go SDK whose model package declares
11 * the entire Ark data plane as `json:"…"`-tagged structs. Those are plain
12 * text, so `fetchSpec` pulls them from GitHub on the ordinary spec-sync cron
13 * and `byteplus-ark-build.ts` turns them into the Ark document — the spec
14 * tracks upstream SDK releases with no codegen step and no committed
15 * artifact. `byteplus-spec.ts` keeps the hand-ported document as the fallback
16 * for when GitHub is unreachable or the SDK is refactored past what the
17 * parser handles.
18 *
19 * Seed Speech appears in no BytePlus SDK in any language, so the voice
20 * document stays hand-written.
21 *
22 * The MODEL CATALOG is different: Ark's data-plane `GET /models` is a real,
23 * richly-typed source (created / task_type / token_limits / modalities /
24 * features / status), so `listModels` prefers it whenever `ARK_API_KEY` is
25 * set. Two things keep the curated catalog alive underneath it:
26 *
27 * 1. The listing is NOT exhaustive — `seedream-5-0-lite-260128` answers
28 * requests but is absent from it (confirmed live 2026-08-12).
29 * 2. Seed Speech (TTS/ASR) lives on a different host entirely and appears in
30 * no Ark listing.
31 *
32 * So the live rows win where they exist and the curated entries fill the
33 * gaps; with no key at all the provider still serves the curated catalog
34 * rather than reporting itself skipped.
35 */
36import type { Activity } from '#/db/schema.ts'
37import { errorMessage } from '#/server/errors.ts'
38import { contentHash } from '#/server/kv.ts'
39import {
40 ARK_GO_FILES,
41 ARK_GO_SOURCE_URL,
42 arkGoFileUrl,
43 buildArkSpecFromGo,
44} from './byteplus-ark-build.ts'
45import { byteplusModelPricing } from './byteplus-pricing.ts'
46import { docsReport, docsRun } from './model-facts.ts'
47import {
48 byteplusModelReasoning,
49 listsReasoning,
50 overlayModelFacts,
51} from './reasoning-config.ts'
52import { bearerConnect, headerApiKeyConnect } from './connect.ts'
53import {
54 BYTEPLUS_ARK_BASE_URL,
55 BYTEPLUS_ARK_DOCS_URL,
56 BYTEPLUS_VOICE_BASE_URL,
57 BYTEPLUS_VOICE_DOCS_URL,
58 bytePlusArkSpec,
59 bytePlusVoiceSpec,
60} from './byteplus-spec.ts'
61import { githubRequestInit } from './github.ts'
62import { byteplusGenerationEndpointId } from './model-meta.ts'
63import { byteplusIdSuffixDate } from './release-dates.ts'
64import { fetchJson, fetchText, sha256Text } from './types.ts'
65import type {
66 ListModelsResult,
67 ModelInfo,
68 OpenApiDocument,
69 ProviderConfig,
70 ProviderSecrets,
71 SpecFetchResult,
72 SpecSource,
73} from './types.ts'
74​
75const ARK_MODELS_URL = 'https://ark.ap-southeast.bytepluses.com/api/v3/models'
76​
77/**
78 * Both hosts' generation surfaces classify by exact path (the Ark and voice
79 * documents have no overlapping paths).
80 */
81function classify(path: string): Activity | null {
82 if (path === '/chat/completions') return 'chat'
83 if (path === '/images/generations') return 'image'
84 if (
85 path === '/contents/generations/tasks' ||
86 path === '/contents/generations/tasks/{id}'
87 ) {
88 return 'video'
89 }
90 if (path === '/tts/create' || path === '/auc/bigmodel/recognize/flash') {
91 return 'audio'
92 }
93 return null
95​
96/**
97 * Ark half: generated from BytePlus's Go SDK so it tracks upstream releases.
98 * Falls back to the embedded document — never to nothing — if GitHub is
99 * unreachable or the SDK is refactored beyond what the parser handles, so a
100 * bad upstream day degrades the spec's freshness rather than the service.
101 */
102async function fetchArkSpec(env: ProviderSecrets): Promise<{
103 spec: OpenApiDocument
104 source: SpecSource
105 warnings: Array<string>
106}> {
107 try {
108 const files = await Promise.all(
109 ARK_GO_FILES.map(async (name) => {
110 const url = arkGoFileUrl(name)
111 return {
112 name,
113 // Raw host: githubRequestInit leaves these unauthenticated.
114 text: await fetchText(url, githubRequestInit(url, env)),
115 }
116 }),
117 )
118 const { spec, warnings } = buildArkSpecFromGo(files)
119 return {
120 spec,
121 source: {
122 url: ARK_GO_SOURCE_URL,
123 // One document from many files: hash their concatenation in the
124 // fixed ARK_GO_FILES order so the digest is reproducible.
125 hash: await sha256Text(files.map((f) => f.text).join('')),
126 },
127 warnings,
128 }
129 } catch (error) {
130 const spec = bytePlusArkSpec()
131 return {
132 spec,
133 source: { url: BYTEPLUS_ARK_DOCS_URL, hash: await contentHash(spec) },
134 warnings: [
135 `byteplus: Go SDK spec generation failed (${errorMessage(error)}) — served the embedded Ark document instead`,
136 ],
137 }
138 }
140​
141async function fetchSpec(env: ProviderSecrets): Promise<SpecFetchResult> {
142 const ark = await fetchArkSpec(env)
143 // Seed Speech appears in no BytePlus SDK in any language, so the voice
144 // document stays hand-written; provenance hashes the document itself (the
145 // FAL embedded-spec precedent).
146 const voice = bytePlusVoiceSpec()
147 return {
148 specs: [ark.spec, voice],
149 sources: [
150 ark.source,
151 { url: BYTEPLUS_VOICE_DOCS_URL, hash: await contentHash(voice) },
152 ],
153 outputStrategy: 'post-200',
154 warnings: ark.warnings,
155 }
157​
158interface CuratedModel {
159 rawId: string
160 activity: Activity
161 contextWindow?: number
162 maxOutput?: number
163 input: Array<string>
164 output: Array<string>
165 capabilities?: unknown
167​
168const chat = (
169 rawId: string,
170 maxOutput: number,
171 capabilities: Array<string>,
172 input: Array<string> = ['text'],
173 contextWindow = 256_000,
174): CuratedModel => ({
175 rawId,
176 activity: 'chat',
177 contextWindow,
178 maxOutput,
179 input,
180 output: ['text'],
181 capabilities,
182})
183​
184const TIV = ['text', 'image', 'video']
185const TIVA = ['text', 'image', 'video', 'audio']
186const REASON_TOOLS = ['reasoning', 'tools', 'tool_choice']
187const REASON_TOOLS_SO = [
188 ...REASON_TOOLS,
189 'response_format',
190 'structured_outputs',
192​
193const video = (
194 rawId: string,
195 input: Array<string>,
196 output: Array<string>,
197 resolutions: Array<string>,
198 duration: { min: number; max: number },
199): CuratedModel => ({
200 rawId,
201 activity: 'video',
202 input,
203 output,
204 capabilities: { resolutions, duration },
205})
206​
207const image = (rawId: string, maxReferenceImages: number): CuratedModel => ({
208 rawId,
209 activity: 'image',
210 input: ['text', 'image'],
211 output: ['image'],
212 capabilities: { maxReferenceImages, sizeTokens: ['1K', '2K', '4K'] },
213})
214​
215/**
216 * Ported from `@tanstack/ai-byteplus` `model-meta.ts` (context windows,
217 * max-output, modalities, and the probed structured-output verdicts — the
218 * BytePlus capability tables are wrong in both directions, so the probe
219 * results are authoritative).
220 */
221const BYTEPLUS_MODELS: Array<CuratedModel> = [
222 // Chat (Seed / GLM / DeepSeek / gpt-oss on Ark)
223 chat('dola-seed-2-1-turbo-260628', 256_000, REASON_TOOLS_SO, TIV),
224 chat('seed-2-0-lite-260428', 128_000, REASON_TOOLS, TIVA),
225 chat('seed-2-0-mini-260428', 128_000, REASON_TOOLS, TIVA),
226 chat('seed-2-0-pro-260328', 128_000, REASON_TOOLS_SO, TIV),
227 chat('seed-2-0-lite-260228', 128_000, REASON_TOOLS_SO, TIV),
228 chat('seed-2-0-mini-260215', 128_000, REASON_TOOLS_SO, TIV),
229 chat('seed-2-0-code-preview-260328', 128_000, REASON_TOOLS, TIV),
230 chat('seed-1-8-251228', 64_000, REASON_TOOLS_SO, TIV),
231 chat('seed-1-6-250915', 32_000, REASON_TOOLS_SO, TIV),
232 chat('seed-1-6-250615', 32_000, REASON_TOOLS_SO, TIV),
233 chat('seed-1-6-flash-250715', 32_000, REASON_TOOLS_SO, TIV),
234 chat('seed-1-6-flash-250615', 32_000, REASON_TOOLS_SO, TIV),
235 chat('glm-5-2-260617', 128_000, REASON_TOOLS_SO, ['text'], 1_024_000),
236 chat('glm-4-7-251222', 128_000, REASON_TOOLS),
237 chat('deepseek-v4-pro-260425', 384_000, REASON_TOOLS, ['text'], 1_024_000),
238 chat('deepseek-v4-flash-260425', 384_000, REASON_TOOLS, ['text'], 1_024_000),
239 chat('deepseek-v3-2-251201', 32_000, REASON_TOOLS, ['text'], 128_000),
240 chat('gpt-oss-120b-250805', 64_000, ['reasoning'], ['text'], 128_000),
241 // Video (Seedance, async task API)
242 video(
243 'dreamina-seedance-2-5-260628',
244 TIVA,
245 ['video', 'audio'],
246 ['480p', '720p'],
247 { min: 4, max: 30 },
248 ),
249 video(
250 'dreamina-seedance-2-0-260128',
251 TIVA,
252 ['video', 'audio'],
253 ['480p', '720p', '1080p', '4k'],
254 { min: 4, max: 15 },
255 ),
256 video(
257 'dreamina-seedance-2-0-fast-260128',
258 TIVA,
259 ['video', 'audio'],
260 ['480p', '720p'],
261 { min: 4, max: 15 },
262 ),
263 video(
264 'dreamina-seedance-2-0-mini-260615',
265 TIVA,
266 ['video', 'audio'],
267 ['480p', '720p'],
268 { min: 4, max: 15 },
269 ),
270 video(
271 'seedance-1-5-pro-251215',
272 ['text', 'image'],
273 ['video', 'audio'],
274 ['480p', '720p', '1080p'],
275 { min: 4, max: 12 },
276 ),
277 video(
278 'seedance-1-0-pro-250528',
279 ['text', 'image'],
280 ['video'],
281 ['480p', '720p', '1080p'],
282 { min: 2, max: 12 },
283 ),
284 video(
285 'seedance-1-0-pro-fast-251015',
286 ['text', 'image'],
287 ['video'],
288 ['480p', '720p', '1080p'],
289 { min: 2, max: 12 },
290 ),
291 // Image (Seedream)
292 image('dola-seedream-5-0-pro-260628', 10),
293 image('seedream-5-0-260128', 14),
294 image('seedream-5-0-lite-260128', 14),
295 image('seedream-4-5-251128', 14),
296 image('seedream-4-0-250828', 14),
297 // Seed Speech (voice host — separate product and API key)
298 {
299 rawId: 'seed-audio-1.0',
300 activity: 'audio',
301 input: ['text', 'audio'],
302 output: ['audio'],
303 },
304 {
305 rawId: 'seed-asr',
306 activity: 'audio',
307 input: ['audio'],
308 output: ['text'],
309 },
311​
312function curatedModels(): Array<ModelInfo> {
313 return BYTEPLUS_MODELS.map((m) => ({
314 rawId: m.rawId,
315 activity: m.activity,
316 contextWindow: m.contextWindow ?? null,
317 maxOutput: m.maxOutput ?? null,
318 modalities: { input: m.input, output: m.output },
319 // A chat row's list is flags; an image or video row's object is the
320 // provider's own description of the model.
321 ...(Array.isArray(m.capabilities)
322 ? { capabilities: m.capabilities }
323 : m.capabilities
324 ? { providerMetadata: m.capabilities as Record<string, unknown> }
325 : {}),
326 // Dated ids embed their release as a -YYMMDD suffix; the undated Seed
327 // Speech ids keep their poll-time firstSeenAt.
328 releasedAt: byteplusIdSuffixDate(m.rawId),
329 }))
331​
332/**
333 * Ark reports one or more `task_type`s per model. Highest-precedence match
334 * wins: a chat model that also accepts audio input carries `SpeechToText`
335 * alongside `TextGeneration` (e.g. seed-2-0-lite-260428) and must classify as
336 * `chat`, not `audio`, so the generation task types are checked first.
337 * 3D-generation models carry no task_type at all and fall through to null —
338 * the same treatment FAL's `text-to-3d` gets until the taxonomy grows.
339 */
340const ARK_TASK_ACTIVITIES: Array<[Activity, Array<string>]> = [
341 [
342 'video',
343 [
344 'TextToVideo',
345 'ImageToVideo',
346 'MultimodalToVideo',
347 'VideoEditing',
348 'VideoExtension',
349 ],
350 ],
351 ['image', ['TextToImage', 'ImageToImage']],
352 ['embeddings', ['TextEmbedding', 'ImageEmbedding', 'MultimodalEmbedding']],
353 ['chat', ['TextGeneration', 'VisualQuestionAnswering']],
354 ['audio', ['SpeechToText', 'TextToSpeech']],
356​
357export function arkTaskActivity(
358 taskTypes: Array<string> | undefined,
359): Activity | null {
360 if (!taskTypes?.length) return null
361 for (const [activity, types] of ARK_TASK_ACTIVITIES) {
362 if (taskTypes.some((t) => types.includes(t))) return activity
363 }
364 return null
366​
367interface ArkModel {
368 id: string
369 name?: string
370 created?: number
371 /** Absent for live models; 'Shutdown' / 'Retiring' once wound down. */
372 status?: string
373 domain?: string
374 task_type?: Array<string>
375 modalities?: {
376 input_modalities?: Array<string>
377 output_modalities?: Array<string>
378 }
379 token_limits?: {
380 context_window?: number
381 max_input_token_length?: number
382 max_output_token_length?: number
383 max_reasoning_token_length?: number
384 }
385 features?: Record<string, unknown>
386 version?: string
388​
389/**
390 * Ark's `features.structured_outputs.json_schema` is NOT reliable: probed
391 * 2026-08-12, `seed-2-0-lite-260428` advertises `json_schema: true` and then
392 * answers a schema-bearing request with
393 * `400 InvalidParameter … json_schema is not supported by this model`, while
394 * `seed-2-0-lite-260228` (same family) accepts one. Both outcomes match
395 * TanStack AI's 2026-07-31 sweep of all 18 chat models, so their probe
396 * verdicts are carried here as a separate, clearly-labelled capability rather
397 * than letting the upstream flag stand alone. Ids outside this set get no
398 * verdict (absence ≠ unsupported).
399 */
400const PROBED_STRUCTURED_OUTPUT: Record<string, boolean> = {
401 'dola-seed-2-1-turbo-260628': true,
402 'seed-2-0-pro-260328': true,
403 'seed-2-0-lite-260228': true,
404 'seed-2-0-mini-260215': true,
405 'seed-1-8-251228': true,
406 'seed-1-6-250915': true,
407 'seed-1-6-250615': true,
408 'seed-1-6-flash-250715': true,
409 'seed-1-6-flash-250615': true,
410 'glm-5-2-260617': true,
411 'seed-2-0-lite-260428': false,
412 'seed-2-0-mini-260428': false,
413 'seed-2-0-code-preview-260328': false,
414 'deepseek-v4-pro-260425': false,
415 'deepseek-v4-flash-260425': false,
416 'deepseek-v3-2-251201': false,
417 'gpt-oss-120b-250805': false,
418 // Accepts the request with 200 but ignores the schema and answers in prose
419 // — a status-code-only probe reads this as support.
420 'glm-4-7-251222': false,
422​
423interface ArkFeatures {
424 structured_outputs?: { json_object?: boolean; json_schema?: boolean }
425 tools?: { function_calling?: boolean }
427​
428/**
429 * Chat rows speak the shared OpenRouter parameter vocabulary (#53, #76).
430 * The probe verdict beats Ark's `json_schema` flag whenever one exists.
431 */
432export function arkChatCapabilities(m: ArkModel): Array<string> {
433 const features = (m.features ?? {}) as ArkFeatures
434 const caps: Array<string> = []
435 if (features.tools?.function_calling) caps.push('tools', 'tool_choice')
436 if ((m.token_limits?.max_reasoning_token_length ?? 0) > 0) {
437 caps.push('reasoning')
438 }
439 const structured =
440 PROBED_STRUCTURED_OUTPUT[m.id] ??
441 features.structured_outputs?.json_schema === true
442 if (structured || features.structured_outputs?.json_object) {
443 caps.push('response_format')
444 }
445 if (structured) caps.push('structured_outputs')
446 return caps
448​
449function toModelInfo(m: ArkModel): ModelInfo {
450 const probed = PROBED_STRUCTURED_OUTPUT[m.id]
451 const activity = arkTaskActivity(m.task_type)
452 return {
453 rawId: m.id,
454 displayName: m.name ?? null,
455 activity,
456 contextWindow: m.token_limits?.context_window ?? null,
457 maxOutput: m.token_limits?.max_output_token_length ?? null,
458 modalities: {
459 input: m.modalities?.input_modalities,
460 output: m.modalities?.output_modalities,
461 },
462 ...(activity === 'chat'
463 ? { capabilities: arkChatCapabilities(m) }
464 : {
465 providerMetadata: {
466 ...m.features,
467 taskType: m.task_type,
468 domain: m.domain || undefined,
469 maxReasoningTokens: m.token_limits?.max_reasoning_token_length,
470 // Distinct key from the upstream `structured_outputs` block
471 // above so the disagreement stays visible.
472 ...(probed === undefined ? {} : { structuredOutputProbed: probed }),
473 },
474 }),
475 // 'Retiring' models still serve but are on the way out; both states are
476 // deprecation signals for consumers picking a model today.
477 deprecated: m.status === 'Shutdown' || m.status === 'Retiring',
478 releasedAt: m.created ?? byteplusIdSuffixDate(m.id),
479 }
481​
482async function listModels(
483 env: ProviderSecrets,
484 kv?: KVNamespace,
485): Promise<ListModelsResult> {
486 const docs = docsRun()
487 const [pricing, reasoning] = await Promise.all([
488 byteplusModelPricing(docs, kv),
489 byteplusModelReasoning(kv),
490 ])
491 const withPricing = (models: Array<ModelInfo>): Array<ModelInfo> =>
492 models.map((model) =>
493 overlayModelFacts(
494 model,
495 pricing(model.rawId),
496 reasoning(model.rawId, listsReasoning(model.capabilities)),
497 ),
498 )
499 const key = env.ARK_API_KEY
500 // No key: the embedded catalog is still a real answer, so serve it rather
501 // than reporting the provider skipped.
502 if (!key) {
503 return {
504 models: withPricing(curatedModels()),
505 docsFailures: docsReport(docs),
506 }
507 }
508​
509 const body = (await fetchJson(ARK_MODELS_URL, {
510 headers: { Authorization: `Bearer ${key}` },
511 })) as { data?: Array<ArkModel> }
512 const live = (body.data ?? []).map(toModelInfo)
513​
514 // Curated entries the listing omits: Seed Speech (different host) and ids
515 // Ark serves but does not enumerate.
516 const liveIds = new Set(live.map((m) => m.rawId))
517 const gapFillers = curatedModels().filter((m) => !liveIds.has(m.rawId))
518 return {
519 models: withPricing([...live, ...gapFillers]),
520 docsFailures: docsReport(docs),
521 }
523​
524export const byteplusProvider: ProviderConfig = {
525 id: 'byteplus',
526 displayName: 'BytePlus',
527 // Optional, not required: it upgrades the model catalog from embedded to
528 // live. fetchSpec never needs it, and listModels degrades to the curated
529 // catalog without it.
530 authEnvVar: 'ARK_API_KEY',
531 // Overridden per operation: the generated Ark document stamps
532 // 'generated', and the Seed Speech document stamps its own verified
533 // status. This default only applies if a marker is ever missing.
534 defaultDerivation: 'probe-verified',
535 specGrain: 'provider',
536 // Default document is Ark. Seed Speech (`?activity=audio`) uses a
537 // different host and X-Api-Key — a combined profile would send Bearer
538 // to the voice host.
539 connect: bearerConnect(BYTEPLUS_ARK_BASE_URL, 'Ark'),
540 connectByActivity: {
541 audio: headerApiKeyConnect(BYTEPLUS_VOICE_BASE_URL, 'X-Api-Key'),
542 },
543 fetchSpec,
544 listModels,
545 classify,
546 classifyGets: true,
547 generationEndpointId: ({ rawId, activity }) =>
548 byteplusGenerationEndpointId(rawId, activity),