用 rb.image() 生成图片。支持一次性生成和流式生成,异步任务自动轮询。
一次性生成
import { RouterBrain } from '@router-brain/sdk';
const rb = new RouterBrain('sk-your-api-key');
// URL 格式(默认)
const result = await rb.image({
model: 'dall-e-3',
prompt: '一只橘猫在樱花树下睡觉,夕阳,温暖色调',
size: '1024x1024',
}).json();
console.log(result.created); // 时间戳
console.log(result.data[0].url); // 图片 URL
console.log(result.usage?.images); // 生成张数
// Base64 格式
const result2 = await rb.image({
model: 'dall-e-3',
prompt: '山水画,水墨风格',
size: '1792x1024',
response_format: 'b64_json',
}).json();
console.log(result2.data[0].b64_json); // base64 字符串
流式生成(SSE)
流式模型使用 .stream() 逐步接收数据:
const stream = await rb.image({
model: 'stabilityai/stable-diffusion-3',
prompt: '赛博朋克城市夜景',
stream: true,
}).stream();
for await (const chunk of stream!) {
const text = new TextDecoder().decode(chunk);
console.log(text);
}
你可能收到的 SSE 事件:
| 事件 | 含义 |
|---|---|
success | 一张图片生成成功,带有 URL 或 base64 |
error | 一张图片生成失败,带有错误详情 |
complete | 全部图片完成,带有最终用量 |
异步任务轮询
部分模型异步处理并返回 task_id。用 .task() 自动轮询至完成:
const result = await rb.image({
model: 'stabilityai/stable-diffusion-3',
prompt: '星空下的独角兽',
}).task({
pollInterval: 2000, // 每 2 秒检查一次
});
console.log(result.task_status); // 'success'
console.log(result.data[0].url); // 图片 URL
console.log(result.usage.images); // 用量
超时自动取消:
const controller = new AbortController();
setTimeout(() => controller.abort(), 30000); // 30 秒超时
try {
const result = await rb.image({
model: 'stabilityai/stable-diffusion-3',
prompt: '...',
}).task({ signal: controller.signal });
} catch (err) {
console.error('任务取消或失败:', (err as Error).message);
}
可用方法
| 方法 | 返回类型 | 使用场景 |
|---|---|---|
json() | Promise<ImageResponseJson> | 普通生成 — 拿到结果 JSON |
stream() | Promise<ReadableStream<Uint8Array> | null> | 实时流式生成 |
task(opts?) | Promise<ImageTaskResponseJson> | 异步模型 — 自动轮询至完成 |
httpStatus() | Promise<number> | 先检查状态码再取结果 |
请求参数
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
model | string | ✅ | 模型名称,如 'dall-e-3' |
prompt | string | ✅ | 图片描述 |
image | ImageAdapterImage | ImageAdapterImage[] | ❌ | 参考图,用于图生图 |
size | string | ❌ | 图片尺寸,如 '1024x1024' |
stream | boolean | ❌ | 是否流式生成 |
response_format | 'url' | 'b64_json' | ❌ | 输出格式,默认 'url' |
upstream_options | Record<string, any> | ❌ | 模型特有参数 |
headers | Record<string, string | string[]> | ❌ | 自定义 HTTP Header |
各供应商具体差异见 图像生成文档。