dsh-mo-image 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,108 +1,160 @@
1
1
  /**
2
- * 国内厂商里协议形状和 OpenAI Images 不一致的两家。
2
+ * 国内厂商里协议形状和 OpenAI Images 不一致的那一家。
3
3
  *
4
- * - 百炼 Qwen-Image:原生多模态同步接口,size 用 `*` 分隔,图片在 output.choices[].message.content[].image
5
- * - 智谱 BigModel:形状像 OpenAI,但不接受 n / response_format,一次只回一张 url
4
+ * - 百炼 Qwen-Image:原生多模态同步接口。
5
+ * - 万相 2.6 文生图与 2.7 图像模型:原生多模态异步接口。
6
+ *
7
+ * 智谱 BigModel 不在这里:它的地址三元组(/images/generations + 无编辑 + /models)与
8
+ * 请求体都和通用 composeBody 一致(不收 n / response_format、负面词拼进提示词),
9
+ * 所以并进了 `openai-images` + 协议级选项 `{ edit: 'none' }`。
10
+ *
11
+ * 字段名不在协议里:prompt / negative / model / n / image 写在哪,由 `fieldsFor()` 按
12
+ * 「用户覆盖 > 模型规则 > 预设」取模板,再用 applyFields / promptParts 写进 body。
13
+ *
14
+ * 仍然留在协议里的三类东西(都不是「这家网关把提示词叫什么」):
15
+ * - 请求形状:消息信封 `input.messages[0].role = 'user'`;content[] 里 image 项在前、
16
+ * text 项在后(老 body 的顺序);编辑端不收尺寸;
17
+ * - 尺寸:它不属于六个逻辑字段,百炼的 `W*H` 星号仍由协议自己拼;
18
+ * - 六种模板能力表达不了的:百炼的负面词**既要单开 parameters.negative_prompt、又拼进
19
+ * 提示词**(一个逻辑字段只能有一条模板),所以折叠那一句还是协议代码。
6
20
  */
7
- import { request } from '../net.js';
8
- import { baseUrlOf, headersFor, readJsonResponse, fetchImageUrl, base64ToImage } from '../adapter-kit.js';
21
+ import { baseUrlOf } from '../adapter-kit.js';
22
+ import { outputProfile } from '../output-profiles.js';
23
+ import { applyFields, promptParts } from '../field-templates.js';
24
+ import { detectFieldRule, WAN_26_T2I, WAN_27_IMAGE, WAN_27_IMAGE_PRO } from '../model-rules.js';
25
+ // 循环依赖:adapters.js 先 import 本模块、再求值完。fieldsFor 是函数声明(已提升),
26
+ // 只要不在模块顶层调用就没问题——这里只在 execute() 里用。
27
+ import { executeBuiltImage, fieldsFor } from '../adapters.js';
9
28
 
29
+ /** 百炼的提示词:负面词既发一个独立参数、又拼进文本,模板表达不了双写,折叠留在协议里。 */
10
30
  function promptOf(input) {
11
31
  const prompt = String((input && input.prompt) || '');
12
32
  const negative = String((input && input.negativePrompt) || '').trim();
13
33
  return negative ? prompt + '\n\nAvoid: ' + negative : prompt;
14
34
  }
15
35
 
16
- function sizeOf(input) {
17
- const fitted = input && input.fitted;
18
- if (!fitted || fitted.omit || fitted.size === 'none' || fitted.size === 'auto') return '';
19
- if (fitted.width && fitted.height) return fitted.width + 'x' + fitted.height;
20
- return String(fitted.size || '');
36
+ /** 负面词的字段值:老实现只在这个值为真时才发那个参数(空串不发)。 */
37
+ function negativeOf(input) {
38
+ return String((input && input.negativePrompt) || '') || undefined;
39
+ }
40
+
41
+ const WAN_MULTIMODAL_PATH = '/services/aigc/image-generation/generation';
42
+ const WAN_MULTIMODAL_OUTPUT = outputProfile({
43
+ kind: 'task',
44
+ path: '/tasks/{taskId}',
45
+ idPath: 'output.task_id',
46
+ statusPath: 'output.task_status',
47
+ resultPath: 'output.choices[].message.content[].image',
48
+ resultAs: 'url',
49
+ success: ['SUCCEEDED'],
50
+ failure: ['FAILED', 'CANCELED', 'UNKNOWN'],
51
+ failureMessagePath: ['output.message', 'message', 'output.code', 'code'],
52
+ intervalMs: 2000,
53
+ maxBytes: 32 * 1024 * 1024,
54
+ emptyMessage: '百炼万相没有返回图片'
55
+ }, 'dashscope-wanx-multimodal');
56
+
57
+ function wanMultimodalSize(fitted, textOnly, canUse4K) {
58
+ if (!fitted || fitted.omit || !fitted.size || ['none', 'auto'].includes(fitted.size)) return undefined;
59
+ if (textOnly) return fitted.width + '*' + fitted.height;
60
+ const text = String(fitted.size).toUpperCase();
61
+ const tier = /^(1|2|4)K$/.exec(text);
62
+ if (tier) {
63
+ if (tier[1] === '4' && !canUse4K) throw new Error('万相 2.7 的这项操作最高支持 2K,请调低出图尺寸。');
64
+ return text;
65
+ }
66
+ const pixels = fitted.width * fitted.height;
67
+ if (!canUse4K && pixels > 2048 ** 2) throw new Error('万相 2.7 的这项操作最高支持 2K,请调低出图尺寸。');
68
+ return fitted.width + '*' + fitted.height;
21
69
  }
22
70
 
23
- async function urlToImage(url, signal) {
24
- return fetchImageUrl(String(url), signal);
71
+ /** 保留已存的适配器 id,只按模型选择万相的新一代接口。 */
72
+ export function wanMultimodalVariant(adapter, model) {
73
+ const textOnly = WAN_26_T2I.test(model);
74
+ if (!textOnly && !WAN_27_IMAGE.test(model)) return adapter;
75
+ const endpoints = { generate: WAN_MULTIMODAL_PATH, edit: textOnly ? '' : WAN_MULTIMODAL_PATH };
76
+ // 历史配置可能缓存了老端点的 input.prompt;新端点固定使用多模态消息字段。
77
+ const { fields } = detectFieldRule(model, '', adapter.id);
78
+ const operation = { input: 'explicit', fields };
79
+ return {
80
+ ...adapter,
81
+ async: false,
82
+ submit: WAN_MULTIMODAL_PATH,
83
+ taskSubmission: true,
84
+ acceptsHttpParams: true,
85
+ endpoints,
86
+ routes: { ...adapter.routes, ...endpoints },
87
+ output: WAN_MULTIMODAL_OUTPUT,
88
+ operations: {
89
+ generate: operation,
90
+ ...(!textOnly ? { edit: { ...operation, maxImages: 9, imageTypes: ['image/jpeg', 'image/png', 'image/bmp', 'image/webp'] } } : {})
91
+ },
92
+ async execute(kind, provider, input, signal, hooks) {
93
+ const images = kind === 'edit' ? input.images || [] : [];
94
+ if (kind === 'edit' && !images.length) throw new Error('百炼万相图生图需要至少一张参考图');
95
+ const body = { input: { messages: [{ role: 'user' }] } };
96
+ if (images.length) applyFields(body, { image: fields.image }, { image: images });
97
+ const values = { model: input.model, prompt: String(input.prompt || ''), negative: negativeOf(input), n: 1 };
98
+ applyFields(body, fields, { ...values, prompt: promptParts(fields, values).prompt });
99
+ const size = wanMultimodalSize(input.fitted, textOnly, kind === 'generate' && WAN_27_IMAGE_PRO.test(input.model));
100
+ if (size) body.parameters.size = size;
101
+ return executeBuiltImage(kind, this, provider, input, WAN_MULTIMODAL_PATH, body, signal, {
102
+ protectedPaths: ['parameters.size', 'parameters.n']
103
+ }, hooks);
104
+ }
105
+ };
25
106
  }
26
107
 
27
108
  export const CN_ADAPTERS = [
28
109
  {
29
110
  id: 'dashscope-qwen-image',
30
- label: '阿里云百炼 · Qwen-Image',
111
+ label: 'protocol.dashscope-qwen-image',
112
+ acceptsHttpParams: true,
31
113
  match: (provider, model) => /dashscope\.aliyuncs\.com/i.test(baseUrlOf(provider)) && /qwen-image/i.test(String(model || '')),
32
114
  local: false,
33
- endpoints: { generate: '/services/aigc/multimodal-generation/generation', edit: '' },
115
+ endpoints: { generate: '/services/aigc/multimodal-generation/generation', edit: '/services/aigc/multimodal-generation/generation' },
116
+ routes: { generate: '/services/aigc/multimodal-generation/generation', edit: '/services/aigc/multimodal-generation/generation', models: '' },
34
117
  transport: { generate: 'json', edit: 'json' },
35
118
  maxN: 6,
36
119
  editFields: [],
37
- // 百炼原生:size 用星号分隔,512²–2048²,比例 1:8–8:1。
38
- size: {
39
- control: 'wh', style: 'string', field: 'size', separator: '*', allowCustom: true,
40
- minPixels: 262144, maxPixels: 4194304, hint: 'modelDecides'
41
- },
42
- async execute(kind, provider, input, signal) {
43
- if (kind === 'edit') throw new Error('百炼 Qwen-Image 暂未支持参考图编辑;请换用支持编辑的模型。');
44
- const fitted = input.fitted && !input.fitted.omit ? input.fitted : { width: 1024, height: 1024 };
45
- const parameters = { n: 1, size: fitted.width + '*' + fitted.height };
46
- if (input.negativePrompt) parameters.negative_prompt = String(input.negativePrompt);
47
- const body = {
48
- model: input.model,
49
- input: { messages: [{ role: 'user', content: [{ text: promptOf(input) }] }] },
50
- parameters: parameters
51
- };
52
- const response = await request(baseUrlOf(provider) + '/services/aigc/multimodal-generation/generation', {
53
- method: 'POST',
54
- headers: headersFor(provider, false, null, this),
55
- body: JSON.stringify(body),
56
- signal: signal
57
- });
58
- const payload = await readJsonResponse(response, 32 * 1024 * 1024);
59
- const content = payload && payload.output && payload.output.choices
60
- && payload.output.choices[0] && payload.output.choices[0].message
61
- && payload.output.choices[0].message.content;
62
- for (const item of Array.isArray(content) ? content : []) {
63
- if (item && item.image) return urlToImage(item.image, signal);
64
- }
65
- throw new Error('百炼 Qwen-Image 没有返回图片');
66
- }
67
- },
68
- {
69
- id: 'zhipu',
70
- label: '智谱 BigModel',
71
- match: (provider) => /(^|\.)bigmodel\.cn$/i.test(String((provider && provider.baseUrl) || '').replace(/^https?:\/\//i, '').split('/')[0]),
72
- local: false,
73
- endpoints: { generate: '/images/generations', edit: '' },
74
- transport: { generate: 'json', edit: 'json' },
75
- maxN: 1,
76
- editFields: [],
77
- // glm-image 与 cogview 的限制不一样:前者 1024–2048 且 32 的倍数,后者 512–2048 且 16 的倍数。
78
- size: { control: 'wh', style: 'string', field: 'size', allowCustom: true, multiple: 32, minSide: 1024, maxSide: 2048, maxPixels: 4194304 },
79
- sizeByModel: [
80
- {
81
- match: /cogview/i,
82
- size: { control: 'wh', style: 'string', field: 'size', allowCustom: true, multiple: 16, minSide: 512, maxSide: 2048, maxPixels: 2097152 }
120
+ // 输出格式描述符:图片在 output.choices[0].message.content[].image,取第一个带 image 的项。
121
+ // `as:'url'` 只认 http(s)——迁移前对 item.image 不做校验,相对路径/垃圾串会变成一次
122
+ // 注定失败的请求;这里改成跳过(后面若有合法 URL 就能拿到)。
123
+ output: outputProfile({
124
+ kind: 'json',
125
+ pick: [{ path: 'output.choices.0.message.content[].image', as: 'url' }],
126
+ maxBytes: 32 * 1024 * 1024,
127
+ emptyMessage: '百炼 Qwen-Image 没有返回图片'
128
+ }, 'dashscope-qwen-image'),
129
+ async execute(kind, provider, input, signal, hooks) {
130
+ // 生成与编辑是同一个原生多模态端点:编辑时把参考图放进 content 的 image 项。
131
+ // 提示词与参考图的落点(input.messages[0].content[],分别包成 { text } / { image })
132
+ // 都来自模板;content[] 之外的 role 是消息信封,模板不描述它。
133
+ const fields = fieldsFor(this, provider, input.model);
134
+ const body = { input: { messages: [{ role: 'user' }] } };
135
+ const images = kind === 'edit'
136
+ ? (input.images || []).filter((image) => image && image.buffer && image.contentType).slice(0, 3)
137
+ : [];
138
+ if (kind === 'edit') {
139
+ if (!images.length) throw new Error('百炼 Qwen-Image 图生图需要一张参考图');
140
+ // 老 body 的顺序是 image 项在前、text 项在后;applyFields 按模板键序追加,所以分两次写。
141
+ applyFields(body, { image: fields.image }, { image: images });
83
142
  }
84
- ],
85
- async execute(kind, provider, input, signal) {
86
- if (kind === 'edit') throw new Error('智谱 BigModel 暂未支持参考图编辑;请换用支持编辑的模型。');
87
- const body = { model: input.model, prompt: promptOf(input) };
88
- const size = sizeOf(input);
89
- if (size) body.size = size;
90
- const quality = String(input.quality || '').trim().toLowerCase();
91
- if (quality && quality !== 'off' && quality !== 'auto') body.quality = quality;
92
- const response = await request(baseUrlOf(provider) + '/images/generations', {
93
- method: 'POST',
94
- headers: headersFor(provider, false, null, this),
95
- body: JSON.stringify(body),
96
- signal: signal
97
- });
98
- const payload = await readJsonResponse(response, 32 * 1024 * 1024);
99
- const first = payload && Array.isArray(payload.data) ? payload.data[0] : null;
100
- if (first && first.url) return urlToImage(first.url, signal);
101
- if (first && first.b64_json) {
102
- const decoded = base64ToImage(first.b64_json);
103
- if (decoded) return decoded;
143
+ applyFields(body, { prompt: fields.prompt }, { prompt: promptOf(input) });
144
+ // 编辑接口不收尺寸、也不发负面词字段:老实现的这两个分支留在协议里(用哪条模板由协议决定)。
145
+ applyFields(
146
+ body,
147
+ kind === 'edit'
148
+ ? { model: fields.model, n: fields.n }
149
+ : { model: fields.model, n: fields.n, negative: fields.negative },
150
+ { model: input.model, n: 1, negative: negativeOf(input) }
151
+ );
152
+ // 尺寸不属于六个逻辑字段:百炼用 `W*H`,编辑端不发。老实现在缺省时退回 1024x1024。
153
+ if (kind !== 'edit') {
154
+ const size = input.fitted && !input.fitted.omit ? input.fitted : { width: 1024, height: 1024 };
155
+ body.parameters = Object.assign({}, body.parameters, { size: size.width + '*' + size.height });
104
156
  }
105
- throw new Error('智谱 BigModel 没有返回图片');
157
+ return executeBuiltImage(kind, this, provider, input, this.endpoints[kind], body, signal, undefined, hooks);
106
158
  }
107
159
  }
108
160
  ];