Open History to see the last commit
1import {
2 isFileSource,
3 resolveMediaPrompt,
4 unsupportedFileSourceError,
5} from '@tanstack/ai'
6import { BaseImageAdapter } from '@tanstack/ai/adapters'
7import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
8import { generateId } from '@tanstack/ai-utils'
9import {
10 bytePlusArkError,
11 bytePlusArkHeaders,
12 bytePlusTimeoutSignal,
13 describeBody,
14 getBytePlusArkApiKeyFromEnv,
15 readJsonBody,
16 toHeaderRecord,
17 withBytePlusArkDefaults,
18} from '../utils/client'
19import {
20 resolveBytePlusImageSize,
21 resolveBytePlusSequentialImages,
22 validateBytePlusImagePrompt,
23 validateBytePlusReferenceImages,
24} from '../image/image-provider-options'
25import type {
26 GeneratedImage,
27 ImageGenerationOptions,
28 ImageGenerationResult,
29 ImagePart,
30 MediaInputMetadata,
31 TokenUsage,
32} from '@tanstack/ai'
33import type { InternalLogger } from '@tanstack/ai/adapter-internals'
34import type {
35 BytePlusImageErrorObject,
36 BytePlusImageGenerationRequest,
37 BytePlusImageGenerationResponse,
38 BytePlusImageUsage,
39} from '../image/wire-types'
40import type {
41 BytePlusImageModelInputModalitiesByName,
42 BytePlusImageModelProviderOptionsByName,
43 BytePlusImageProviderOptions,
44} from '../image/image-provider-options'
45import type {
46 BytePlusImageModel,
47 BytePlusImageModelSizeByName,
48} from '../model-meta'
49import type { BytePlusArkConfig } from '../utils/client'
50
51/**
52 * Configuration for the BytePlus Seedream image adapter.
53 */
54export interface BytePlusImageConfig extends BytePlusArkConfig {}
55
56/**
57 * Roles Seedream can honour. Every input image is a reference — there is no
58 * inpainting mask, control-image or frame channel — so this is an allow-list
59 * rather than a deny-list: a role added to the core union later (or a
60 * video-oriented one like `start_frame`) fails loudly here instead of being
61 * silently flattened into a plain reference.
62 */
63const SUPPORTED_INPUT_ROLES: ReadonlySet<string> = new Set([
64 'reference',
65 'character',
66])
67
68/**
69 * Converts a prompt image part to the string Seedream's `image` field takes:
70 * URLs pass through (BytePlus fetches them server-side), data sources become
71 * data URIs. BytePlus requires the format in `data:image/<format>;base64,` to
72 * be lowercase, so the mime type is lowercased on the way out.
73 */
74function imagePartToImageRef(part: ImagePart<MediaInputMetadata>): string {
75 const { source } = part
76 if (isFileSource(source)) throw unsupportedFileSourceError('byteplus')
77 if (source.type === 'url') return source.value
78 if (source.value.startsWith('data:')) return source.value
79 return `data:${source.mimeType.toLowerCase()};base64,${source.value}`
80}
81
82/**
83 * Renders provider error objects as `code: message` pairs for a log line or
84 * an error message.
85 */
86function describeFailures(
87 failures: ReadonlyArray<BytePlusImageErrorObject>,
88): string {
89 return failures
90 .map((failure) =>
91 [failure.code, failure.message].filter(Boolean).join(': '),
92 )
93 .filter((text) => text.length > 0)
94 .join('; ')
95}
96
97/**
98 * Maps Seedream's usage block onto `TokenUsage`.
99 *
100 * BytePlus bills per generated image and does not count input tokens, so
101 * `promptTokens` is always 0 and `generated_images` is surfaced as
102 * `usage.billed` (`{ quantity, unit: 'images' }`) — the count the price is
103 * applied to.
104 */
105function buildBytePlusImageUsage(
106 usage: BytePlusImageUsage | undefined,
107): TokenUsage | undefined {
108 if (!usage) return undefined
109
110 const completionTokens = usage.output_tokens ?? 0
111 return {
112 promptTokens: 0,
113 completionTokens,
114 totalTokens: usage.total_tokens ?? completionTokens,
115 ...(usage.generated_images !== undefined && {
116 billed: { quantity: usage.generated_images, unit: 'images' },
117 }),
118 }
119}
120
121/**
122 * BytePlus Seedream image generation adapter.
123 *
124 * Drives Ark's `POST /images/generations` endpoint directly rather than
125 * through the OpenAI SDK: the endpoint takes size tokens (`2K`) as well as
126 * pixel sizes, has no `n` parameter, and carries reference images for editing
127 * in the generation request instead of a separate edits endpoint.
128 *
129 * Features:
130 * - Text-to-image and image-conditioned generation (editing, multi-reference)
131 * from a single call, with per-model reference-count limits enforced.
132 * - Size validation across both accepted forms.
133 * - `numberOfImages` mapped onto Seedream's group-image mode.
134 *
135 * @example
136 * ```typescript
137 * const adapter = byteplusImage('seedream-4-0-250828')
138 * const result = await generateImage({
139 * adapter,
140 * prompt: 'A guitar in a sunlit workshop',
141 * size: '2K',
142 * modelOptions: { watermark: false },
143 * })
144 * ```
145 */
146export class BytePlusImageAdapter<
147 TModel extends BytePlusImageModel,
148> extends BaseImageAdapter<
149 TModel,
150 BytePlusImageProviderOptions,
151 BytePlusImageModelProviderOptionsByName,
152 BytePlusImageModelSizeByName,
153 BytePlusImageModelInputModalitiesByName
154> {
155 override readonly kind = 'image' as const
156 readonly name = 'byteplus' as const
157
158 /** Config with the Ark base URL resolved and trailing slashes trimmed. */
159 private readonly clientConfig: Omit<BytePlusImageConfig, 'baseURL'> & {
160 baseURL: string
161 }
162
163 constructor(model: TModel, config: BytePlusImageConfig) {
164 super(model, {})
165 this.clientConfig = withBytePlusArkDefaults(config)
166 }
167
168 async generateImages(
169 options: ImageGenerationOptions<
170 BytePlusImageProviderOptions,
171 BytePlusImageModelSizeByName[TModel]
172 >,
173 ): Promise<ImageGenerationResult> {
174 const { numberOfImages, size, modelOptions, logger } = options
175 const model = this.model
176
177 const resolved = resolveMediaPrompt(options.prompt)
178
179 if (resolved.videos.length > 0 || resolved.audios.length > 0) {
180 throw new Error(
181 `byteplus.generateImages does not support video / audio prompt parts on model ${model}.`,
182 )
183 }
184
185 const unsupportedRole = resolved.images.find(
186 (part) =>
187 part.metadata?.role !== undefined &&
188 !SUPPORTED_INPUT_ROLES.has(part.metadata.role),
189 )
190 if (unsupportedRole) {
191 throw new Error(
192 `byteplus: Seedream has no ${unsupportedRole.metadata?.role} input; ` +
193 `it accepts reference images only (${[...SUPPORTED_INPUT_ROLES].join(', ')}).`,
194 )
195 }
196
197 validateBytePlusImagePrompt(model, resolved.text)
198 validateBytePlusReferenceImages(model, resolved.images.length)
199
200 const imageRefs = resolved.images.map(imagePartToImageRef)
201 const request: BytePlusImageGenerationRequest = {
202 ...(imageRefs.length > 0 && { image: imageRefs }),
203 ...(size !== undefined && {
204 size: resolveBytePlusImageSize(size),
205 }),
206 ...resolveBytePlusSequentialImages(model, numberOfImages),
207 // Explicit provider options win over the values derived from the
208 // generic options above (e.g. forcing `sequential_image_generation`).
209 ...modelOptions,
210 model,
211 prompt: resolved.text,
212 }
213
214 try {
215 logger.request(
216 `activity=image provider=${this.name} model=${model} size=${request.size ?? 'default'} refs=${imageRefs.length}`,
217 { provider: this.name, model },
218 )
219
220 const fetchImpl = this.clientConfig.fetch ?? fetch
221 const signal = bytePlusTimeoutSignal(this.clientConfig.timeout)
222 const response = await fetchImpl(
223 `${this.clientConfig.baseURL}/images/generations`,
224 {
225 method: 'POST',
226 ...(signal && { signal }),
227 headers: bytePlusArkHeaders(
228 this.clientConfig.apiKey,
229 toHeaderRecord(this.clientConfig.defaultHeaders),
230 ),
231 body: JSON.stringify(request),
232 },
233 )
234
235 const body = await readJsonBody(response)
236 if (!response.ok) {
237 throw bytePlusArkError(response.status, body, 'image generation')
238 }
239
240 return this.transformResponse(body, logger, numberOfImages)
241 } catch (error: unknown) {
242 logger.errors(`${this.name}.generateImages fatal`, {
243 error: toRunErrorPayload(error, `${this.name}.generateImages failed`),
244 source: `${this.name}.generateImages`,
245 })
246 throw error
247 }
248 }
249
250 private transformResponse(
251 body: unknown,
252 logger: InternalLogger,
253 numberOfImages: number | undefined,
254 ): ImageGenerationResult {
255 // Shape pinned by a live seedream-4-0-250828 call and the Ark OpenAPI
256 // document. Validate rather than cast: `readJsonBody` returns `undefined`
257 // for an empty body and the raw text for a non-JSON one (an HTML error
258 // page from a proxy in front of the API), and casting either would report
259 // "returned no images" with the body — the only evidence of what actually
260 // happened — thrown away.
261 if (typeof body !== 'object' || body === null) {
262 throw bytePlusArkError(
263 200,
264 body,
265 'image generation returned a non-object body',
266 )
267 }
268 const payload = body as BytePlusImageGenerationResponse
269
270 const images: Array<GeneratedImage> = []
271 const failures: Array<BytePlusImageErrorObject> = []
272 // Items matching none of the three known shapes. Ark's OpenAPI document
273 // describes a second, nested item form, so this is a live possibility
274 // rather than a defensive branch — and an unrecognized item that is
275 // neither counted nor reported turns provider drift into an
276 // "returned no images" with no attribution at all.
277 let unrecognized = 0
278 for (const item of payload.data ?? []) {
279 if (item.b64_json) {
280 images.push({ b64Json: item.b64_json })
281 } else if (item.url) {
282 images.push({ url: item.url })
283 } else if (item.error) {
284 // Group-image mode reports per-image failures alongside successes;
285 // dropping them silently would make a short result look complete.
286 failures.push(item.error)
287 } else {
288 unrecognized += 1
289 }
290 }
291 if (payload.error) failures.push(payload.error)
292
293 if (unrecognized > 0) {
294 logger.errors(
295 `${this.name}.generateImages: ${unrecognized} response item(s) matched ` +
296 `none of b64_json / url / error — the response shape may have changed.`,
297 {
298 source: `${this.name}.generateImages`,
299 provider: this.name,
300 model: this.model,
301 body,
302 },
303 )
304 }
305
306 if (images.length === 0) {
307 const detail =
308 describeFailures(failures) ||
309 (unrecognized > 0
310 ? `${unrecognized} unrecognized response item(s): ${describeBody(body) ?? ''}`
311 : '')
312 throw new Error(
313 `byteplus: image generation returned no images` +
314 (detail ? `: ${detail}` : '.'),
315 )
316 }
317
318 if (failures.length > 0) {
319 logger.errors(
320 `${this.name}.generateImages dropped ${failures.length} failed image(s): ${describeFailures(failures)}`,
321 {
322 source: `${this.name}.generateImages`,
323 provider: this.name,
324 model: this.model,
325 failures,
326 },
327 )
328 // The caller asked for a group and is getting a short array. Warn
329 // unconditionally: the `numberOfImages` warning below only fires when
330 // the count was set explicitly, so a partial failure would otherwise
331 // return successfully with no signal at all.
332 logger.warn(
333 `byteplus: ${failures.length} of ${failures.length + images.length} ` +
334 `images failed to generate; returning ${images.length}.`,
335 { provider: this.name, model: this.model },
336 )
337 }
338
339 if (numberOfImages !== undefined && images.length < numberOfImages) {
340 logger.warn(
341 `byteplus: requested ${numberOfImages} images, received ${images.length}. ` +
342 `Seedream has no exact count — sequential_image_generation.max_images is ` +
343 `an upper bound and the model decides how many the prompt warrants.`,
344 { provider: this.name, model: this.model },
345 )
346 }
347
348 const usage = buildBytePlusImageUsage(payload.usage)
349
350 return {
351 id: generateId(this.name),
352 model: this.model,
353 images,
354 ...(usage ? { usage } : {}),
355 }
356 }
357}
358
359/**
360 * Creates a BytePlus Seedream image adapter with an explicit API key.
361 * Type resolution happens here at the call site.
362 *
363 * @param model - The model name (e.g., 'seedream-4-0-250828')
364 * @param apiKey - Your BytePlus Ark API key
365 * @param config - Optional additional configuration
366 * @returns Configured BytePlus image adapter instance with resolved types
367 *
368 * @example
369 * ```typescript
370 * const adapter = createBytePlusImage('seedream-5-0-260128', 'ark-...')
371 *
372 * const result = await generateImage({
373 * adapter,
374 * prompt: 'A cute baby sea otter',
375 * size: '2K',
376 * })
377 * ```
378 */
379export function createBytePlusImage<TModel extends BytePlusImageModel>(
380 model: TModel,
381 apiKey: string,
382 config?: Omit<BytePlusImageConfig, 'apiKey'>,
383): BytePlusImageAdapter<TModel> {
384 return new BytePlusImageAdapter(model, { apiKey, ...config })
385}
386
387/**
388 * Creates a BytePlus Seedream image adapter, reading `ARK_API_KEY` from the
389 * environment. Type resolution happens here at the call site.
390 *
391 * Note that Ark keys are region-isolated: a key issued for `ap-southeast`
392 * does not work against the EU host.
393 *
394 * @param model - The model name (e.g., 'seedream-4-0-250828')
395 * @param config - Optional configuration (excluding apiKey, auto-detected)
396 * @returns Configured BytePlus image adapter instance with resolved types
397 * @throws Error if ARK_API_KEY is not found in environment
398 *
399 * @example
400 * ```typescript
401 * const adapter = byteplusImage('seedream-4-0-250828')
402 *
403 * const result = await generateImage({
404 * adapter,
405 * prompt: 'A beautiful sunset over mountains',
406 * modelOptions: { watermark: false },
407 * })
408 * ```
409 */
410export function byteplusImage<TModel extends BytePlusImageModel>(
411 model: TModel,
412 config?: Omit<BytePlusImageConfig, 'apiKey'>,
413): BytePlusImageAdapter<TModel> {
414 return createBytePlusImage(model, getBytePlusArkApiKeyFromEnv(), config)
415}