koishi-plugin-p-draw 1.6.2 → 1.6.3

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.
package/index.js CHANGED
@@ -63,7 +63,7 @@ exports.Config = Schema.intersect([
63
63
 
64
64
  Schema.object({
65
65
  qualityPrefix: Schema.string().default('').description('质量词前缀(Aesthetic 1.1 建议留空;Base 模型可填 masterpiece, best quality, score_7)'),
66
- negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词'),
66
+ negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词。推荐值就是当前默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts(Aesthetic 1.1 适用)。若用 Base 模型,可再加 score_4, score_5, score_6;不想要画师署名可保留 artist name'),
67
67
  styleTags: Schema.string().default('').description('画风 tags'),
68
68
  defaultArtistTags: Schema.string().default('').description('备用画师 tags'),
69
69
  activeArtistPreset: Schema.string().default('').description('启用的画师组名称'),
@@ -123,7 +123,22 @@ exports.Config = Schema.intersect([
123
123
  promptOptimizeEnabled: Schema.boolean().default(false).description('启用自然语言优化(需配置下面的 LLM 接口)'),
124
124
  llmBaseUrl: Schema.string().default('').description('LLM 接口地址(OpenAI 兼容,如 https://api.deepseek.com/v1)'),
125
125
  llmApiKey: Schema.string().role('secret').default('').description('LLM API Key'),
126
- llmModel: Schema.string().default('').description('LLM 模型名(留空则不优化)'),
126
+ llmProxy: Schema.string().default('').description('仅 LLM 使用代理(留空直连)。格式 http://127.0.0.1:7890 / socks5://127.0.0.1:7891,可省略 http://。通道内单独填了 proxy 则优先用通道的'),
127
+ llmModel: Schema.string().default('').description('LLM 模型名(旧版单模型;请在 llmModels 里配置,这里留空即可)'),
128
+ llmModels: Schema.array(Schema.string()).default([]).description('主通道的模型名列表,按顺序逐个尝试(如 ["deepseek-chat","gpt-4o-mini"])'),
129
+ llmChannels: Schema.dict(Schema.object({
130
+ baseUrl: Schema.string().description('接口地址(OpenAI 兼容)'),
131
+ apiKey: Schema.string().role('secret').description('API Key'),
132
+ models: Schema.array(Schema.string()).description('该通道的模型名列表,按顺序尝试'),
133
+ proxy: Schema.string().description('该通道专用代理(留空则用上面的 llmProxy)'),
134
+ }).description('通道')).default({}).description('附加通道(中转站/备用站):主通道全部模型都失败后,按顺序继续尝试这些通道'),
135
+ llmChannelOrder: Schema.array(Schema.string()).default([]).description('附加通道的尝试顺序(填通道名;留空则按配置里的先后顺序)'),
136
+ llmThinking: Schema.union([
137
+ Schema.const('auto').description('仅 DeepSeek 系接口发送 thinking(推荐)'),
138
+ Schema.const('always').description('总是发送 thinking'),
139
+ Schema.const('never').description('从不发送 thinking(部分中转站必须选这个)'),
140
+ ]).default('auto').description('是否发送 DeepSeek 专有的 thinking 字段;非 DeepSeek 模型带了通常会被拒'),
141
+ llmExtraBody: Schema.string().role('textarea').default('{}').description('附加请求体 JSON(最后覆盖),用于中转站私有参数,如 {"enable_thinking":false}'),
127
142
  llmMaxTokens: Schema.number().default(1000).description('LLM 输出上限'),
128
143
  promptOptimizeTemplate: Schema.string().description('优化模板(支持 {theme} {search_block} {character_rule} 占位符)').default('你是为 Anima 图像生成模型编写正面提示词的 AI 画师。\n\n请根据用户的原始要求设计一幅完整、协调、具有视觉吸引力的画面,并将结果输出为英文 Danbooru-style tags。\n\n输出要求:\n- 只输出一行英文 tags,使用英文逗号分隔。\n- 不要输出解释、分析、标题、编号、Markdown、代码块或中文。\n- 不要输出 masterpiece、best quality、score 等质量前缀。\n- 不要输出画师 tags;质量词和画师组会由程序另行拼接。\n- 尽量使用模型容易理解的可见画面描述。\n- 保持用户明确指定的角色、主体、人数、关键服装、动作、表情和道具。\n- 除上述明确要求外,可以自由决定服装细节、姿态、构图、镜头、背景、环境、光影、色彩、氛围、前景和特效。\n- 以最终图像协调、精致、有表现力和好看为优先,不需要机械追求固定 Tag 数量。\n- 不要为了数量重复同义词;画面已经完整时即可停止。\n- 请自行解决明显冲突,直接输出你认为最适合生成最终画面的版本。\n\n角色和动态上下文:\n{character_rule}\n{search_block}\n\n用户原始要求:\n{theme}'),
129
144
  }).description('⑨ 提示词优化 / LLM').collapse(),
@@ -131,6 +146,7 @@ exports.Config = Schema.intersect([
131
146
  Schema.object({
132
147
  webSearchEnabled: Schema.boolean().default(false).description('启用联网搜索(指令里写「联网/搜索/查一下」触发)'),
133
148
  tavilyApiKey: Schema.string().role('secret').default('').description('Tavily API Key(https://tavily.com)'),
149
+ tavilyProxy: Schema.string().default('').description('仅联网搜索(Tavily)使用代理(留空直连)。格式 http://127.0.0.1:7890,可省略 http://。与 LLM / 视觉校验的代理互相独立'),
134
150
  webSearchMaxResults: Schema.number().default(5).description('搜索结果数量'),
135
151
  webSearchDepth: Schema.string().default('basic').description('搜索深度(basic / advanced)'),
136
152
  webSearchQueryTemplate: Schema.string().default('{prompt} 角色 外观 立绘 服装 配色 武器 官方图 official art character design outfit appearance wiki fandom').description('搜索词模板({prompt} 代表用户需求)'),
@@ -143,7 +159,16 @@ exports.Config = Schema.intersect([
143
159
  multiSendDegradedCandidate: Schema.boolean().default(true).description('全部候选不达标时仍发送最优候选'),
144
160
  verifyLlmBaseUrl: Schema.string().default('').description('视觉校验接口地址(OpenAI 兼容;留空跳过校验)'),
145
161
  verifyLlmApiKey: Schema.string().role('secret').default('').description('视觉校验 API Key'),
146
- verifyLlmModel: Schema.string().default('').description('视觉校验模型名(需支持图片输入,如 qwen-vl)'),
162
+ verifyLlmProxy: Schema.string().default('').description('仅视觉校验使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的'),
163
+ verifyLlmModel: Schema.string().default('').description('视觉校验模型名(旧版单模型;请在 verifyLlmModels 里配置)'),
164
+ verifyLlmModels: Schema.array(Schema.string()).default([]).description('视觉通道的模型名列表,按顺序逐个尝试(需支持图片输入,如 qwen-vl)'),
165
+ verifyLlmChannels: Schema.dict(Schema.object({
166
+ baseUrl: Schema.string().description('接口地址(OpenAI 兼容)'),
167
+ apiKey: Schema.string().role('secret').description('API Key'),
168
+ models: Schema.array(Schema.string()).description('该通道的模型名列表,按顺序尝试'),
169
+ proxy: Schema.string().description('该通道专用代理(留空则用上面的 verifyLlmProxy)'),
170
+ }).description('通道')).default({}).description('视觉校验的附加通道:主通道全部失败后按顺序继续尝试'),
171
+ verifyLlmChannelOrder: Schema.array(Schema.string()).default([]).description('视觉附加通道的尝试顺序(填通道名;留空则按配置先后顺序)'),
147
172
  }).description('⑪ 多人视觉校验').collapse(),
148
173
 
149
174
  Schema.object({
@@ -174,6 +199,8 @@ const {
174
199
  renderMultiPersonCharacter, multiPersonAutoSize,
175
200
  } = require('./lib/multi')
176
201
  const { buildComfyClient } = require('./lib/http')
202
+ const { createOutboundFetch, normalizeProxyUrl, proxySupportAvailable } = require('./lib/net')
203
+ const { buildLlmChain, hasLlm, buildChatBody, runLlmChain } = require('./lib/llm')
177
204
  exports.apply = async function apply(ctx, cfg) {
178
205
  // 注意:不在此处 extend p_system 表 —— 该表由 p-qiandao 等 p 系插件创建。
179
206
  // 重复声明同一张表可能导致 Koishi 的 schema 迁移冲突,拖垮签到插件。
@@ -181,6 +208,11 @@ exports.apply = async function apply(ctx, cfg) {
181
208
  const logger = ctx.logger('p-draw')
182
209
  ctx.i18n.define('zh-CN', zhCN)
183
210
 
211
+ // 出站请求:代理按用途各自传入(联网搜索 / 文本 LLM / 视觉校验互不影响)
212
+ const outboundFetch = createOutboundFetch({
213
+ onWarn: (message) => logger.warn(message),
214
+ })
215
+
184
216
  // 运行时数据持久化到数据库,而不是调用 scope.update
185
217
  // 写 koishi.yml:scope.update 会触发插件重载,导致正在生成的图被 dispose(Context has
186
218
  // been disposed),且重复写入时配置文件会被冲掉(曾出现配置整体恢复成默认)。
@@ -749,7 +781,7 @@ exports.apply = async function apply(ctx, cfg) {
749
781
  const cfgVal = Number(overrides.cfg) || workCfg.cfg
750
782
  const seed = Number(overrides.seed) || crypto.randomInt(1, 2 ** 32 - 1)
751
783
  const negativePrompt = joinPromptParts([overrides.negativePrompt || cfg.negativePrompt || ''])
752
- const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), workflowOpts())
784
+ const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), Object.assign({}, workflowOpts(), { modelParams: modelSpecific }))
753
785
 
754
786
  const clientId = crypto.randomUUID()
755
787
  const submit = await comfyPost('/prompt', { prompt: promptBody, client_id: clientId }, 20000)
@@ -879,7 +911,7 @@ exports.apply = async function apply(ctx, cfg) {
879
911
  const query = queryTemplate.includes('{prompt}')
880
912
  ? queryTemplate.replace(/\{prompt\}/g, prompt).trim()
881
913
  : `${prompt} ${queryTemplate}`.trim()
882
- const rawRes = await fetch('https://api.tavily.com/search', {
914
+ const rawRes = await outboundFetch('https://api.tavily.com/search', {
883
915
  method: 'POST',
884
916
  headers: { 'Content-Type': 'application/json' },
885
917
  body: JSON.stringify({
@@ -890,7 +922,7 @@ exports.apply = async function apply(ctx, cfg) {
890
922
  topic: 'general',
891
923
  }),
892
924
  signal: controller.signal,
893
- })
925
+ }, cfg.tavilyProxy)
894
926
  if (!rawRes.ok) {
895
927
  const bodyText = await rawRes.text().catch(() => '')
896
928
  logger.warn(`联网搜索接口返回错误:HTTP ${rawRes.status} ${bodyText.slice(0, 200)}`)
@@ -921,12 +953,77 @@ exports.apply = async function apply(ctx, cfg) {
921
953
  }
922
954
  }
923
955
 
956
+ // 统一调用 LLM:按「通道 × 模型」候选链逐个尝试,返回首个成功结果。
957
+ // role='text' 用 llm* 配置,role='vision' 用 verifyLlm* 配置(需支持图片输入)。
958
+ async function callLlm({ role = 'text', system, user, images, maxTokens = 700, timeout = 120000 }) {
959
+ const chain = buildLlmChain(cfg, role)
960
+ if (!chain.length) {
961
+ return { ok: false, text: '', reason: 'llm_not_configured', candidate: null, errors: [] }
962
+ }
963
+
964
+ const messages = []
965
+ if (system) messages.push({ role: 'system', content: system })
966
+ if (images && images.length) {
967
+ messages.push({
968
+ role: 'user',
969
+ content: [
970
+ ...(user ? [{ type: 'text', text: user }] : []),
971
+ ...images.map((src) => ({ type: 'image_url', image_url: { url: src } })),
972
+ ],
973
+ })
974
+ } else {
975
+ messages.push({ role: 'user', content: user })
976
+ }
977
+
978
+ const result = await runLlmChain(chain, async (candidate) => {
979
+ const controller = new AbortController()
980
+ const timer = setTimeout(() => controller.abort(), timeout)
981
+ try {
982
+ const headers = { 'Content-Type': 'application/json' }
983
+ if (candidate.apiKey) headers.Authorization = `Bearer ${candidate.apiKey}`
984
+ const body = buildChatBody(cfg, { candidate, messages, maxTokens, defaultMaxTokens: maxTokens })
985
+ // 代理按用途分开:通道自带 proxy 优先,否则用该用途的默认代理
986
+ const purposeProxy = role === 'vision' ? cfg.verifyLlmProxy : cfg.llmProxy
987
+ const proxy = candidate.proxy || purposeProxy || ''
988
+ const rawRes = await outboundFetch(candidate.baseUrl + '/chat/completions', {
989
+ method: 'POST',
990
+ headers,
991
+ body: JSON.stringify(body),
992
+ signal: controller.signal,
993
+ }, proxy)
994
+ if (!rawRes.ok) {
995
+ const detail = await rawRes.text().catch(() => '')
996
+ throw new Error(`HTTP ${rawRes.status}${detail ? ' ' + detail.slice(0, 200) : ''}`)
997
+ }
998
+ const res = await rawRes.json()
999
+ const text = extractLlmText(res)
1000
+ if (!text) throw new Error('接口未返回可用的文本内容')
1001
+ return text
1002
+ } finally {
1003
+ clearTimeout(timer)
1004
+ }
1005
+ }, {
1006
+ onError: (candidate, message) => {
1007
+ if (cfg.outputLogs) logger.warn(`[p-draw] LLM 候选失败(${candidate.label} / ${candidate.model}):${message}`)
1008
+ },
1009
+ })
1010
+
1011
+ if (!result.ok) {
1012
+ const last = result.errors.length ? result.errors[result.errors.length - 1].message : 'unknown'
1013
+ return { ok: false, text: '', reason: last, candidate: null, errors: result.errors }
1014
+ }
1015
+ if (cfg.outputLogs && (chain.length > 1 || result.errors.length)) {
1016
+ logger.info(`[p-draw] LLM 命中 ${result.candidate.label} / ${result.candidate.model}(前面失败 ${result.errors.length} 个)`)
1017
+ }
1018
+ return { ok: true, text: result.value, candidate: result.candidate, errors: result.errors }
1019
+ }
1020
+
924
1021
  async function optimizePrompt(session, userPrompt, force = false, precomputedSearch = null) {
925
1022
  if (!cfg.promptOptimizeEnabled && !force) {
926
1023
  return { ok: true, prompt: userPrompt, reason: 'optimize_disabled' }
927
1024
  }
928
- if (!cfg.llmModel || !cfg.llmBaseUrl) {
929
- logger.warn('提示词优化已开启但未配置 llmModel / llmBaseUrl,跳过优化')
1025
+ if (!hasLlm(cfg)) {
1026
+ logger.warn('提示词优化已开启但未配置任何 LLM 通道(llmBaseUrl + llmModels),跳过优化')
930
1027
  return { ok: false, prompt: userPrompt, reason: 'llm_not_configured' }
931
1028
  }
932
1029
  let searchBlock = ''
@@ -949,50 +1046,17 @@ exports.apply = async function apply(ctx, cfg) {
949
1046
  .replace(/[ \t]+\n/g, '\n')
950
1047
  .replace(/\n{3,}/g, '\n\n')
951
1048
  .trim()
952
- const controller = new AbortController()
953
- const timer = setTimeout(() => controller.abort(), 120000)
954
- try {
955
- const headers = { 'Content-Type': 'application/json' }
956
- if (cfg.llmApiKey) headers.Authorization = `Bearer ${cfg.llmApiKey}`
957
- const rawRes = await fetch(
958
- String(cfg.llmBaseUrl).replace(/\/+$/, '') + '/chat/completions',
959
- {
960
- method: 'POST',
961
- headers,
962
- body: JSON.stringify({
963
- model: cfg.llmModel,
964
- messages: [
965
- { role: 'system', content: rendered },
966
- { role: 'user', content: userPrompt },
967
- ],
968
- max_tokens: Math.max(64, parseInt(cfg.llmMaxTokens) || 1000),
969
- // DeepSeek V4 默认开启思考模式,改为关闭以保证 content 直接返回 tags
970
- thinking: { type: 'disabled' },
971
- }),
972
- signal: controller.signal,
973
- },
974
- )
975
- if (!rawRes.ok) {
976
- const bodyText = await rawRes.text().catch(() => '')
977
- const reason = `HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`
978
- logger.warn(`提示词优化接口返回错误:${reason}`)
979
- return { ok: false, prompt: userPrompt, reason }
980
- }
981
- const res = await rawRes.json()
982
- const text = extractLlmText(res)
983
- if (!text) {
984
- const reason = '接口未返回可用的文本内容'
985
- logger.warn(`提示词优化:${reason} 原始响应=${JSON.stringify(res).slice(0, 500)}`)
986
- return { ok: false, prompt: userPrompt, reason }
987
- }
988
- return { ok: true, prompt: text }
989
- } catch (e) {
990
- const reason = String(e && e.message || e)
991
- logger.warn(`提示词优化失败:${reason}`)
992
- return { ok: false, prompt: userPrompt, reason }
993
- } finally {
994
- clearTimeout(timer)
1049
+ const outcome = await callLlm({
1050
+ role: 'text',
1051
+ system: rendered,
1052
+ user: userPrompt,
1053
+ maxTokens: cfg.llmMaxTokens,
1054
+ })
1055
+ if (!outcome.ok) {
1056
+ logger.warn(`提示词优化失败(已尝试 ${outcome.errors.length} 个候选):${outcome.reason}`)
1057
+ return { ok: false, prompt: userPrompt, reason: outcome.reason }
995
1058
  }
1059
+ return { ok: true, prompt: outcome.text }
996
1060
  }
997
1061
 
998
1062
  // ---------------- 提示词组装 ----------------
@@ -1024,43 +1088,13 @@ exports.apply = async function apply(ctx, cfg) {
1024
1088
  // ---------------- 多人(移植自 anima /anm 多人) ----------------
1025
1089
 
1026
1090
  // 通用 LLM 调用:system + user,返回文本;失败抛错由调用方捕获。
1027
- async function llmChat({ system, user, maxTokens = 700, baseUrl, apiKey, model, timeout = 120000 }) {
1028
- const resolvedBase = baseUrl || cfg.llmBaseUrl
1029
- const resolvedKey = apiKey || cfg.llmApiKey
1030
- const resolvedModel = model || cfg.llmModel
1031
- const controller = new AbortController()
1032
- const timer = setTimeout(() => controller.abort(), timeout)
1033
- try {
1034
- const headers = { 'Content-Type': 'application/json' }
1035
- if (resolvedKey) headers.Authorization = `Bearer ${resolvedKey}`
1036
- const rawRes = await fetch(
1037
- String(resolvedBase).replace(/\/+$/, '') + '/chat/completions',
1038
- {
1039
- method: 'POST',
1040
- headers,
1041
- body: JSON.stringify({
1042
- model: resolvedModel,
1043
- messages: [
1044
- { role: 'system', content: system },
1045
- { role: 'user', content: user },
1046
- ],
1047
- max_tokens: Math.max(64, parseInt(maxTokens) || 700),
1048
- thinking: { type: 'disabled' },
1049
- }),
1050
- signal: controller.signal,
1051
- },
1052
- )
1053
- if (!rawRes.ok) {
1054
- const bodyText = await rawRes.text().catch(() => '')
1055
- throw new Error(`HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`)
1056
- }
1057
- const res = await rawRes.json()
1058
- const text = extractLlmText(res)
1059
- if (!text) throw new Error('接口未返回可用的文本内容')
1060
- return text
1061
- } finally {
1062
- clearTimeout(timer)
1091
+ // 多人规划用的文本 LLM 调用:统一走「通道 × 模型」回退链,全部失败才抛错。
1092
+ async function llmChat({ system, user, maxTokens = 700, timeout = 120000 }) {
1093
+ const outcome = await callLlm({ role: 'text', system, user, maxTokens, timeout })
1094
+ if (!outcome.ok) {
1095
+ throw new Error(outcome.reason === 'llm_not_configured' ? '未配置任何 LLM 通道' : outcome.reason)
1063
1096
  }
1097
+ return outcome.text
1064
1098
  }
1065
1099
 
1066
1100
  // 多人规划:让 LLM 输出结构化场景 JSON(2-4 人)。
@@ -1298,9 +1332,7 @@ exports.apply = async function apply(ctx, cfg) {
1298
1332
  // 视觉校验(anima_verify + generation_verifier 移植):对生成的图片跑视觉 LLM,
1299
1333
  // 不合格则用相同提示词重试(最多 multiCandidateCount 张),按多候选规则挑选并返回结果。
1300
1334
  async function verifyGeneratedImages(session, images, userRequest, prompt, size, planCount, unet, negativePrompt) {
1301
- const verifyBaseUrl = String(cfg.verifyLlmBaseUrl || '').trim()
1302
- const verifyModel = String(cfg.verifyLlmModel || '').trim()
1303
- if (!verifyBaseUrl || !verifyModel) {
1335
+ if (!hasLlm(cfg, 'vision')) {
1304
1336
  return { ok: true, degraded: true, message: '', verdict: null, outputs: images, prompt, negativePrompt }
1305
1337
  }
1306
1338
  const passScore = Math.max(0, Math.min(10, parseInt(cfg.multiVerifyPassScore) || 6))
@@ -1314,38 +1346,17 @@ exports.apply = async function apply(ctx, cfg) {
1314
1346
  let currentPrompt = prompt
1315
1347
  let currentNegativePrompt = negativePrompt
1316
1348
 
1349
+ // 视觉校验同样走「通道 × 模型」回退链(role='vision' 用 verifyLlm* 配置)
1317
1350
  async function verifyOnce(imgs, userReq) {
1318
- const controller = new AbortController()
1319
- const timer = setTimeout(() => controller.abort(), 120000)
1320
- try {
1321
- const headers = { 'Content-Type': 'application/json' }
1322
- if (cfg.verifyLlmApiKey) headers.Authorization = `Bearer ${cfg.verifyLlmApiKey}`
1323
- const content = imgs.map(src => ({ type: 'image_url', image_url: { url: src } }))
1324
- const rawRes = await fetch(
1325
- verifyBaseUrl.replace(/\/+$/, '') + '/chat/completions',
1326
- {
1327
- method: 'POST',
1328
- headers,
1329
- body: JSON.stringify({
1330
- model: verifyModel,
1331
- messages: [
1332
- { role: 'system', content: systemPrompt },
1333
- { role: 'user', content: [{ type: 'text', text: `用户的原始画图请求(中文):\n${userReq}\n\n请审查这张图片。` }, ...content] },
1334
- ],
1335
- max_tokens: Math.max(256, parseInt(cfg.llmMaxTokens) || 700),
1336
- }),
1337
- signal: controller.signal,
1338
- },
1339
- )
1340
- if (!rawRes.ok) {
1341
- const bodyText = await rawRes.text().catch(() => '')
1342
- throw new Error(`HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`)
1343
- }
1344
- const res = await rawRes.json()
1345
- return extractLlmText(res)
1346
- } finally {
1347
- clearTimeout(timer)
1348
- }
1351
+ const outcome = await callLlm({
1352
+ role: 'vision',
1353
+ system: systemPrompt,
1354
+ user: `用户的原始画图请求(中文):\n${userReq}\n\n请审查这张图片。`,
1355
+ images: imgs,
1356
+ maxTokens: Math.max(256, parseInt(cfg.llmMaxTokens) || 700),
1357
+ })
1358
+ if (!outcome.ok) throw new Error(outcome.reason)
1359
+ return outcome.text
1349
1360
  }
1350
1361
 
1351
1362
  function extractVerifyJson(text) {
@@ -1537,7 +1548,7 @@ exports.apply = async function apply(ctx, cfg) {
1537
1548
  if (!ready.ok) return ready.message
1538
1549
 
1539
1550
  // 多人规划(强制依赖 LLM)
1540
- if (!cfg.llmModel || !cfg.llmBaseUrl) {
1551
+ if (!hasLlm(cfg)) {
1541
1552
  return session.text('.multi-no-llm')
1542
1553
  }
1543
1554
 
@@ -2014,8 +2025,8 @@ exports.apply = async function apply(ctx, cfg) {
2014
2025
  let interactiveCoupon = false
2015
2026
  if (!raw) {
2016
2027
  const globalOpt = cfg.promptOptimizeEnabled
2017
- const adminOpt = !globalOpt && isAdmin && cfg.llmModel && cfg.llmBaseUrl
2018
- const tokenOpt = !globalOpt && !isAdmin && cfg.llmModel && cfg.llmBaseUrl
2028
+ const adminOpt = !globalOpt && isAdmin && hasLlm(cfg)
2029
+ const tokenOpt = !globalOpt && !isAdmin && hasLlm(cfg)
2019
2030
  if (globalOpt) {
2020
2031
  if (shouldOptimizePerImage({ count, enabled: true, admin: false })) {
2021
2032
  perImageOptimize = true
package/lib/i18n.js CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  const zhCN = {
4
4
  comfyuiBaseUrl: { $description: 'ComfyUI 地址' },
5
+ tavilyProxy: { $description: '仅联网搜索(Tavily)使用代理(留空直连)。与 LLM / 视觉校验的代理互相独立' },
6
+ llmProxy: { $description: '仅 LLM 使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的' },
7
+ verifyLlmProxy: { $description: '仅视觉校验使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的' },
5
8
  workflow: { $description: '工作流类型(内置 anima_t2i)' },
6
9
  customWorkflowEnabled: { $description: '使用自定义 ComfyUI 工作流 JSON' },
7
10
  customWorkflowPath: { $description: '自定义工作流 JSON 路径(相对 Koishi 运行目录,例如 data/p-draw/workflows/anima-aesthetic-v1.1.json;插件目录作为回退)' },
@@ -27,11 +30,16 @@ const zhCN = {
27
30
  scheduler: { $description: '调度器' },
28
31
  qualityPrefix: { $description: '质量词前缀(使用 Aesthetic 1.1 时建议留空;Base 模型可填 masterpiece, best quality, score_7)' },
29
32
  skipQualityPrefixForCustomWorkflow: { $description: '启用自定义工作流时自动跳过质量前缀注入(Aesthetic 模型不需要质量标签)' },
30
- negativePrompt: { $description: '负面提示词(Aesthetic 1.1 推荐值)' },
33
+ negativePrompt: { $description: '负面提示词。推荐值即默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts' },
31
34
  promptOptimizeEnabled: { $description: '启用自然语言优化(需要配置下方 LLM 接口)' },
32
35
  llmBaseUrl: { $description: 'LLM 接口地址(OpenAI 兼容,例如 https://api.deepseek.com/v1)' },
33
36
  llmApiKey: { $description: 'LLM API Key' },
34
- llmModel: { $description: 'LLM 模型名(留空则不优化,原样生图)' },
37
+ llmModel: { $description: 'LLM 模型名(旧版单模型;请在 llmModels 里配置)' },
38
+ llmModels: { $description: '主通道的模型名列表,按顺序逐个尝试' },
39
+ llmChannels: { $description: '附加通道(中转站/备用站):主通道全部模型失败后按顺序继续尝试' },
40
+ llmChannelOrder: { $description: '附加通道的尝试顺序(填通道名;留空则按配置先后顺序)' },
41
+ llmThinking: { $description: '是否发送 DeepSeek 专有的 thinking 字段(auto / always / never)' },
42
+ llmExtraBody: { $description: '附加请求体 JSON(最后覆盖),用于中转站私有参数' },
35
43
  llmMaxTokens: { $description: 'LLM 输出上限' },
36
44
  webSearchEnabled: { $description: '启用联网搜索(指令里写“联网/搜索/查一下”等触发)' },
37
45
  tavilyApiKey: { $description: 'Tavily API Key(联网搜索用,https://tavily.com 申请)' },
@@ -59,7 +67,10 @@ const zhCN = {
59
67
  multiSendDegradedCandidate: { $description: '多人候选全部不达标时仍发送最优候选' },
60
68
  verifyLlmBaseUrl: { $description: '视觉校验 LLM 接口地址(OpenAI 兼容;留空则跳过校验)' },
61
69
  verifyLlmApiKey: { $description: '视觉校验 LLM API Key' },
62
- verifyLlmModel: { $description: '视觉校验 LLM 模型名(需支持图片输入,如 qwen-vl)' },
70
+ verifyLlmModel: { $description: '视觉校验模型名(旧版单模型;请在 verifyLlmModels 里配置)' },
71
+ verifyLlmModels: { $description: '视觉通道的模型名列表,按顺序逐个尝试(需支持图片输入)' },
72
+ verifyLlmChannels: { $description: '视觉校验的附加通道:主通道全部失败后按顺序继续尝试' },
73
+ verifyLlmChannelOrder: { $description: '视觉附加通道的尝试顺序(填通道名;留空则按配置先后顺序)' },
63
74
  adminOnly: { $description: '仅管理员可用(adminUsers 中的用户)' },
64
75
  allowedUserIds: { $description: '用户白名单(QQ 号,留空表示不限制)' },
65
76
  blockedUserIds: { $description: '用户黑名单(QQ 号,黑名单优先于白名单)' },
package/lib/llm.js ADDED
@@ -0,0 +1,153 @@
1
+ // LLM 通道与模型回退。
2
+ //
3
+ // 一个「通道」= 一组 baseUrl + apiKey;通道内可以填多个模型名。
4
+ // 调用顺序:主通道的模型逐个试 → 全挂 → 下一个通道的模型逐个试。
5
+ // 纯函数 + 一个 runner,不依赖 koishi,可独立单测。
6
+
7
+ const THINKING_MODES = new Set(['auto', 'always', 'never'])
8
+
9
+ // 支持数组或逗号/换行分隔的字符串
10
+ function splitModelList(value) {
11
+ const out = []
12
+ const push = (item) => {
13
+ const text = String(item == null ? '' : item).trim()
14
+ if (text && !out.includes(text)) out.push(text)
15
+ }
16
+ if (Array.isArray(value)) value.forEach(push)
17
+ else if (typeof value === 'string') value.split(/[,,\n]/).forEach(push)
18
+ return out
19
+ }
20
+
21
+ function normalizeBaseUrl(value) {
22
+ return String(value == null ? '' : value).trim().replace(/\/+$/, '')
23
+ }
24
+
25
+ // 通道的模型列表:models(数组)优先,兼容旧的单个 model 字段
26
+ function channelModels(channel) {
27
+ const models = splitModelList(channel && channel.models)
28
+ for (const model of splitModelList(channel && channel.model)) {
29
+ if (!models.includes(model)) models.push(model)
30
+ }
31
+ return models
32
+ }
33
+
34
+ // 附加通道,按 llmChannelOrder 排序;未列出的通道补在后面,避免漏配就丢通道
35
+ function collectChannels(cfg, role) {
36
+ const isVision = role === 'vision'
37
+ const dict = isVision ? cfg.verifyLlmChannels : cfg.llmChannels
38
+ if (!dict || typeof dict !== 'object') return []
39
+ const declared = splitModelList(isVision ? cfg.verifyLlmChannelOrder : cfg.llmChannelOrder)
40
+ const names = declared.filter(name => dict[name])
41
+ for (const name of Object.keys(dict)) {
42
+ if (!names.includes(name)) names.push(name)
43
+ }
44
+ return names.map(name => ({ name, channel: dict[name] }))
45
+ }
46
+
47
+ // 摊平成有序候选链:[{ baseUrl, apiKey, model, label }]
48
+ function buildLlmChain(cfg, role = 'text') {
49
+ const c = cfg || {}
50
+ const isVision = role === 'vision'
51
+ const primaryBase = normalizeBaseUrl(isVision ? c.verifyLlmBaseUrl : c.llmBaseUrl)
52
+ const primaryKey = String((isVision ? c.verifyLlmApiKey : c.llmApiKey) || '').trim()
53
+ const primaryModels = channelModels({
54
+ models: isVision ? c.verifyLlmModels : c.llmModels,
55
+ model: isVision ? c.verifyLlmModel : c.llmModel,
56
+ })
57
+
58
+ const candidates = []
59
+ const seen = new Set()
60
+ const add = (baseUrl, apiKey, model, label, proxy) => {
61
+ const base = normalizeBaseUrl(baseUrl)
62
+ if (!base || !model) return
63
+ const key = [base, String(apiKey || ''), model].join('\u0000')
64
+ if (seen.has(key)) return
65
+ seen.add(key)
66
+ candidates.push({ baseUrl: base, apiKey: String(apiKey || ''), model, label: label || base, proxy: String(proxy || '').trim() })
67
+ }
68
+
69
+ for (const model of primaryModels) add(primaryBase, primaryKey, model, '主通道', '')
70
+ for (const { name, channel } of collectChannels(c, role)) {
71
+ const base = channel && channel.baseUrl
72
+ const key = channel && channel.apiKey
73
+ // 通道可以单独指定代理;留空则用该用途的默认代理(由调用方决定)
74
+ const channelProxy = channel && channel.proxy
75
+ for (const model of channelModels(channel)) add(base, key, model, name, channelProxy)
76
+ }
77
+ return candidates
78
+ }
79
+
80
+ function hasLlm(cfg, role = 'text') {
81
+ return buildLlmChain(cfg, role).length > 0
82
+ }
83
+
84
+ function resolveThinkingMode(value) {
85
+ const mode = String(value == null ? '' : value).trim().toLowerCase()
86
+ return THINKING_MODES.has(mode) ? mode : 'auto'
87
+ }
88
+
89
+ // thinking 是 DeepSeek 专有字段,别的模型 / 中转站带上通常直接 400。
90
+ // auto:只有当 baseUrl 或模型名看起来是 DeepSeek 时才发。
91
+ function shouldSendThinking(cfg, candidate) {
92
+ const mode = resolveThinkingMode(cfg && cfg.llmThinking)
93
+ if (mode === 'always') return true
94
+ if (mode === 'never') return false
95
+ const haystack = `${(candidate && candidate.baseUrl) || ''} ${(candidate && candidate.model) || ''}`.toLowerCase()
96
+ return haystack.includes('deepseek')
97
+ }
98
+
99
+ function parseExtraBody(value) {
100
+ const raw = typeof value === 'string' ? value.trim() : ''
101
+ if (!raw) return {}
102
+ try {
103
+ const data = JSON.parse(raw)
104
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {}
105
+ } catch (e) {
106
+ return {}
107
+ }
108
+ }
109
+
110
+ // 请求体:基础字段 + 条件性 thinking + 用户自定义附加参数(最后覆盖)
111
+ function buildChatBody(cfg, { candidate, messages, maxTokens, defaultMaxTokens = 700 }) {
112
+ const body = {
113
+ model: candidate.model,
114
+ messages,
115
+ max_tokens: Math.max(64, parseInt(maxTokens) || defaultMaxTokens),
116
+ }
117
+ if (shouldSendThinking(cfg, candidate)) body.thinking = { type: 'disabled' }
118
+ return Object.assign(body, parseExtraBody(cfg && cfg.llmExtraBody))
119
+ }
120
+
121
+ // 依次尝试候选;attempt 抛错即视为该候选失败,继续下一个。
122
+ // 返回 { ok, candidate, value, errors },errors 里保留每次失败原因便于诊断。
123
+ async function runLlmChain(candidates, attempt, { onError } = {}) {
124
+ const errors = []
125
+ for (const candidate of candidates) {
126
+ try {
127
+ const value = await attempt(candidate)
128
+ return { ok: true, candidate, value, errors }
129
+ } catch (e) {
130
+ const message = String((e && e.message) || e || 'unknown')
131
+ errors.push({ model: candidate.model, label: candidate.label, message })
132
+ if (typeof onError === 'function') {
133
+ try { onError(candidate, message) } catch (err) { /* ignore */ }
134
+ }
135
+ }
136
+ }
137
+ return { ok: false, candidate: null, value: null, errors }
138
+ }
139
+
140
+ module.exports = {
141
+ THINKING_MODES,
142
+ splitModelList,
143
+ normalizeBaseUrl,
144
+ channelModels,
145
+ collectChannels,
146
+ buildLlmChain,
147
+ hasLlm,
148
+ resolveThinkingMode,
149
+ shouldSendThinking,
150
+ parseExtraBody,
151
+ buildChatBody,
152
+ runLlmChain,
153
+ }
package/lib/net.js ADDED
@@ -0,0 +1,85 @@
1
+ // 出站 HTTP:可选代理(Tavily / LLM / 视觉校验共用)。
2
+ //
3
+ // Node 内置 fetch 不支持直接用代理,这里通过 undici 的 ProxyAgent 挂 dispatcher。
4
+ // undici 属于可选依赖:拿不到时降级为直连,并且只告警一次,不影响其他功能。
5
+
6
+ let undiciModule = null
7
+ let undiciLoaded = false
8
+
9
+ function loadUndici() {
10
+ if (undiciLoaded) return undiciModule
11
+ undiciLoaded = true
12
+ try {
13
+ // eslint-disable-next-line global-require
14
+ undiciModule = require('undici')
15
+ } catch (e) {
16
+ undiciModule = null
17
+ }
18
+ return undiciModule
19
+ }
20
+
21
+ // 允许省略协议:127.0.0.1:7890 → http://127.0.0.1:7890
22
+ function normalizeProxyUrl(value) {
23
+ const raw = String(value == null ? '' : value).trim()
24
+ if (!raw) return ''
25
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`
26
+ }
27
+
28
+ // 是否能用上真实代理(undici 可用且 ProxyAgent 能构造)
29
+ const dispatcherCache = new Map()
30
+
31
+ function resolveDispatcher(proxyUrl) {
32
+ const url = normalizeProxyUrl(proxyUrl)
33
+ if (!url) return null
34
+ if (dispatcherCache.has(url)) return dispatcherCache.get(url)
35
+ const mod = loadUndici()
36
+ let dispatcher = null
37
+ if (mod && typeof mod.ProxyAgent === 'function') {
38
+ try {
39
+ dispatcher = new mod.ProxyAgent(url)
40
+ } catch (e) {
41
+ dispatcher = null
42
+ }
43
+ }
44
+ dispatcherCache.set(url, dispatcher)
45
+ return dispatcher
46
+ }
47
+
48
+ function proxySupportAvailable() {
49
+ const mod = loadUndici()
50
+ return Boolean(mod && typeof mod.ProxyAgent === 'function')
51
+ }
52
+
53
+ // 构造一个「按次指定代理」的 fetch:outboundFetch(url, options, proxyUrl)。
54
+ //
55
+ // 代理是分用途配置的(联网搜索 / 文本 LLM / 视觉校验各一套),所以这里不在工厂里
56
+ // 绑定代理,而是每次调用由调用方传入;proxyUrl 为空即直连。
57
+ function createOutboundFetch({ onWarn } = {}) {
58
+ const warned = new Set()
59
+ return async function outboundFetch(url, options = {}, proxyUrl = '') {
60
+ const proxy = normalizeProxyUrl(proxyUrl)
61
+ if (!proxy) return fetch(url, options)
62
+
63
+ const dispatcher = resolveDispatcher(proxy)
64
+ if (!dispatcher) {
65
+ if (!warned.has(proxy) && typeof onWarn === 'function') {
66
+ warned.add(proxy)
67
+ onWarn(`已配置代理 ${proxy},但无法启用(缺少 undici 依赖),该代理将被忽略,本次直连。`)
68
+ }
69
+ return fetch(url, options)
70
+ }
71
+ return fetch(url, { ...options, dispatcher })
72
+ }
73
+ }
74
+
75
+ function clearDispatcherCache() {
76
+ dispatcherCache.clear()
77
+ }
78
+
79
+ module.exports = {
80
+ normalizeProxyUrl,
81
+ resolveDispatcher,
82
+ proxySupportAvailable,
83
+ createOutboundFetch,
84
+ clearDispatcherCache,
85
+ }
package/lib/workflows.js CHANGED
@@ -318,6 +318,11 @@ function customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVa
318
318
  }
319
319
 
320
320
  const override = Boolean(cfg.customWorkflowOverrideParameters)
321
+ // modelParams 里显式配置的字段永远覆盖工作流内取值(用户明确为这个模型指定的值),
322
+ // 其余字段才受 customWorkflowOverrideParameters 这个总开关控制。
323
+ const modelParams = (opts && opts.modelParams && typeof opts.modelParams === 'object') ? opts.modelParams : {}
324
+ const explicitlySet = (key) => Object.prototype.hasOwnProperty.call(modelParams, key)
325
+ const overwrite = (key) => override || explicitlySet(key)
321
326
  const resolutionSet = new Set(targets.resolutionIds)
322
327
  const stepsSet = new Set(targets.stepsIds)
323
328
  const seedSet = new Set(targets.seedIds)
@@ -330,16 +335,17 @@ function customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVa
330
335
  if (classType === 'SaveImage' && 'filename_prefix' in inputs) {
331
336
  inputs.filename_prefix = 'pdraw/anm'
332
337
  }
333
- // 尺寸:配置了 customWorkflowOverrideParameters,或用户显式指定了尺寸时覆盖
334
- if ((override || explicitSize) && resolutionSet.has(nodeId)) {
338
+ // 尺寸:总开关开、用户显式指定尺寸、或 modelParams 配了 width/height 时覆盖
339
+ const sizeOverride = override || explicitSize || overwrite('width') || overwrite('height')
340
+ if (sizeOverride && resolutionSet.has(nodeId)) {
335
341
  if ('width' in inputs) inputs.width = width
336
342
  if ('height' in inputs) inputs.height = height
337
343
  }
338
- if (override && stepsSet.has(nodeId)) {
339
- if ('steps' in inputs) inputs.steps = steps
340
- if ('cfg' in inputs) inputs.cfg = cfgVal
341
- if (cfg.samplerName && 'sampler_name' in inputs) inputs.sampler_name = cfg.samplerName
342
- if (cfg.scheduler && 'scheduler' in inputs) inputs.scheduler = cfg.scheduler
344
+ if (stepsSet.has(nodeId)) {
345
+ if ('steps' in inputs && overwrite('steps')) inputs.steps = steps
346
+ if ('cfg' in inputs && overwrite('cfg')) inputs.cfg = cfgVal
347
+ if (cfg.samplerName && 'sampler_name' in inputs && overwrite('samplerName')) inputs.sampler_name = cfg.samplerName
348
+ if (cfg.scheduler && 'scheduler' in inputs && overwrite('scheduler')) inputs.scheduler = cfg.scheduler
343
349
  }
344
350
  if (seedSet.has(nodeId)) {
345
351
  if ('seed' in inputs) inputs.seed = seed
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-p-draw",
3
3
  "description": "p点-绘图,连接本地 ComfyUI 生图。支持自然语言优化、尺寸选择、画师组、固定角色、生成队列,需要配合 p-qiandao 使用",
4
- "version": "1.6.2",
4
+ "version": "1.6.3",
5
5
  "main": "index.js",
6
6
  "files": [
7
7
  "index.js",
package/readme.md CHANGED
@@ -8,7 +8,9 @@ p点-绘图插件,连接本地 ComfyUI 生图,参考 AstrBot 的 [anima 绘
8
8
  - `p-draw 多人 <描述>` 多人生图(2-4 人画面):LLM 结构化规划人物分组、互动关系与统一场景,未指定尺寸时按人数/肢体接触自动选横图,生成后可选视觉校验。
9
9
  - 批量张数:描述后加 `x3` / `×3` / `3张` / `三张` / `--数量 3` 可一次生成多张(上限 `batchMax`,默认 4),按张数 × 单价扣 P 点。
10
10
  - 自然语言自动优化为 Danbooru tags(可选,需配置 LLM 接口)。
11
+ - **多模型 / 中转站回退**:同一组 url+key 下可填多个模型名逐个尝试,全挂了再切下一个 url+key;兼容非 DeepSeek 站点(不硬发 `thinking`),可用 `llmExtraBody` 追加站点私有参数。
11
12
  - 联网搜索:描述中带 `联网`/`搜索`/`查一下` 等词时自动补充角色设定(需 Tavily Key)。
13
+ - **可选代理(分用途单独配置)**:`tavilyProxy` / `llmProxy` / `verifyLlmProxy` 三个独立开关,分别作用于联网搜索、LLM、视觉校验,留空即直连;LLM 通道还能各自指定专用代理。
12
14
  - 原样 tags 模式(`无优化` 前缀)。
13
15
  - 尺寸选择:`竖图` `横图` `方图` `长竖图` `宽屏`,或 `1024x1536:描述` / `--尺寸 1216x832`。
14
16
  - 采样参数临时覆盖(可选):`画图 少女 --cfg 3.5 --steps 40`(也可写 `--强度 3.5` / `--步数 40`)。优先级:命令级 > `modelParams` > 全局配置;参数会从提示词里剥离,不会混进 tags。
@@ -86,7 +88,7 @@ plugins:
86
88
 
87
89
  | 项 | 说明 |
88
90
  |----|------|
89
- | `qualityPrefix` / `negativePrompt` | 质量词前缀与负面词。默认 `qualityPrefix` 为空(Aesthetic 1.1 不需要质量标签),`negativePrompt` 为 Aesthetic 推荐值;从 Base 模型迁移时再把前缀填回 `masterpiece, best quality, score_7` |
91
+ | `qualityPrefix` / `negativePrompt` | 质量词前缀与负面词。默认 `qualityPrefix` 为空(Aesthetic 1.1 不需要质量标签),`negativePrompt` 为 Aesthetic 推荐值;从 Base 模型迁移时再把前缀填回 `masterpiece, best quality, score_7`。**负面词推荐值**:`worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts`(即默认值;Base 模型可再加 `score_4, score_5, score_6`) |
90
92
  | `styleTags` / `defaultArtistTags` | 画风 tags、备用画师 tags |
91
93
  | `activeArtistPreset` / `artistPresets` | 启用的画师组名称与画师组列表 |
92
94
  | `fixedCharacters` | 固定角色(仅兼容旧配置,运行时以数据库为准) |
@@ -121,7 +123,7 @@ plugins:
121
123
  |----|------|
122
124
  | `customWorkflowEnabled` / `customWorkflowPath` | 启用自定义工作流 JSON;路径相对 Koishi 运行目录解析 |
123
125
  | `skipQualityPrefixForCustomWorkflow` | 启用自定义工作流时跳过质量前缀注入(默认 `true`) |
124
- | `customWorkflowOverrideParameters` | 用插件参数覆盖工作流内的采样参数 |
126
+ | `customWorkflowOverrideParameters` | 用插件参数覆盖工作流内的采样参数(总开关)。注意:`modelParams` 里显式写了的字段不受这个开关限制,永远覆盖 |
125
127
  | `customWorkflowReloadOnChange` | 工作流文件变化时自动重载,无需重启(默认 `true`) |
126
128
  | `positivePromptNodeId` / `negativePromptNodeId` | 正/负面提示词节点 ID;留空自动识别 |
127
129
  | `resolutionNodeId` / `seedNodeId` / `stepsNodeId` | 尺寸 / 种子 / 步数节点 ID;可留空(留空则按节点类型覆盖) |
@@ -130,13 +132,20 @@ plugins:
130
132
 
131
133
  | 项 | 说明 |
132
134
  |----|------|
133
- | `modelParams` | 字典:`key`=模型文件名,`value` 只填要覆盖的 `samplerName` / `scheduler` / `steps` / `cfg` / `width` / `height`。匹配不区分大小写与 `-` `_`。优先级:命令级 `--steps`/`--cfg` > 本节 > 全局配置 |
135
+ | `modelParams` | 字典:`key`=模型文件名,`value` 只填要覆盖的 `samplerName` / `scheduler` / `steps` / `cfg` / `width` / `height`。匹配不区分大小写与 `-` `_`。**只要在 `modelParams` 里写了某个字段,它就会覆盖工作流内的值——包括自定义工作流**(不受 `customWorkflowOverrideParameters` 开关限制)。优先级:命令级 `--steps`/`--cfg` > 本节 > 全局配置 |
134
136
 
135
137
  ### ⑨ 提示词优化 / LLM(折叠)
136
138
 
137
139
  | 项 | 说明 |
138
140
  |----|------|
139
- | `promptOptimizeEnabled` / `llmBaseUrl` / `llmApiKey` / `llmModel` | 自然语言优化(OpenAI 兼容接口) |
141
+ | `promptOptimizeEnabled` | 启用自然语言优化 |
142
+ | `llmBaseUrl` / `llmApiKey` | 主通道接口地址与 Key(OpenAI 兼容) |
143
+ | `llmProxy` | **仅 LLM** 使用代理,留空直连(详见「中转站、多模型与代理」) |
144
+ | `llmModels` | 主通道的**模型名列表**,按顺序逐个尝试(如 `["deepseek-chat","gpt-4o-mini"]`)。旧的 `llmModel` 单模型仍兼容 |
145
+ | `llmChannels` | 附加通道(中转站/备用站):`通道名 → { baseUrl, apiKey, models }`。主通道所有模型都失败后按顺序继续试 |
146
+ | `llmChannelOrder` | 附加通道的尝试顺序(填通道名;留空则按配置先后顺序) |
147
+ | `llmThinking` | 是否发送 DeepSeek 专有的 `thinking` 字段。`auto`(默认,仅 DeepSeek 域名发送)/ `always` / `never`。**非 DeepSeek 模型带上它常被直接拒绝,中转站建议保持 auto 或改 never** |
148
+ | `llmExtraBody` | 附加请求体 JSON,最后覆盖。用于中转站私有参数,如 `{"enable_thinking":false}` |
140
149
  | `llmMaxTokens` | LLM 输出上限 |
141
150
  | `promptOptimizeTemplate` | 优化模板(支持 `{theme}` `{search_block}` `{character_rule}` 占位符) |
142
151
 
@@ -145,6 +154,7 @@ plugins:
145
154
  | 项 | 说明 |
146
155
  |----|------|
147
156
  | `webSearchEnabled` / `tavilyApiKey` | 联网搜索开关与 Tavily Key |
157
+ | `tavilyProxy` | **仅联网搜索**使用代理,留空直连 |
148
158
  | `webSearchMaxResults` / `webSearchDepth` / `webSearchQueryTemplate` | 结果数量、搜索深度、搜索词模板 |
149
159
 
150
160
  ### ⑪ 多人视觉校验(折叠)
@@ -153,7 +163,9 @@ plugins:
153
163
  |----|------|
154
164
  | `multiVerifyEnabled` / `multiVerifyPassScore` | 校验开关与合格分数(0-10) |
155
165
  | `multiCandidateCount` / `multiSendDegradedCandidate` | 候选采样数与全部不达标时是否仍发送最优候选 |
156
- | `verifyLlmBaseUrl` / `verifyLlmApiKey` / `verifyLlmModel` | 视觉模型(需支持图片输入;留空则跳过校验) |
166
+ | `verifyLlmBaseUrl` / `verifyLlmApiKey` / `verifyLlmModels` | 视觉模型(需支持图片输入,如 qwen-vl)。和文本侧一样支持多模型逐个尝试 |
167
+ | `verifyLlmProxy` | **仅视觉校验**使用代理,留空直连 |
168
+ | `verifyLlmChannels` / `verifyLlmChannelOrder` | 视觉侧的附加通道与尝试顺序(结构同 `llmChannels`) |
157
169
 
158
170
  ### ⑫ 兼容项(折叠)
159
171
 
@@ -175,6 +187,80 @@ p-draw:0z81el:
175
187
  # customWorkflowPath: data/p-draw/workflows/anima-aesthetic-v1.1.json
176
188
  ```
177
189
 
190
+ ## 中转站、多模型与代理
191
+
192
+ ### 多模型逐个回退
193
+
194
+ 同一个 `baseUrl` + `apiKey` 下可以填**多个模型名**,按顺序逐个尝试;前一个失败(网络错误 / 非 2xx / 返回空文本)自动换下一个:
195
+
196
+ ```yaml
197
+ llmBaseUrl: https://relay.example.com/v1
198
+ llmApiKey: sk-xxx
199
+ llmModels:
200
+ - deepseek-chat
201
+ - gpt-4o-mini
202
+ ```
203
+
204
+ 如果这一组模型全挂了,再切换到下一个「通道」(另一组 url + key):
205
+
206
+ ```yaml
207
+ llmChannels:
208
+ 备用站: # 通道名自取,只用于排序和日志
209
+ baseUrl: https://backup.example.com/v1
210
+ apiKey: sk-yyy
211
+ models:
212
+ - qwen-max
213
+ llmChannelOrder:
214
+ - 备用站
215
+ ```
216
+
217
+ 调用顺序:主通道的 `llmModels` 依次 → 全部失败 → `llmChannels` 里各通道的 `models` 依次。日志会记录每个候选的失败原因(`outputLogs` 开启时)。**视觉校验(`verifyLlm*`)规则完全相同**,只是配置项换成 `verifyLlmModels` / `verifyLlmChannels` / `verifyLlmChannelOrder`。
218
+
219
+ ### 中转站兼容
220
+
221
+ 请求体默认**只在 DeepSeek 域名下**附加 `thinking` 字段——很多中转站/其它模型不认识它,带上会被直接 400。特殊情况用 `llmThinking` 调:
222
+
223
+ | 取值 | 行为 |
224
+ |---|---|
225
+ | `auto`(默认) | 仅当 `baseUrl` 或模型名含 `deepseek` 时发送 |
226
+ | `always` | 总是发送(自建 DeepSeek 中转站用) |
227
+ | `never` | 从不发送(域名像 DeepSeek 但网关不认这个字段时用) |
228
+
229
+ 站点私有参数用 `llmExtraBody` 追加,**最后覆盖**,所以也能改 `max_tokens` 等:
230
+
231
+ ```yaml
232
+ llmExtraBody: '{"enable_thinking": false, "top_p": 0.9}'
233
+ ```
234
+
235
+ ### 代理(可选,按用途分开)
236
+
237
+ 三个代理**互相独立**,都留空就是直连:
238
+
239
+ | 配置项 | 作用范围 | 所在分组 |
240
+ |---|---|---|
241
+ | `tavilyProxy` | 只影响联网搜索(Tavily) | ⑩ 联网搜索 |
242
+ | `llmProxy` | 只影响提示词优化 / 多人规划的文本 LLM | ⑨ 提示词优化 / LLM |
243
+ | `verifyLlmProxy` | 只影响多人视觉校验的视觉模型 | ⑪ 多人视觉校验 |
244
+
245
+ ```yaml
246
+ tavilyProxy: http://127.0.0.1:7890 # 只给搜索走代理
247
+ llmProxy: '' # LLM 直连
248
+ verifyLlmProxy: socks5://127.0.0.1:7891 # 视觉模型走另一个
249
+ ```
250
+
251
+ `llmChannels` / `verifyLlmChannels` 里每个通道还可以填 `proxy` 指定**该通道专用**代理,优先级高于上面三个用途级配置:
252
+
253
+ ```yaml
254
+ llmChannels:
255
+ 海外中转:
256
+ baseUrl: https://overseas.example.com/v1
257
+ apiKey: sk-zzz
258
+ models: [gpt-4o-mini]
259
+ proxy: http://127.0.0.1:7890 # 只有这个通道走代理
260
+ ```
261
+
262
+ 格式都支持 `http://`、`socks5://`,也可省略协议直接写 `127.0.0.1:7890`。若宿主的 Koishi 里解析不到 `undici`,该代理会被忽略并告警一次,其余功能不受影响。
263
+
178
264
  ## 工作流对接:Anima Aesthetic 1.1
179
265
 
180
266
  ### 1. 模型文件放置