|
| 1 | +import BaseApi from '../../common/baseApi'; |
| 2 | +import { getDashscopeUserAgent } from '../../common/userAgent'; |
| 3 | +import { waitForTask } from '../../common/asyncTask'; |
| 4 | +import { ImageGenerationOptions } from '../../types'; |
| 5 | +import { shouldModifyIncrementalOutput } from '../../utils/paramUtils'; |
| 6 | +import GenerationResult from '../generation/result'; |
| 7 | +import { parseStreamResult } from '../generation/streamUtils'; |
| 8 | + |
| 9 | +/** Model ids supported by ImageGeneration (aligned with Python `ImageGeneration.Models`). */ |
| 10 | +export const ImageGenerationModels = { |
| 11 | + WAN2_6_IMAGE: 'wan2.6-image', |
| 12 | + WAN2_6_T2I: 'wan2.6-t2i', |
| 13 | +} as const; |
| 14 | + |
| 15 | +/** |
| 16 | + * Image generation API based on a `messages` interface (wan2.6-image / wan2.6-t2i). |
| 17 | + * |
| 18 | + * Supports both synchronous (streaming / non-streaming) and asynchronous task modes. |
| 19 | + * Aligned with Python `dashscope.aigc.image_generation.ImageGeneration`. |
| 20 | + */ |
| 21 | +class ImageGeneration extends BaseApi { |
| 22 | + |
| 23 | + /** Sync service path (multimodal-generation). */ |
| 24 | + private static SYNC_SERVICE = 'services/aigc/multimodal-generation/generation'; |
| 25 | + /** Async service path (image-generation). */ |
| 26 | + private static ASYNC_SERVICE = 'services/aigc/image-generation/generation'; |
| 27 | + |
| 28 | + protected service = ImageGeneration.SYNC_SERVICE; |
| 29 | + |
| 30 | + /** Synchronous / streaming call. */ |
| 31 | + async call(options: ImageGenerationOptions) { |
| 32 | + const { model, messages, stream = false, incremental_output, n, is_async, wait_timeout, ...rest } = options; |
| 33 | + if (!model) throw new Error('model is required'); |
| 34 | + if (!messages || messages.length === 0) throw new Error('messages is required'); |
| 35 | + |
| 36 | + const input: Record<string, unknown> = { messages }; |
| 37 | + const parameters: Record<string, unknown> = { ...rest }; |
| 38 | + |
| 39 | + // Incremental merge logic (aligned with Python) |
| 40 | + let mergeIncremental = false; |
| 41 | + if (stream && shouldModifyIncrementalOutput(model) && incremental_output === false) { |
| 42 | + mergeIncremental = true; |
| 43 | + parameters.incremental_output = true; |
| 44 | + } else if (incremental_output !== undefined) { |
| 45 | + parameters.incremental_output = incremental_output; |
| 46 | + } |
| 47 | + |
| 48 | + const data: Record<string, unknown> = { model, input }; |
| 49 | + if (Object.keys(parameters).length) Object.assign(data, { parameters }); |
| 50 | + |
| 51 | + // Async mode: create task then wait |
| 52 | + if (is_async) { |
| 53 | + return this.asyncCallAndWait(data, wait_timeout); |
| 54 | + } |
| 55 | + |
| 56 | + // Sync mode |
| 57 | + const headers: Record<string, string> = {}; |
| 58 | + if (stream) { |
| 59 | + headers['Accept'] = 'text/event-stream'; |
| 60 | + headers['X-Accel-Buffering'] = 'no'; |
| 61 | + headers['X-DashScope-SSE'] = 'enable'; |
| 62 | + headers['User-Agent'] = `${getDashscopeUserAgent()}; incremental_to_full/${mergeIncremental ? '1' : '0'}`; |
| 63 | + const result = await this.request({ |
| 64 | + method: 'post', |
| 65 | + data, |
| 66 | + headers, |
| 67 | + responseType: 'stream', |
| 68 | + }); |
| 69 | + const opts = mergeIncremental ? { mergeIncremental: true, n: (n as number) ?? 1 } : {}; |
| 70 | + return parseStreamResult(result, opts); |
| 71 | + } |
| 72 | + |
| 73 | + const result = await this.request({ method: 'post', data, headers: undefined }); |
| 74 | + return new GenerationResult(result.status, result.data); |
| 75 | + } |
| 76 | + |
| 77 | + /** Create an async image generation task. Returns task info with `output.task_id`. */ |
| 78 | + async asyncCall(options: ImageGenerationOptions) { |
| 79 | + const { model, messages, ...rest } = options; |
| 80 | + if (!model) throw new Error('model is required'); |
| 81 | + if (!messages || messages.length === 0) throw new Error('messages is required'); |
| 82 | + const input: Record<string, unknown> = { messages }; |
| 83 | + const parameters: Record<string, unknown> = {}; |
| 84 | + for (const [k, v] of Object.entries(rest)) { |
| 85 | + if (v !== undefined && k !== 'is_async' && k !== 'wait_timeout') parameters[k] = v; |
| 86 | + } |
| 87 | + const data: Record<string, unknown> = { model, input }; |
| 88 | + if (Object.keys(parameters).length) Object.assign(data, { parameters }); |
| 89 | + const result = await this.request({ |
| 90 | + method: 'post', |
| 91 | + service: ImageGeneration.ASYNC_SERVICE, |
| 92 | + headers: { 'X-DashScope-Async': 'enable' }, |
| 93 | + data, |
| 94 | + }); |
| 95 | + return result.data; |
| 96 | + } |
| 97 | + |
| 98 | + /** Internal: send async request and wait for completion. */ |
| 99 | + private async asyncCallAndWait(data: Record<string, unknown>, waitTimeout?: number) { |
| 100 | + const result = await this.request({ |
| 101 | + method: 'post', |
| 102 | + service: ImageGeneration.ASYNC_SERVICE, |
| 103 | + headers: { 'X-DashScope-Async': 'enable' }, |
| 104 | + data, |
| 105 | + }); |
| 106 | + const createResult = result.data; |
| 107 | + const taskOpts = typeof waitTimeout === 'number' ? { waitTimeout } : undefined; |
| 108 | + return waitForTask(createResult, (taskId) => this.fetch(taskId), taskOpts); |
| 109 | + } |
| 110 | + |
| 111 | + /** Fetch task status by task id. */ |
| 112 | + async fetch(taskId: string) { |
| 113 | + const result = await this.request({ |
| 114 | + service: 'tasks', |
| 115 | + api: taskId, |
| 116 | + method: 'get', |
| 117 | + headers: { 'X-DashScope-Async': 'enable' }, |
| 118 | + }); |
| 119 | + return result.data; |
| 120 | + } |
| 121 | + |
| 122 | + /** Wait for an async task to complete, with optional `wait_timeout` (seconds). */ |
| 123 | + async wait(taskId: string, waitTimeout?: number) { |
| 124 | + const taskOpts = typeof waitTimeout === 'number' ? { waitTimeout } : undefined; |
| 125 | + return waitForTask( |
| 126 | + { output: { task_id: taskId } }, |
| 127 | + (id) => this.fetch(id), |
| 128 | + taskOpts, |
| 129 | + ); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +export default ImageGeneration; |
0 commit comments