开发者报障:「为什么我们库存入库这块 我上传的图片是图二 但是 ai 却无法解析?」
**不是识别不出来,是输出被截断**(实测确证):
- 本地 API 日志:入库识别确实调了模型(promptChars 1830),返回 textLength 2248/2026;
- 同一提示词+同一张图、**默认参数**复现:4616 字符,`{"kind":"document","items":[…23 条…]}`,
spec 也抽全(500g/袋、25kg/袋、600g*12瓶…),解析 23 条 ⇒ 提示词与图片没问题;
- 定位:入库识别专用参数 `buildWeighStationLlmOptions` 里 **`maxOutputTokens: 800`**
—— 800 token ≈ 2000–2500 字符,与日志 2248/2026 吻合;
- **只改上限**对照:800 → 2273 字符、结尾停在 `…"unit":"袋","origin`(数组中间)
→ `JSON.parse` 失败 → **0 条**;默认 → 4616 字符 → **23 条**。根因确证。
修法(两层):
① `maxOutputTokens` **800 → 4000**(约容纳 50 行;token 按实际生成计费,提高上限不额外花钱);
② `parseItemsJson` 加**截断兜底**:解析失败时按大括号配对逐个抠出**已完整**的明细对象
(正确处理字符串内引号/转义),能捞多少算多少,并留一行服务端日志
`JSON 解析失败但捞出 N 行(疑似输出被截断)`。口径:**宁可给部分结果,不再整批归零**;
完全不是 JSON / 空返回 / 只有 kind 无 items ⇒ 仍老实返回 0 条(不臆造)。
未动提示词(不触 AI 发布/登记流程),未动识别口径、候选匹配与档案回写(1cd4b2c)。
证据:`server/tests/stockInboundParseItemsJson.test.ts` **5 通过**(完整/截断捞 3 行/含转义引号/
非 JSON 返回 0/围栏代码块);修后用**真实参数**对同一张真单据端到端复跑:
`maxOutputTokens=4000` → 4617 字符 → **23 条**,首行 `燕子酵母粉 / 500g/袋 / 5 / 袋`;
`cd server && npx tsc --noEmit` 本次面零错误(仅剩既有 defaults.ts variablesSchema 缺失);
设计门禁 8 通过/1 红(check-ai-cost)/1 未执行 与基线一致。设计文档 + README 已登记。
442 lines
15 KiB
TypeScript
442 lines
15 KiB
TypeScript
import { isArkConfigured, loadEnv } from '../env';
|
||
import {
|
||
callArkWithAudio,
|
||
callArkWithFile,
|
||
callArkWithImage,
|
||
callArkWithImages,
|
||
callArkWithText,
|
||
invalidateBranchArkConfigCache,
|
||
resolveArkRuntimeConfig,
|
||
assertArkHttpOk,
|
||
} from './arkService';
|
||
import {
|
||
resolveUsableBranchLlmConfig,
|
||
resolveUsablePlatformLlmConfig,
|
||
} from './branchLlmConfigService';
|
||
import { type LlmCallOptions, type LlmRuntimeConfig, LlmServiceError } from './llmTypes';
|
||
import {
|
||
getLlmProviderPreset,
|
||
normalizeLlmProvider,
|
||
providerSupportsImageGeneration,
|
||
stripOpenAiCompatEndpointPath,
|
||
} from './providers/llmProviderPresets';
|
||
import {
|
||
openaiCompatCallWithAudio,
|
||
openaiCompatCallWithFile,
|
||
openaiCompatCallWithImage,
|
||
openaiCompatCallWithImages,
|
||
openaiCompatCallWithText,
|
||
openaiCompatGenerateImage,
|
||
} from './providers/openaiCompatibleLlmAdapter';
|
||
|
||
export type { LlmCallOptions, LlmRuntimeConfig };
|
||
export {
|
||
LlmServiceError,
|
||
isLlmServiceError,
|
||
assertLlmHttpOk,
|
||
ArkServiceError,
|
||
isArkServiceError,
|
||
ARK_ACCOUNT_OVERDUE_MESSAGE,
|
||
} from './llmTypes';
|
||
export { assertArkHttpOk, invalidateBranchArkConfigCache };
|
||
|
||
const DEFAULT_ARK = getLlmProviderPreset('ark');
|
||
|
||
const branchLlmCache = new Map<string, { expiresAt: number; config: LlmRuntimeConfig | null }>();
|
||
let platformLlmCache: { expiresAt: number; config: LlmRuntimeConfig | null } | null = null;
|
||
|
||
export function invalidateBranchLlmConfigCache(branchCode?: string | null) {
|
||
invalidateBranchArkConfigCache(branchCode);
|
||
const code = String(branchCode || '').trim();
|
||
if (!code) {
|
||
branchLlmCache.clear();
|
||
platformLlmCache = null;
|
||
return;
|
||
}
|
||
branchLlmCache.delete(code);
|
||
}
|
||
|
||
export function selectLlmRuntimeLayers(input: {
|
||
branch: LlmRuntimeConfig | null;
|
||
platform: LlmRuntimeConfig | null;
|
||
envOpenAi: LlmRuntimeConfig | null;
|
||
envArk: LlmRuntimeConfig;
|
||
}): LlmRuntimeConfig {
|
||
return input.branch || input.platform || input.envOpenAi || input.envArk;
|
||
}
|
||
|
||
async function resolveCachedPlatformLlm(): Promise<LlmRuntimeConfig | null> {
|
||
if (platformLlmCache && platformLlmCache.expiresAt > Date.now()) {
|
||
return platformLlmCache.config;
|
||
}
|
||
try {
|
||
const config = await resolveUsablePlatformLlmConfig();
|
||
platformLlmCache = { expiresAt: Date.now() + 60_000, config };
|
||
return config;
|
||
} catch (error) {
|
||
console.warn('Load platform LLM config failed:', error);
|
||
platformLlmCache = { expiresAt: Date.now() + 15_000, config: null };
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function envArkRuntime(): LlmRuntimeConfig {
|
||
loadEnv();
|
||
const multi = process.env.ARK_API_KEYS?.split(',').map((k) => k.trim()).filter(Boolean) || [];
|
||
const single = process.env.ARK_API_KEY?.trim();
|
||
const apiKeys = multi.length ? multi : single ? [single] : [];
|
||
return {
|
||
provider: 'ark',
|
||
baseUrl: DEFAULT_ARK.baseUrl,
|
||
apiKeys,
|
||
model: process.env.ARK_MODEL || DEFAULT_ARK.model,
|
||
imageModel: process.env.ARK_IMAGE_MODEL || DEFAULT_ARK.imageModel,
|
||
visionModel: process.env.ARK_VISION_MODEL || '',
|
||
imageSize: process.env.ARK_IMAGE_SIZE || DEFAULT_ARK.imageSize,
|
||
supportsImageGeneration: true,
|
||
};
|
||
}
|
||
|
||
/** .env OpenAI 兼容兜底(腾讯 TokenHub 等)。无 Key 或无 Base URL 则不用。 */
|
||
export function envOpenAiCompatRuntime(): LlmRuntimeConfig | null {
|
||
loadEnv();
|
||
const apiKey = String(process.env.LLM_API_KEY || '').trim();
|
||
const baseUrl = stripOpenAiCompatEndpointPath(process.env.LLM_BASE_URL || '');
|
||
if (!apiKey || !baseUrl) return null;
|
||
const rawProvider = String(process.env.LLM_PROVIDER || 'openai').trim();
|
||
const provider = normalizeLlmProvider(rawProvider === 'ark' ? 'openai' : rawProvider);
|
||
const preset = getLlmProviderPreset(provider);
|
||
const imageModel = String(process.env.LLM_IMAGE_MODEL || '').trim();
|
||
return {
|
||
provider,
|
||
baseUrl,
|
||
apiKeys: [apiKey],
|
||
model: String(process.env.LLM_MODEL || '').trim() || preset.model,
|
||
imageModel,
|
||
visionModel: String(process.env.LLM_VISION_MODEL || '').trim(),
|
||
imageSize: String(process.env.LLM_IMAGE_SIZE || '').trim() || preset.imageSize,
|
||
supportsImageGeneration: Boolean(imageModel) && providerSupportsImageGeneration(provider),
|
||
};
|
||
}
|
||
|
||
function envFallbackRuntime(): LlmRuntimeConfig {
|
||
const ark = envArkRuntime();
|
||
if (ark.apiKeys.length) return ark;
|
||
return envOpenAiCompatRuntime() || ark;
|
||
}
|
||
|
||
/** 超管页展示用:.env 通用兜底为豆包;TokenHub 仅称重台。不含明文 Key */
|
||
export function getEnvLlmFallbackPublic(): {
|
||
provider: LlmRuntimeConfig['provider'];
|
||
model: string;
|
||
visionModel: string;
|
||
imageModel: string;
|
||
imageSize: string;
|
||
baseUrl: string;
|
||
hasApiKeys: boolean;
|
||
apiKeysHint: string;
|
||
} {
|
||
const runtime = envFallbackRuntime();
|
||
const first = runtime.apiKeys[0] || '';
|
||
const tail = first ? first.slice(-4) : '';
|
||
return {
|
||
provider: runtime.provider,
|
||
model: runtime.model,
|
||
visionModel: runtime.visionModel || '',
|
||
imageModel: runtime.imageModel,
|
||
imageSize: runtime.imageSize || DEFAULT_ARK.imageSize,
|
||
baseUrl: runtime.baseUrl,
|
||
hasApiKeys: runtime.apiKeys.length > 0,
|
||
apiKeysHint: first
|
||
? runtime.apiKeys.length > 1
|
||
? `••••${tail} 等${runtime.apiKeys.length}个`
|
||
: `••••${tail}`
|
||
: '',
|
||
};
|
||
}
|
||
|
||
export async function resolveLlmRuntimeConfig(options?: LlmCallOptions): Promise<LlmRuntimeConfig> {
|
||
const modelOverride = String(options?.model || '').trim();
|
||
const apply = (cfg: LlmRuntimeConfig) => (modelOverride ? { ...cfg, model: modelOverride } : cfg);
|
||
const override = options?.runtimeOverride;
|
||
if (override && override.apiKeys.length) {
|
||
return apply(override);
|
||
}
|
||
|
||
let branch: LlmRuntimeConfig | null = null;
|
||
const code = String(options?.branchCode || '').trim();
|
||
if (code) {
|
||
const cached = branchLlmCache.get(code);
|
||
if (cached && cached.expiresAt > Date.now()) {
|
||
branch = cached.config;
|
||
} else {
|
||
try {
|
||
const config = await resolveUsableBranchLlmConfig(code);
|
||
branchLlmCache.set(code, { expiresAt: Date.now() + 60_000, config });
|
||
branch = config;
|
||
} catch (error) {
|
||
console.warn('Load branch LLM config failed:', error);
|
||
branchLlmCache.set(code, { expiresAt: Date.now() + 15_000, config: null });
|
||
branch = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
const platform = await resolveCachedPlatformLlm();
|
||
return apply(
|
||
selectLlmRuntimeLayers({
|
||
branch,
|
||
platform,
|
||
// TokenHub 只给称重台 runtimeOverride,通用能力走豆包。
|
||
envOpenAi: null,
|
||
envArk: envArkRuntime(),
|
||
})
|
||
);
|
||
}
|
||
|
||
/** 称重台识图模型:豆包 ARK;忽略历史 glm / TokenHub 残留配置 */
|
||
export function resolveWeighVisionModel(): string {
|
||
loadEnv();
|
||
const weigh = String(process.env.ARK_WEIGH_VISION_MODEL || process.env.WEIGH_VISION_MODEL || '').trim();
|
||
if (weigh && !/^glm/i.test(weigh)) return weigh;
|
||
const arkVision = String(process.env.ARK_VISION_MODEL || '').trim();
|
||
if (arkVision) return arkVision;
|
||
return String(process.env.ARK_MODEL || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 称重台:强制豆包 ARK(runtimeOverride),忽略分公司/平台 LLM 配置。
|
||
* 避免被 branch 上的 deepseek / TokenHub vision 盖掉。
|
||
*/
|
||
export function buildWeighStationLlmOptions(branchCode?: string | null): LlmCallOptions {
|
||
const model = resolveWeighVisionModel() || undefined;
|
||
const ark = envArkRuntime();
|
||
return {
|
||
branchCode: branchCode || undefined,
|
||
model,
|
||
/**
|
||
* 输出上限(2026-10-16 真机修复):
|
||
* 原值 **800** 只够约 2000–2500 字符,而整张单据(20+ 行)的 JSON 约 4600 字符
|
||
* ⇒ 模型输出在数组中间被切断 ⇒ 整段 `JSON.parse` 失败 ⇒ 明明识别出商品却显示 **0 条**
|
||
* (开发者报障「上传图片 ai 却无法解析」;实测 800 时返回 2273 字、结尾停在 `"origin`)。
|
||
* 4000 可容纳约 50 行;token 按**实际生成**计费,提高上限本身不额外花钱。
|
||
*/
|
||
maxOutputTokens: 4000,
|
||
disableThinking: true,
|
||
runtimeOverride: ark.apiKeys.length
|
||
? {
|
||
...ark,
|
||
model: model || ark.model,
|
||
// 清空 visionModel,避免 callWithImage 再套 LLM_VISION_MODEL / 分公司 vision
|
||
visionModel: '',
|
||
}
|
||
: undefined,
|
||
};
|
||
}
|
||
|
||
export async function hasRuntimeConfig(options?: LlmCallOptions): Promise<boolean> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
return runtime.apiKeys.length > 0;
|
||
}
|
||
|
||
/** 录单识图:未单独配置视觉模型时与文本/语音同一模型(当前为 seed-2.0) */
|
||
export const DEFAULT_ORDER_PARSE_VISION_MODEL = '';
|
||
|
||
function isVisionModelDisabled(value: string): boolean {
|
||
const t = value.trim().toLowerCase();
|
||
return t === 'off' || t === '-' || t === 'none';
|
||
}
|
||
|
||
/** 识图模型:只用分公司 visionModel;空或 off 则与对话模型相同 */
|
||
export function resolveOrderParseVisionModel(runtimeVisionModel?: string | null): string {
|
||
const fromBranch = String(runtimeVisionModel || '').trim();
|
||
if (fromBranch) {
|
||
return isVisionModelDisabled(fromBranch) ? '' : fromBranch;
|
||
}
|
||
return DEFAULT_ORDER_PARSE_VISION_MODEL;
|
||
}
|
||
|
||
export async function withOrderParseVisionModel(options?: LlmCallOptions): Promise<LlmCallOptions> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
const visionModel = resolveOrderParseVisionModel(runtime.visionModel);
|
||
if (!visionModel) return { ...(options || {}) };
|
||
return { ...(options || {}), model: visionModel };
|
||
}
|
||
|
||
export async function callWithText(
|
||
systemPrompt: string,
|
||
userText: string,
|
||
options?: LlmCallOptions
|
||
): Promise<string | null> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) return null;
|
||
if (runtime.provider === 'ark') {
|
||
return callArkWithText(systemPrompt, userText, options);
|
||
}
|
||
return openaiCompatCallWithText(runtime, systemPrompt, userText);
|
||
}
|
||
|
||
export async function callWithImage(
|
||
systemPrompt: string,
|
||
imageBase64: string,
|
||
options?: LlmCallOptions
|
||
): Promise<string | null> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) return null;
|
||
const visionModel = resolveOrderParseVisionModel(runtime.visionModel);
|
||
const imageRuntime = visionModel ? { ...runtime, model: visionModel } : runtime;
|
||
console.info('LLM image call:', {
|
||
provider: imageRuntime.provider,
|
||
model: imageRuntime.model,
|
||
visionOverride: visionModel || null,
|
||
promptChars: systemPrompt.length,
|
||
});
|
||
if (imageRuntime.provider === 'ark') {
|
||
return callArkWithImage(systemPrompt, imageBase64, visionModel ? { ...options, model: visionModel } : options);
|
||
}
|
||
return openaiCompatCallWithImage(imageRuntime, systemPrompt, imageBase64, options?.maxOutputTokens);
|
||
}
|
||
|
||
/** 多图一次调用(同一批入库的多张照片):让模型自己合并同一商品;单图退化为 callWithImage */
|
||
export async function callWithImages(
|
||
systemPrompt: string,
|
||
imagesBase64: string[],
|
||
options?: LlmCallOptions
|
||
): Promise<string | null> {
|
||
const images = (imagesBase64 || []).map((b) => String(b || '').trim()).filter(Boolean);
|
||
if (!images.length) return null;
|
||
if (images.length === 1) return callWithImage(systemPrompt, images[0], options);
|
||
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) return null;
|
||
const visionModel = resolveOrderParseVisionModel(runtime.visionModel);
|
||
const imageRuntime = visionModel ? { ...runtime, model: visionModel } : runtime;
|
||
console.info('LLM images call:', {
|
||
provider: imageRuntime.provider,
|
||
model: imageRuntime.model,
|
||
visionOverride: visionModel || null,
|
||
imageCount: images.length,
|
||
promptChars: systemPrompt.length,
|
||
});
|
||
if (imageRuntime.provider === 'ark') {
|
||
return callArkWithImages(systemPrompt, images, visionModel ? { ...options, model: visionModel } : options);
|
||
}
|
||
return openaiCompatCallWithImages(imageRuntime, systemPrompt, images, options?.maxOutputTokens);
|
||
}
|
||
|
||
export async function callWithFile(
|
||
systemPrompt: string,
|
||
fileBase64: string,
|
||
options?: LlmCallOptions & { filename?: string; mime?: string }
|
||
): Promise<string | null> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) return null;
|
||
if (runtime.provider === 'ark') {
|
||
return callArkWithFile(systemPrompt, fileBase64, options);
|
||
}
|
||
return openaiCompatCallWithFile(runtime, systemPrompt, fileBase64, options?.filename);
|
||
}
|
||
|
||
export async function callWithAudio(
|
||
systemPrompt: string,
|
||
audioBase64: string,
|
||
audioFormat = 'webm',
|
||
options?: LlmCallOptions
|
||
): Promise<string | null> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) return null;
|
||
if (runtime.provider === 'ark') {
|
||
return callArkWithAudio(systemPrompt, audioBase64, audioFormat, options);
|
||
}
|
||
return openaiCompatCallWithAudio(runtime, systemPrompt, audioBase64, audioFormat);
|
||
}
|
||
|
||
const MAX_GENERATED_IMAGE_BYTES = 4 * 1024 * 1024;
|
||
|
||
async function generateArkImage(
|
||
prompt: string,
|
||
size: string | undefined,
|
||
options?: LlmCallOptions
|
||
): Promise<Buffer | null> {
|
||
const runtime = await resolveArkRuntimeConfig(options);
|
||
const apiKey = runtime.apiKeys[0];
|
||
if (!apiKey) return null;
|
||
|
||
const response = await fetch(`${runtime.baseUrl}/images/generations`, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
Authorization: `Bearer ${apiKey}`,
|
||
},
|
||
body: JSON.stringify({
|
||
model: runtime.imageModel,
|
||
prompt,
|
||
size: size || runtime.imageSize || '1024x1024',
|
||
response_format: 'b64_json',
|
||
watermark: false,
|
||
sequential_image_generation: 'disabled',
|
||
}),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errText = await response.text();
|
||
assertArkHttpOk(response.status, errText);
|
||
console.error('ARK image generation failed:', response.status, errText.slice(0, 300));
|
||
return null;
|
||
}
|
||
|
||
const payload = (await response.json()) as {
|
||
data?: Array<{ b64_json?: string; url?: string }>;
|
||
error?: { message?: string };
|
||
};
|
||
|
||
const b64 = payload.data?.[0]?.b64_json;
|
||
if (b64) {
|
||
const buffer = Buffer.from(b64, 'base64');
|
||
if (buffer.byteLength > MAX_GENERATED_IMAGE_BYTES) return null;
|
||
return buffer;
|
||
}
|
||
|
||
const remoteUrl = payload.data?.[0]?.url;
|
||
if (remoteUrl) {
|
||
const imageRes = await fetch(remoteUrl);
|
||
if (imageRes.ok) {
|
||
const buffer = Buffer.from(await imageRes.arrayBuffer());
|
||
if (buffer.byteLength > MAX_GENERATED_IMAGE_BYTES) return null;
|
||
return buffer;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export async function generateImage(
|
||
prompt: string,
|
||
options?: LlmCallOptions & { size?: string }
|
||
): Promise<Buffer | null> {
|
||
const runtime = await resolveLlmRuntimeConfig(options);
|
||
if (!runtime.apiKeys.length) {
|
||
throw new LlmServiceError('LLM_NOT_CONFIGURED', '未配置可用的大模型 API Key');
|
||
}
|
||
if (!providerSupportsImageGeneration(runtime.provider)) {
|
||
throw new LlmServiceError(
|
||
'LLM_IMAGE_UNSUPPORTED',
|
||
`${runtime.provider} 不支持商品 AI 生图,请改用火山方舟、OpenAI 或通义千问,或关闭 AI 生图。`
|
||
);
|
||
}
|
||
if (runtime.provider === 'ark') {
|
||
return generateArkImage(prompt, options?.size, options);
|
||
}
|
||
return openaiCompatGenerateImage(runtime, prompt, options?.size);
|
||
}
|
||
|
||
export function hasArkApiKey() {
|
||
return isArkConfigured();
|
||
}
|
||
|
||
/** 供余额 UI:当前有效配置是否为方舟 */
|
||
export async function isEffectiveProviderArk(branchCode?: string | null): Promise<boolean> {
|
||
const runtime = await resolveLlmRuntimeConfig({ branchCode });
|
||
return runtime.provider === 'ark' && runtime.apiKeys.length > 0;
|
||
}
|
||
|