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

byteplus-ark-build.ts

370 lines16.6 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'
67 operationId: string
68 summary: string
69 /** Body schema. GETs use `pathParam` instead. */
70 requestType?: string
71 pathParam?: { name: string; description: string }
72 responseType: string
73 responseDescription: string
75​
76/**
77 * `ChatCompletionRequest` (the legacy struct) is deliberately NOT used —
78 * upstream marks it deprecated and it lacks `thinking`,
79 * `parallel_tool_calls` and `max_completion_tokens`.
80 */
81const ARK_ENDPOINTS: Array<ArkEndpoint> = [
82 {
83 path: '/chat/completions',
84 operationId: 'createChatCompletion',
85 summary:
86 'Chat completion (Seed / GLM / DeepSeek / gpt-oss) — OpenAI-compatible plus thinking, reasoning_effort, repetition_penalty and service_tier',
87 requestType: 'CreateChatCompletionRequest',
88 responseType: 'ChatCompletionResponse',
89 responseDescription: 'Completion',
90 },
91 {
92 path: '/images/generations',
93 operationId: 'createImageGeneration',
94 summary: 'Generate or edit images with Seedream',
95 requestType: 'GenerateImagesRequest',
96 responseType: 'ImagesResponse',
97 responseDescription: 'Generated images',
98 },
99 {
100 path: '/contents/generations/tasks',
101 operationId: 'createContentsGenerationsTask',
102 summary:
103 'Open a Seedance video generation task (async — poll GET /contents/generations/tasks/{id} for the result)',
104 requestType: 'CreateContentGenerationTaskRequest',
105 responseType: 'CreateContentGenerationTaskResponse',
106 responseDescription: 'Task acknowledgment',
107 },
108 {
109 path: '/contents/generations/tasks/{id}',
110 method: 'get',
111 operationId: 'getContentsGenerationsTask',
112 summary:
113 '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).',
114 pathParam: {
115 name: 'id',
116 description:
117 'Task id from POST /contents/generations/tasks. You can query records from the past 7 days.',
118 },
119 responseType: 'GetContentGenerationTaskResponse',
120 responseDescription:
121 'Task record. content.video_url is the file once status is succeeded.',
122 },
124​
125/**
126 * Request fields Ark accepts that the Go SDK's structs do not declare, keyed
127 * by the schema they belong to. Each description says where it is from:
128 * TanStack AI's 2026-07-31 probe sweep or Ark's API doc. The SDK lags.
129 */
130const ARK_CURATED_PROPERTIES: Record<string, Record<string, JsonSchema>> = {
131 CreateChatCompletionRequest: {
132 reasoning_effort: {
133 type: 'string',
134 enum: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
135 description:
136 "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.",
137 },
138 top_k: {
139 type: 'integer',
140 description:
141 'Restricts sampling to the k most likely tokens. Absent from the Go SDK; probe-verified 2026-07-31.',
142 },
143 seed: {
144 type: 'integer',
145 description:
146 'Best-effort determinism hint for repeated identical requests. Absent from the Go SDK; probe-verified 2026-07-31.',
147 },
148 },
149 GenerateImagesRequest: {
150 stream: {
151 type: 'boolean',
152 description:
153 'Server-sent-events mode, emitting each image as it finishes. Absent from the Go SDK request struct, which models the unary call only.',
154 },
155 layer_decomposition: {
156 type: 'boolean',
157 description:
158 '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).',
159 },
160 },
161 CreateContentGenerationTaskRequest: {
162 output_format: {
163 type: 'string',
164 description:
165 '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.',
166 },
167 },
169​
170/**
171 * Curated field descriptions, keyed by schema then wire field name. These
172 * carry behaviour a type declaration cannot state, so they override the Go
173 * doc comment whenever both exist.
174 */
175const ARK_CURATED_DESCRIPTIONS: Record<string, Record<string, string>> = {
176 CreateChatCompletionRequest: {
177 model:
178 'Ark model id (e.g. seed-2-0-lite-260428) or a preconfigured endpoint id.',
179 max_tokens:
180 'Maximum tokens to generate. Mutually exclusive with max_completion_tokens — sending both is a 400.',
181 max_completion_tokens:
182 "OpenAI's newer name for max_tokens; mutually exclusive with it.",
183 repetition_penalty:
184 'Penalty applied to repeated tokens. Values above 1 discourage repetition.',
185 service_tier:
186 "'flex' routes to the batch queue at a lower price with no latency guarantee; 'default' is the standard online tier.",
187 thinking:
188 "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).",
189 response_format:
190 "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.",
191 stop: 'Up to four strings that stop generation when produced.',
192 user: 'Opaque end-user identifier forwarded for abuse monitoring.',
193 },
194 GenerateImagesRequest: {
195 model:
196 'Seedream model id (e.g. seedream-4-0-250828) or a preconfigured endpoint id.',
197 prompt: 'Instruction text (docs give the limit as 600 English words).',
198 image:
199 '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).',
200 size: "Output size: a shorthand token ('1K', '2K', '4K') or explicit pixels ('2048x2048') — never a mix. Server default 2048x2048.",
201 response_format:
202 "How generated images come back. 'url' links expire 24 hours after generation. Server default 'url'.",
203 output_format:
204 "Generated file format. Seedream 5.0 family only; default 'jpeg'.",
205 watermark:
206 "Stamp an 'AI generated' watermark in the bottom-right corner. DEFAULTS TO TRUE — pass false to opt out.",
207 sequential_image_generation:
208 "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.",
209 guidance_scale:
210 'How strictly the result follows the prompt; higher values adhere more closely at some cost to diversity.',
211 tools:
212 'Provider tools to run during generation; the only documented member is web search, whose usage comes back under usage.tool_usage.web_search.',
213 },
214 CreateContentGenerationTaskRequest: {
215 model:
216 'Seedance model id (e.g. seedance-1-5-pro-251215; the 2.0 family requires the dreamina- prefix) or a preconfigured endpoint id.',
217 ratio:
218 "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).",
219 resolution:
220 '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.',
221 duration:
222 '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).',
223 frames:
224 'Frame count, an alternative to duration that allows fractional seconds.',
225 seed: 'Randomness seed; integers in [-1, 2^32-1], where -1 means unseeded.',
226 camera_fixed:
227 "Appends a 'fix the camera' instruction to the prompt. Default false.",
228 watermark: 'Burn a watermark into the output. Default false.',
229 generate_audio: 'Generate a synchronized audio track. Default false.',
230 service_tier:
231 "'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.",
232 return_last_frame: 'Also return the final frame as a PNG. Default false.',
233 draft: 'Cheap low-fidelity preview render. Default false.',
234 content:
235 '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.',
236 safety_identifier:
237 'Opaque per-end-user identifier for abuse attribution, max 64 chars.',
238 execution_expires_after:
239 "Seconds from created_at after which the task is marked 'expired'.",
240 callback_url:
241 'URL that receives a POST with the task payload on each status change.',
242 },
243 CreateContentGenerationTaskResponse: {
244 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).',
245 },
246 GetContentGenerationTaskResponse: {
247 id: 'Task id returned by the create call.',
248 status:
249 '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.',
250 content:
251 '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.',
252 },
253 Content: {
254 video_url:
255 '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.',
256 last_frame_url:
257 'URL of the last frame. Returned when the create call set return_last_frame: true. Valid for 24 hours.',
258 },
260​
261/** Apply curated extra properties and descriptions to a generated schema. */
262function applyCurated(name: string, schema: JsonSchema): JsonSchema {
263 const extras = ARK_CURATED_PROPERTIES[name]
264 const descriptions = ARK_CURATED_DESCRIPTIONS[name]
265 if (!extras && !descriptions) return schema
266​
267 const properties = {
268 ...(schema.properties as Record<string, JsonSchema> | undefined),
269 }
270 for (const [field, spec] of Object.entries(extras ?? {})) {
271 // Curated extras never clobber a field the SDK now declares — if upstream
272 // has caught up, upstream wins on shape.
273 properties[field] ??= spec
274 }
275 for (const [field, description] of Object.entries(descriptions ?? {})) {
276 const existing = properties[field]
277 if (existing) properties[field] = { ...existing, description }
278 }
279 return { ...schema, properties }
281​
282export interface ArkSpecBuild {
283 spec: OpenApiDocument
284 warnings: Array<string>
286​
287/**
288 * Build the Ark document from fetched Go sources. Throws only if the sources
289 * are unusable (no endpoint root parsed) so the caller can fall back to the
290 * embedded document.
291 */
292export function buildArkSpecFromGo(files: Array<GoSourceFile>): ArkSpecBuild {
293 const roots = ARK_ENDPOINTS.flatMap((e) =>
294 [e.requestType, e.responseType].filter((name) => name !== undefined),
295 )
296 const { schemas, warnings } = parseGoSchemas(files, roots)
297​
298 const missing = roots.filter((r) => !(r in schemas))
299 if (missing.length > 0) {
300 throw new Error(
301 `byteplus: Go SDK parse missing endpoint types: ${missing.join(', ')}`,
302 )
303 }
304​
305 const components: Record<string, JsonSchema> = {}
306 for (const [name, schema] of Object.entries(schemas)) {
307 components[name] = applyCurated(name, schema)
308 }
309​
310 const paths: NonNullable<OpenApiDocument['paths']> = {}
311 for (const endpoint of ARK_ENDPOINTS) {
312 const method = endpoint.method ?? 'post'
313 const operation: Record<string, unknown> = {
314 // Re-derived from the SDK every sync, so it self-heals: no
315 // verifiedAt, because freshness is the sync timestamp.
316 [PROVENANCE_MARKER]: { derivation: 'generated' },
317 operationId: endpoint.operationId,
318 summary: endpoint.summary,
319 responses: {
320 '200': {
321 description: endpoint.responseDescription,
322 content: {
323 'application/json': {
324 schema: {
325 $ref: `#/components/schemas/${endpoint.responseType}`,
326 },
327 },
328 },
329 },
330 },
331 }
332 if (endpoint.requestType !== undefined) {
333 operation.requestBody = {
334 required: true,
335 content: {
336 'application/json': {
337 schema: { $ref: `#/components/schemas/${endpoint.requestType}` },
338 },
339 },
340 }
341 }
342 if (endpoint.pathParam !== undefined) {
343 operation.parameters = [
344 {
345 name: endpoint.pathParam.name,
346 in: 'path',
347 required: true,
348 description: endpoint.pathParam.description,
349 schema: { type: 'string' },
350 },
351 ]
352 }
353 paths[endpoint.path] = { [method]: operation }
354 }
355​
356 return {
357 spec: {
358 openapi: '3.1.0',
359 info: {
360 title: 'BytePlus ModelArk API',
361 version: 'v3',
362 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.`,
363 },
364 servers: [{ url: BYTEPLUS_ARK_BASE_URL }],
365 paths,
366 components: { schemas: components },
367 },
368 warnings,
369 }