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

image.ts

417 lines13.7 KB

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}`
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('; ')
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. The deprecated `unitsBilled` is still populated for
104 * backward compatibility.
105 */
106function buildBytePlusImageUsage(
107 usage: BytePlusImageUsage | undefined,
108): TokenUsage | undefined {
109 if (!usage) return undefined
110​
111 const completionTokens = usage.output_tokens ?? 0
112 return {
113 promptTokens: 0,
114 completionTokens,
115 totalTokens: usage.total_tokens ?? completionTokens,
116 ...(usage.generated_images !== undefined && {
117 billed: { quantity: usage.generated_images, unit: 'images' },
118 unitsBilled: usage.generated_images,
119 }),
120 }
122​
123/**
124 * BytePlus Seedream image generation adapter.
125 *
126 * Drives Ark's `POST /images/generations` endpoint directly rather than
127 * through the OpenAI SDK: the endpoint takes size tokens (`2K`) as well as
128 * pixel sizes, has no `n` parameter, and carries reference images for editing
129 * in the generation request instead of a separate edits endpoint.
130 *
131 * Features:
132 * - Text-to-image and image-conditioned generation (editing, multi-reference)
133 * from a single call, with per-model reference-count limits enforced.
134 * - Size validation across both accepted forms.
135 * - `numberOfImages` mapped onto Seedream's group-image mode.
136 *
137 * @example
138 * ```typescript
139 * const adapter = byteplusImage('seedream-4-0-250828')
140 * const result = await generateImage({
141 * adapter,
142 * prompt: 'A guitar in a sunlit workshop',
143 * size: '2K',
144 * modelOptions: { watermark: false },
145 * })
146 * ```
147 */
148export class BytePlusImageAdapter<
149 TModel extends BytePlusImageModel,
150> extends BaseImageAdapter<
151 TModel,
152 BytePlusImageProviderOptions,
153 BytePlusImageModelProviderOptionsByName,
154 BytePlusImageModelSizeByName,
155 BytePlusImageModelInputModalitiesByName
156> {
157 override readonly kind = 'image' as const
158 readonly name = 'byteplus' as const
159​
160 /** Config with the Ark base URL resolved and trailing slashes trimmed. */
161 private readonly clientConfig: Omit<BytePlusImageConfig, 'baseURL'> & {
162 baseURL: string
163 }
164​
165 constructor(model: TModel, config: BytePlusImageConfig) {
166 super(model, {})
167 this.clientConfig = withBytePlusArkDefaults(config)
168 }
169​
170 async generateImages(
171 options: ImageGenerationOptions<
172 BytePlusImageProviderOptions,
173 BytePlusImageModelSizeByName[TModel]
174 >,
175 ): Promise<ImageGenerationResult> {
176 const { numberOfImages, size, modelOptions, logger } = options
177 const model = this.model
178​
179 const resolved = resolveMediaPrompt(options.prompt)
180​
181 if (resolved.videos.length > 0 || resolved.audios.length > 0) {
182 throw new Error(
183 `byteplus.generateImages does not support video / audio prompt parts on model ${model}.`,
184 )
185 }
186​
187 const unsupportedRole = resolved.images.find(
188 (part) =>
189 part.metadata?.role !== undefined &&
190 !SUPPORTED_INPUT_ROLES.has(part.metadata.role),
191 )
192 if (unsupportedRole) {
193 throw new Error(
194 `byteplus: Seedream has no ${unsupportedRole.metadata?.role} input; ` +
195 `it accepts reference images only (${[...SUPPORTED_INPUT_ROLES].join(', ')}).`,
196 )
197 }
198​
199 validateBytePlusImagePrompt(model, resolved.text)
200 validateBytePlusReferenceImages(model, resolved.images.length)
201​
202 const imageRefs = resolved.images.map(imagePartToImageRef)
203 const request: BytePlusImageGenerationRequest = {
204 ...(imageRefs.length > 0 && { image: imageRefs }),
205 ...(size !== undefined && {
206 size: resolveBytePlusImageSize(size),
207 }),
208 ...resolveBytePlusSequentialImages(model, numberOfImages),
209 // Explicit provider options win over the values derived from the
210 // generic options above (e.g. forcing `sequential_image_generation`).
211 ...modelOptions,
212 model,
213 prompt: resolved.text,
214 }
215​
216 try {
217 logger.request(
218 `activity=image provider=${this.name} model=${model} size=${request.size ?? 'default'} refs=${imageRefs.length}`,
219 { provider: this.name, model },
220 )
221​
222 const fetchImpl = this.clientConfig.fetch ?? fetch
223 const signal = bytePlusTimeoutSignal(this.clientConfig.timeout)
224 const response = await fetchImpl(
225 `${this.clientConfig.baseURL}/images/generations`,
226 {
227 method: 'POST',
228 ...(signal && { signal }),
229 headers: bytePlusArkHeaders(
230 this.clientConfig.apiKey,
231 toHeaderRecord(this.clientConfig.defaultHeaders),
232 ),
233 body: JSON.stringify(request),
234 },
235 )
236​
237 const body = await readJsonBody(response)
238 if (!response.ok) {
239 throw bytePlusArkError(response.status, body, 'image generation')
240 }
241​
242 return this.transformResponse(body, logger, numberOfImages)
243 } catch (error: unknown) {
244 logger.errors(`${this.name}.generateImages fatal`, {
245 error: toRunErrorPayload(error, `${this.name}.generateImages failed`),
246 source: `${this.name}.generateImages`,
247 })
248 throw error
249 }
250 }
251​
252 private transformResponse(
253 body: unknown,
254 logger: InternalLogger,
255 numberOfImages: number | undefined,
256 ): ImageGenerationResult {
257 // Shape pinned by a live seedream-4-0-250828 call and the Ark OpenAPI
258 // document. Validate rather than cast: `readJsonBody` returns `undefined`
259 // for an empty body and the raw text for a non-JSON one (an HTML error
260 // page from a proxy in front of the API), and casting either would report
261 // "returned no images" with the body — the only evidence of what actually
262 // happened — thrown away.
263 if (typeof body !== 'object' || body === null) {
264 throw bytePlusArkError(
265 200,
266 body,
267 'image generation returned a non-object body',
268 )
269 }
270 const payload = body as BytePlusImageGenerationResponse
271​
272 const images: Array<GeneratedImage> = []
273 const failures: Array<BytePlusImageErrorObject> = []
274 // Items matching none of the three known shapes. Ark's OpenAPI document
275 // describes a second, nested item form, so this is a live possibility
276 // rather than a defensive branch — and an unrecognized item that is
277 // neither counted nor reported turns provider drift into an
278 // "returned no images" with no attribution at all.
279 let unrecognized = 0
280 for (const item of payload.data ?? []) {
281 if (item.b64_json) {
282 images.push({ b64Json: item.b64_json })
283 } else if (item.url) {
284 images.push({ url: item.url })
285 } else if (item.error) {
286 // Group-image mode reports per-image failures alongside successes;
287 // dropping them silently would make a short result look complete.
288 failures.push(item.error)
289 } else {
290 unrecognized += 1
291 }
292 }
293 if (payload.error) failures.push(payload.error)
294​
295 if (unrecognized > 0) {
296 logger.errors(
297 `${this.name}.generateImages: ${unrecognized} response item(s) matched ` +
298 `none of b64_json / url / error — the response shape may have changed.`,
299 {
300 source: `${this.name}.generateImages`,
301 provider: this.name,
302 model: this.model,
303 body,
304 },
305 )
306 }
307​
308 if (images.length === 0) {
309 const detail =
310 describeFailures(failures) ||
311 (unrecognized > 0
312 ? `${unrecognized} unrecognized response item(s): ${describeBody(body) ?? ''}`
313 : '')
314 throw new Error(
315 `byteplus: image generation returned no images` +
316 (detail ? `: ${detail}` : '.'),
317 )
318 }
319​
320 if (failures.length > 0) {
321 logger.errors(
322 `${this.name}.generateImages dropped ${failures.length} failed image(s): ${describeFailures(failures)}`,
323 {
324 source: `${this.name}.generateImages`,
325 provider: this.name,
326 model: this.model,
327 failures,
328 },
329 )
330 // The caller asked for a group and is getting a short array. Warn
331 // unconditionally: the `numberOfImages` warning below only fires when
332 // the count was set explicitly, so a partial failure would otherwise
333 // return successfully with no signal at all.
334 logger.warn(
335 `byteplus: ${failures.length} of ${failures.length + images.length} ` +
336 `images failed to generate; returning ${images.length}.`,
337 { provider: this.name, model: this.model },
338 )
339 }
340​
341 if (numberOfImages !== undefined && images.length < numberOfImages) {
342 logger.warn(
343 `byteplus: requested ${numberOfImages} images, received ${images.length}. ` +
344 `Seedream has no exact count — sequential_image_generation.max_images is ` +
345 `an upper bound and the model decides how many the prompt warrants.`,
346 { provider: this.name, model: this.model },
347 )
348 }
349​
350 const usage = buildBytePlusImageUsage(payload.usage)
351​
352 return {
353 id: generateId(this.name),
354 model: this.model,
355 images,
356 ...(usage ? { usage } : {}),
357 }
358 }
360​
361/**
362 * Creates a BytePlus Seedream image adapter with an explicit API key.
363 * Type resolution happens here at the call site.
364 *
365 * @param model - The model name (e.g., 'seedream-4-0-250828')
366 * @param apiKey - Your BytePlus Ark API key
367 * @param config - Optional additional configuration
368 * @returns Configured BytePlus image adapter instance with resolved types
369 *
370 * @example
371 * ```typescript
372 * const adapter = createBytePlusImage('seedream-5-0-260128', 'ark-...')
373 *
374 * const result = await generateImage({
375 * adapter,
376 * prompt: 'A cute baby sea otter',
377 * size: '2K',
378 * })
379 * ```
380 */
381export function createBytePlusImage<TModel extends BytePlusImageModel>(
382 model: TModel,
383 apiKey: string,
384 config?: Omit<BytePlusImageConfig, 'apiKey'>,
385): BytePlusImageAdapter<TModel> {
386 return new BytePlusImageAdapter(model, { apiKey, ...config })
388​
389/**
390 * Creates a BytePlus Seedream image adapter, reading `ARK_API_KEY` from the
391 * environment. Type resolution happens here at the call site.
392 *
393 * Note that Ark keys are region-isolated: a key issued for `ap-southeast`
394 * does not work against the EU host.
395 *
396 * @param model - The model name (e.g., 'seedream-4-0-250828')
397 * @param config - Optional configuration (excluding apiKey, auto-detected)
398 * @returns Configured BytePlus image adapter instance with resolved types
399 * @throws Error if ARK_API_KEY is not found in environment
400 *
401 * @example
402 * ```typescript
403 * const adapter = byteplusImage('seedream-4-0-250828')
404 *
405 * const result = await generateImage({
406 * adapter,
407 * prompt: 'A beautiful sunset over mountains',
408 * modelOptions: { watermark: false },
409 * })
410 * ```
411 */
412export function byteplusImage<TModel extends BytePlusImageModel>(
413 model: TModel,
414 config?: Omit<BytePlusImageConfig, 'apiKey'>,
415): BytePlusImageAdapter<TModel> {
416 return createBytePlusImage(model, getBytePlusArkApiKeyFromEnv(), config)