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

byteplus-ark-build.ts

388 lines17.3 KB

1/**
2 * Builds the BytePlus Ark OpenAPI document from BytePlus's own Go SDK at sync
3 * time, so the spec tracks upstream SDK releases instead of being frozen at
4 * whatever was hand-ported.
5 *
6 * `service/arkruntime/model/*.go` declares the whole Ark data plane as structs
7 * with `json:"…"` tags; `go-struct-parser.ts` turns those into component
8 * schemas, and this module maps them onto HTTP paths and re-applies the
9 * curated knowledge the SDK cannot express.
10 *
11 * **Two things the SDK does not carry**, both preserved here rather than
12 * regressed away:
13 *
14 * 1. A handful of request fields Ark accepts that the Go structs omit
15 * (`reasoning_effort`, `top_k` and `seed` on chat; `stream` and
16 * `layer_decomposition` on images;
17 * `output_format` on video). These are listed explicitly in
18 * {@link ARK_CURATED_PROPERTIES} — an explicit list, not a blanket merge of
19 * the old static document, so that a field genuinely REMOVED upstream
20 * disappears from our spec instead of being resurrected forever.
21 * 2. Field descriptions. Go doc comments are sparse, while the hand-written
22 * ones carry probe findings that matter to callers (Seedream's `watermark`
23 * defaults to true, generated URLs expire in 24h, `max_tokens` and
24 * `max_completion_tokens` are mutually exclusive, …). Curated descriptions
25 * win wherever they exist.
26 *
27 * Endpoint→type mapping is hand-maintained: the SDK's model package has no
28 * notion of HTTP paths (those are consts over in the client package), and
29 * which struct serves which route is not mechanically derivable. Paths change
30 * rarely; field sets change often — so the rarely-changing half is pinned and
31 * the fast-moving half is generated.
32 */
33import { parseGoSchemas } from './go-struct-parser.ts'
34import type { GoSourceFile, JsonSchema } from './go-struct-parser.ts'
35import { PROVENANCE_MARKER } from './types.ts'
36import type { OpenApiDocument } from './types.ts'
37​
38export const BYTEPLUS_ARK_BASE_URL =
39 'https://ark.ap-southeast.bytepluses.com/api/v3'
40​
41/** Default branch of `byteplus-sdk/byteplus-go-sdk-v2`. */
42const GO_SDK_REF = 'main'
43const GO_SDK_REPO = 'byteplus-sdk/byteplus-go-sdk-v2'
44const GO_MODEL_DIR = 'service/arkruntime/model'
45​
46/**
47 * The model-package files reachable from our endpoint roots. Fetched in this
48 * order; the provenance hash covers their concatenation.
49 */
50export const ARK_GO_FILES = [
51 'chat_completion.go',
52 'images.go',
53 'content_generation.go',
54 'common.go',
55] as const
56​
57export function arkGoFileUrl(file: string): string {
58 return `https://raw.githubusercontent.com/${GO_SDK_REPO}/${GO_SDK_REF}/${GO_MODEL_DIR}/${file}`
60​
61/** Human-facing provenance URL for the directory the schemas came from. */
62export const ARK_GO_SOURCE_URL = `https://github.com/${GO_SDK_REPO}/tree/${GO_SDK_REF}/${GO_MODEL_DIR}`
63​
64interface ArkEndpoint {
65 path: string
66 method?: 'post' | 'get' | 'delete'
67 operationId: string
68 summary: string
69 /** Body schema. GETs and DELETEs use `pathParam` instead. */
70 requestType?: string
71 pathParam?: { name: string; description: string }
72 /** Omitted when the call has no response body (task cancel). */
73 responseType?: string
74 responseDescription: string
76​
77/**
78 * `ChatCompletionRequest` (the legacy struct) is deliberately NOT used —
79 * upstream marks it deprecated and it lacks `thinking`,
80 * `parallel_tool_calls` and `max_completion_tokens`.
81 */
82const ARK_ENDPOINTS: Array<ArkEndpoint> = [
83 {
84 path: '/chat/completions',
85 operationId: 'createChatCompletion',
86 summary:
87 'Chat completion (Seed / GLM / DeepSeek / gpt-oss) — OpenAI-compatible plus thinking, reasoning_effort, repetition_penalty and service_tier',
88 requestType: 'CreateChatCompletionRequest',
89 responseType: 'ChatCompletionResponse',
90 responseDescription: 'Completion',
91 },
92 {
93 path: '/images/generations',
94 operationId: 'createImageGeneration',
95 summary: 'Generate or edit images with Seedream',
96 requestType: 'GenerateImagesRequest',
97 responseType: 'ImagesResponse',
98 responseDescription: 'Generated images',
99 },
100 {
101 path: '/contents/generations/tasks',
102 operationId: 'createContentsGenerationsTask',
103 summary:
104 'Open a Seedance video generation task (async — poll GET /contents/generations/tasks/{id} for the result)',
105 requestType: 'CreateContentGenerationTaskRequest',
106 responseType: 'CreateContentGenerationTaskResponse',
107 responseDescription: 'Task acknowledgment',
108 },
109 {
110 path: '/contents/generations/tasks/{id}',
111 method: 'get',
112 operationId: 'getContentsGenerationsTask',
113 summary:
114 'Retrieve a Seedance video task. Poll until status is succeeded, then download content.video_url (valid 24 hours; the task record is kept 7 days).',
115 pathParam: {
116 name: 'id',
117 description:
118 'Task id from POST /contents/generations/tasks. You can query records from the past 7 days.',
119 },
120 responseType: 'GetContentGenerationTaskResponse',
121 responseDescription:
122 'Task record. content.video_url is the file once status is succeeded.',
123 },
124 {
125 path: '/contents/generations/tasks/{id}',
126 method: 'delete',
127 operationId: 'deleteContentsGenerationsTask',
128 summary:
129 'Cancel a Seedance video task. The Go SDK calls DELETE and reads no response body.',
130 pathParam: {
131 name: 'id',
132 description:
133 'Task id from POST /contents/generations/tasks. Records from the past 7 days can be cancelled.',
134 },
135 responseDescription: 'The task is cancelled. The response has no body.',
136 },
138​
139/**
140 * Request fields Ark accepts that the Go SDK's structs do not declare, keyed
141 * by the schema they belong to. Each description says where it is from:
142 * TanStack AI's 2026-07-31 probe sweep or Ark's API doc. The SDK lags.
143 */
144const ARK_CURATED_PROPERTIES: Record<string, Record<string, JsonSchema>> = {
145 CreateChatCompletionRequest: {
146 reasoning_effort: {
147 type: 'string',
148 enum: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
149 description:
150 "Reasoning budget hint. 'none' and 'xhigh' are only accepted by glm-5-2-260617; 'max' by glm-5-2-260617 and the deepseek-v4-* models. Rejected in combination with thinking: {type: 'disabled'}. Absent from the Go SDK; probe-verified 2026-07-31.",
151 },
152 top_k: {
153 type: 'integer',
154 description:
155 'Restricts sampling to the k most likely tokens. Absent from the Go SDK; probe-verified 2026-07-31.',
156 },
157 seed: {
158 type: 'integer',
159 description:
160 'Best-effort determinism hint for repeated identical requests. Absent from the Go SDK; probe-verified 2026-07-31.',
161 },
162 },
163 GenerateImagesRequest: {
164 stream: {
165 type: 'boolean',
166 description:
167 'Server-sent-events mode, emitting each image as it finishes. Absent from the Go SDK request struct, which models the unary call only.',
168 },
169 layer_decomposition: {
170 type: 'boolean',
171 description:
172 'Layer decomposition (Seedream 5.0 pro and flash): true splits the single input `image` into a base image plus up to 16 PNG layers. Server default false. Absent from the Go SDK; from the Image generation API doc (docs.byteplus.com/en/docs/ModelArk/1541523).',
173 },
174 },
175 CreateContentGenerationTaskRequest: {
176 output_format: {
177 type: 'string',
178 description:
179 'Container of the generated video, e.g. mp4 or mov. Absent from the Go SDK request struct but returned on the task record and accepted on create.',
180 },
181 },
183​
184/**
185 * Curated field descriptions, keyed by schema then wire field name. These
186 * carry behaviour a type declaration cannot state, so they override the Go
187 * doc comment whenever both exist.
188 */
189const ARK_CURATED_DESCRIPTIONS: Record<string, Record<string, string>> = {
190 CreateChatCompletionRequest: {
191 model:
192 'Ark model id (e.g. seed-2-0-lite-260428) or a preconfigured endpoint id.',
193 max_tokens:
194 'Maximum tokens to generate. Mutually exclusive with max_completion_tokens — sending both is a 400.',
195 max_completion_tokens:
196 "OpenAI's newer name for max_tokens; mutually exclusive with it.",
197 repetition_penalty:
198 'Penalty applied to repeated tokens. Values above 1 discourage repetition.',
199 service_tier:
200 "'flex' routes to the batch queue at a lower price with no latency guarantee; 'default' is the standard online tier.",
201 thinking:
202 "Reasoning ('deep thinking') switch. 'enabled' is the default on every model except deepseek-v3-2-251201; 'auto' is only accepted by gpt-oss-120b-250805. Cannot be combined with reasoning_effort when disabled (400 InvalidParameter).",
203 response_format:
204 "Structured output. Only {type: 'json_schema'} works, and only on a subset of models — Ark's own features.structured_outputs flag is unreliable (seed-2-0-lite-260428 advertises support and then 400s). Probe-verified accepting: dola-seed-2-1-turbo-260628, seed-2-0-pro-260328, seed-2-0-lite-260228, seed-2-0-mini-260215, seed-1-8-251228, the seed-1-6 family, glm-5-2-260617.",
205 stop: 'Up to four strings that stop generation when produced.',
206 user: 'Opaque end-user identifier forwarded for abuse monitoring.',
207 },
208 GenerateImagesRequest: {
209 model:
210 'Seedream model id (e.g. seedream-4-0-250828) or a preconfigured endpoint id.',
211 prompt: 'Instruction text (docs give the limit as 600 English words).',
212 image:
213 'Input images for image-conditioned generation (editing, reference-guided generation, multi-reference composition). Each entry is a publicly reachable URL or a data:image/<format>;base64,<data> URI — <format> must be lowercase. Up to 14 references (10 on dola-seedream-5-0-pro-260628).',
214 size: "Output size: a shorthand token ('1K', '2K', '4K') or explicit pixels ('2048x2048') — never a mix. Server default 2048x2048.",
215 response_format:
216 "How generated images come back. 'url' links expire 24 hours after generation. Server default 'url'.",
217 output_format:
218 "Generated file format. Seedream 5.0 family only; default 'jpeg'.",
219 watermark:
220 "Stamp an 'AI generated' watermark in the bottom-right corner. DEFAULTS TO TRUE — pass false to opt out.",
221 sequential_image_generation:
222 "Group-image mode: 'auto' lets the model return a set of related images (bounded by sequential_image_generation_options.max_images — an upper bound, not a count); 'disabled' (server default) returns exactly one.",
223 guidance_scale:
224 'How strictly the result follows the prompt; higher values adhere more closely at some cost to diversity.',
225 tools:
226 'Provider tools to run during generation; the only documented member is web search, whose usage comes back under usage.tool_usage.web_search.',
227 },
228 CreateContentGenerationTaskRequest: {
229 model:
230 'Seedance model id (e.g. seedance-1-5-pro-251215; the 2.0 family requires the dreamina- prefix) or a preconfigured endpoint id.',
231 ratio:
232 "Output aspect ratio: 16:9, 9:16, 4:3, 3:4, 1:1, 21:9, or 'adaptive' (follows the input frame; image-to-video only).",
233 resolution:
234 'Resolution tier: 480p/720p on Seedance 2.5 and 2.0-fast/-mini, up to 1080p on the 1.x models and 4k on dreamina-seedance-2-0-260128. Matched case-insensitively by the API; there is no 2K tier on any model.',
235 duration:
236 'Whole seconds of output (2-12s on 1.0, 4-12s on 1.5-pro, 4-15s on 2.0, 4-30s on 2.5). -1 lets the model choose (2.5 / 2.0 / 1.5-pro).',
237 frames:
238 'Frame count, an alternative to duration that allows fractional seconds.',
239 seed: 'Randomness seed; integers in [-1, 2^32-1], where -1 means unseeded.',
240 camera_fixed:
241 "Appends a 'fix the camera' instruction to the prompt. Default false.",
242 watermark: 'Burn a watermark into the output. Default false.',
243 generate_audio: 'Generate a synchronized audio track. Default false.',
244 service_tier:
245 "'default' (online) or 'flex' (offline batch, half price). Note flex tasks are missing from the default task listing unless filter.service_tier=flex is passed.",
246 return_last_frame: 'Also return the final frame as a PNG. Default false.',
247 draft: 'Cheap low-fidelity preview render. Default false.',
248 content:
249 'Prompt text plus image / video / audio inputs. The API sorts requests into task types from the roles present — i2v (first frame), flf2v (first + last frame) and r2v (reference media) — and the two families are mutually exclusive.',
250 safety_identifier:
251 'Opaque per-end-user identifier for abuse attribution, max 64 chars.',
252 execution_expires_after:
253 "Seconds from created_at after which the task is marked 'expired'.",
254 callback_url:
255 'URL that receives a POST with the task payload on each status change.',
256 },
257 CreateContentGenerationTaskResponse: {
258 id: 'Task id, e.g. cgt-batch-20260731174311-zmz5s — the -batch infix appears on flex-tier routing. The video is not in this body. Poll GET /contents/generations/tasks/{id} until status is succeeded; content.video_url expires 24 hours later (the task record itself is kept for 7 days).',
259 },
260 GetContentGenerationTaskResponse: {
261 id: 'Task id returned by the create call.',
262 status:
263 'queued, running, succeeded, failed, or cancelled. The video URL is present once this is succeeded. A task can also be marked expired when execution_expires_after elapses.',
264 content:
265 'Output of a completed task. video_url is the file; last_frame_url is set when the create call passed return_last_frame: true. Both URLs are valid for 24 hours.',
266 },
267 Content: {
268 video_url:
269 'URL of the generated video. Present when status is succeeded. Valid for 24 hours; a Dreamina Seedance 2.5 URL can be downloaded up to 100 times. Download or copy it before it expires.',
270 last_frame_url:
271 'URL of the last frame. Returned when the create call set return_last_frame: true. Valid for 24 hours.',
272 },
274​
275/** Apply curated extra properties and descriptions to a generated schema. */
276function applyCurated(name: string, schema: JsonSchema): JsonSchema {
277 const extras = ARK_CURATED_PROPERTIES[name]
278 const descriptions = ARK_CURATED_DESCRIPTIONS[name]
279 if (!extras && !descriptions) return schema
280​
281 const properties = {
282 ...(schema.properties as Record<string, JsonSchema> | undefined),
283 }
284 for (const [field, spec] of Object.entries(extras ?? {})) {
285 // Curated extras never clobber a field the SDK now declares — if upstream
286 // has caught up, upstream wins on shape.
287 properties[field] ??= spec
288 }
289 for (const [field, description] of Object.entries(descriptions ?? {})) {
290 const existing = properties[field]
291 if (existing) properties[field] = { ...existing, description }
292 }
293 return { ...schema, properties }
295​
296export interface ArkSpecBuild {
297 spec: OpenApiDocument
298 warnings: Array<string>
300​
301/**
302 * Build the Ark document from fetched Go sources. Throws only if the sources
303 * are unusable (no endpoint root parsed) so the caller can fall back to the
304 * embedded document.
305 */
306export function buildArkSpecFromGo(files: Array<GoSourceFile>): ArkSpecBuild {
307 const roots = ARK_ENDPOINTS.flatMap((e) =>
308 [e.requestType, e.responseType].filter((name) => name !== undefined),
309 )
310 const { schemas, warnings } = parseGoSchemas(files, roots)
311​
312 const missing = roots.filter((r) => !(r in schemas))
313 if (missing.length > 0) {
314 throw new Error(
315 `byteplus: Go SDK parse missing endpoint types: ${missing.join(', ')}`,
316 )
317 }
318​
319 const components: Record<string, JsonSchema> = {}
320 for (const [name, schema] of Object.entries(schemas)) {
321 components[name] = applyCurated(name, schema)
322 }
323​
324 const paths: NonNullable<OpenApiDocument['paths']> = {}
325 for (const endpoint of ARK_ENDPOINTS) {
326 const method = endpoint.method ?? 'post'
327 const operation: Record<string, unknown> = {
328 // Re-derived from the SDK every sync, so it self-heals: no
329 // verifiedAt, because freshness is the sync timestamp.
330 [PROVENANCE_MARKER]: { derivation: 'generated' },
331 operationId: endpoint.operationId,
332 summary: endpoint.summary,
333 responses: {
334 '200': endpoint.responseType
335 ? {
336 description: endpoint.responseDescription,
337 content: {
338 'application/json': {
339 schema: {
340 $ref: `#/components/schemas/${endpoint.responseType}`,
341 },
342 },
343 },
344 }
345 : { description: endpoint.responseDescription },
346 },
347 }
348 if (endpoint.requestType !== undefined) {
349 operation.requestBody = {
350 required: true,
351 content: {
352 'application/json': {
353 schema: { $ref: `#/components/schemas/${endpoint.requestType}` },
354 },
355 },
356 }
357 }
358 if (endpoint.pathParam !== undefined) {
359 operation.parameters = [
360 {
361 name: endpoint.pathParam.name,
362 in: 'path',
363 required: true,
364 description: endpoint.pathParam.description,
365 schema: { type: 'string' },
366 },
367 ]
368 }
369 const item = paths[endpoint.path] ?? {}
370 item[method] = operation
371 paths[endpoint.path] = item
372 }
373​
374 return {
375 spec: {
376 openapi: '3.1.0',
377 info: {
378 title: 'BytePlus ModelArk API',
379 version: 'v3',
380 description: `Generated at sync time from BytePlus's official Go SDK (${ARK_GO_SOURCE_URL}), with curated descriptions and the request fields the SDK omits re-applied. Auth: Authorization: Bearer $ARK_API_KEY; keys are region-isolated.`,
381 },
382 servers: [{ url: BYTEPLUS_ARK_BASE_URL }],
383 paths,
384 components: { schemas: components },
385 },
386 warnings,
387 }