Files
SupplierSystem/server/src/services/arkService.ts
T
雨天 7db8cd6ceb feat(库存入库): 多图一次识别与分类/单位/保质期兜底
识别接口支持 images_base64 多图一次调用(模型自行合并同一实物,为空逐图回退,旧单图字段仍兼容);提示词要求单位按形态给、保质期保留原文单位、分类从已有分类选(漏给时文本分类兜底);有效期按生产日期+保质期推算(1 月=30 天);仅识别路由放宽 body 到 20MB,并新增存放区域列表接口。
2026-10-10 18:05:38 +08:00

707 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { isArkConfigured, loadEnv } from '../env';
import { resolveUsableBranchArkConfig, resolveUsablePlatformLlmConfig } from './branchLlmConfigService';
import {
ArkServiceError,
ARK_ACCOUNT_OVERDUE_MESSAGE,
assertArkHttpOk,
isArkServiceError,
type LlmCallOptions,
} from './llmTypes';
export {
ArkServiceError,
ARK_ACCOUNT_OVERDUE_MESSAGE,
assertArkHttpOk,
isArkServiceError,
};
const DEFAULT_ARK_BASE_URL = 'https://ark.cn-beijing.volces.com/api/v3';
const DEFAULT_MODEL = 'doubao-seed-2-0-lite-260428';
const DEFAULT_IMAGE_MODEL = 'doubao-seedream-4-0-250828';
interface ArkContentPart {
type?: string;
text?: string;
output_text?: string;
image_url?: string;
input_audio?: {
data?: string;
format?: string;
};
audio_url?: string;
}
interface ArkOutputItem {
type?: string;
text?: string;
content?: ArkContentPart[];
}
interface ArkResponsePayload {
id?: string;
status?: string;
output?: ArkOutputItem[];
error?: { message?: string };
}
let apiKeyIndex = 0;
const branchConfigCache = new Map<string, { expiresAt: number; config: ArkRuntimeConfig | null }>();
let platformArkCache: { expiresAt: number; config: ArkRuntimeConfig | null } | null = null;
export type ArkCallOptions = LlmCallOptions;
export interface ArkRuntimeConfig {
baseUrl: string;
apiKeys: string[];
model: string;
imageModel: string;
imageSize?: string;
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function getArkApiKeys(): string[] {
loadEnv();
const multi = process.env.ARK_API_KEYS?.split(',').map((key) => key.trim()).filter(Boolean) || [];
if (multi.length) return multi;
const single = process.env.ARK_API_KEY?.trim();
return single ? [single] : [];
}
export function invalidateBranchArkConfigCache(branchCode?: string | null) {
const code = String(branchCode || '').trim();
if (!code) {
branchConfigCache.clear();
platformArkCache = null;
return;
}
branchConfigCache.delete(code);
}
async function getBranchArkConfig(branchCode?: string | null): Promise<ArkRuntimeConfig | null> {
const code = String(branchCode || '').trim();
if (!code) return null;
const cached = branchConfigCache.get(code);
if (cached && cached.expiresAt > Date.now()) return cached.config;
try {
// 显式按 branchCode 进 tenant,不依赖请求 ALS 是否指向同一分公司
const config = await resolveUsableBranchArkConfig(code);
branchConfigCache.set(code, { expiresAt: Date.now() + 60_000, config });
return config;
} catch (error) {
console.warn('Load branch LLM config failed:', error);
branchConfigCache.set(code, { expiresAt: Date.now() + 15_000, config: null });
return null;
}
}
async function getPlatformArkConfig(): Promise<ArkRuntimeConfig | null> {
if (platformArkCache && platformArkCache.expiresAt > Date.now()) {
return platformArkCache.config;
}
try {
const full = await resolveUsablePlatformLlmConfig();
const config =
full && full.provider === 'ark'
? {
baseUrl: full.baseUrl,
apiKeys: full.apiKeys,
model: full.model,
imageModel: full.imageModel,
imageSize: full.imageSize,
}
: null;
platformArkCache = { expiresAt: Date.now() + 60_000, config };
return config;
} catch (error) {
console.warn('Load platform Ark config failed:', error);
platformArkCache = { expiresAt: Date.now() + 15_000, config: null };
return null;
}
}
export async function resolveArkRuntimeConfig(options?: ArkCallOptions): Promise<ArkRuntimeConfig> {
const modelOverride = String(options?.model || '').trim();
const override = options?.runtimeOverride;
if (override && override.provider === 'ark' && override.apiKeys.length) {
return {
baseUrl: override.baseUrl,
apiKeys: override.apiKeys,
model: modelOverride || override.model,
imageModel: override.imageModel,
imageSize: override.imageSize,
};
}
const branchConfig = await getBranchArkConfig(options?.branchCode);
if (branchConfig) {
return modelOverride ? { ...branchConfig, model: modelOverride } : branchConfig;
}
const platformConfig = await getPlatformArkConfig();
if (platformConfig) {
return modelOverride ? { ...platformConfig, model: modelOverride } : platformConfig;
}
return {
baseUrl: DEFAULT_ARK_BASE_URL,
apiKeys: getArkApiKeys(),
model: modelOverride || getArkModel(),
imageModel: process.env.ARK_IMAGE_MODEL || DEFAULT_IMAGE_MODEL,
imageSize: process.env.ARK_IMAGE_SIZE,
};
}
function getNextApiKey(keys = getArkApiKeys()): string | null {
if (!keys.length) return null;
const key = keys[apiKeyIndex % keys.length];
apiKeyIndex += 1;
return key;
}
function getArkModel() {
return process.env.ARK_MODEL || DEFAULT_MODEL;
}
function extractResponseText(response: ArkResponsePayload): string {
const chunks: string[] = [];
for (const item of response.output || []) {
if (item.text?.trim()) chunks.push(item.text.trim());
for (const part of item.content || []) {
const piece = String(part.text || part.output_text || '').trim();
if (piece) chunks.push(piece);
}
}
if (chunks.length) return chunks.join('\n');
const legacy = response as unknown as {
choices?: Array<{ message?: { content?: string } }>;
output_text?: string;
};
if (legacy.output_text) return legacy.output_text;
return legacy.choices?.[0]?.message?.content || '';
}
/** 上游 fetch 超时:防止 Ark 网关挂起导致请求线程/连接无限占用(P1 链路加固) */
function arkFetchTimeoutMs(): number {
return Number(process.env.ARK_FETCH_TIMEOUT_MS || 120_000);
}
async function requestArk(baseUrl: string, path: string, apiKey: string, init?: RequestInit) {
return fetch(`${baseUrl}${path}`, {
...init,
signal: AbortSignal.timeout(arkFetchTimeoutMs()),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
...(init?.headers || {}),
},
});
}
async function pollArkResponse(responseId: string, apiKey: string, runtime: ArkRuntimeConfig): Promise<ArkResponsePayload | null> {
const maxAttempts = Number(process.env.ARK_POLL_MAX_ATTEMPTS || 60);
const intervalMs = Number(process.env.ARK_POLL_INTERVAL_MS || 250);
const startedAt = Date.now();
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
const pollRes = await requestArk(runtime.baseUrl, `/responses/${responseId}`, apiKey, { method: 'GET' });
if (!pollRes.ok) {
const errText = await pollRes.text();
assertArkHttpOk(pollRes.status, errText);
console.error('ARK poll failed:', pollRes.status, errText.slice(0, 300));
return null;
}
const payload = (await pollRes.json()) as ArkResponsePayload;
const status = payload.status || 'completed';
if (status === 'completed') {
console.info('ARK poll completed:', {
responseId,
attempts: attempt + 1,
elapsedMs: Date.now() - startedAt,
});
return payload;
}
if (status === 'failed' || status === 'cancelled' || status === 'incomplete') {
console.error('ARK response failed:', payload.error?.message || status);
return null;
}
await sleep(intervalMs);
}
console.error('ARK poll timeout:', responseId);
return null;
}
async function createArkResponse(
body: Record<string, unknown>,
options?: ArkCallOptions,
apiKeyOverride?: string | null
): Promise<ArkResponsePayload | null> {
const runtime = await resolveArkRuntimeConfig(options);
const apiKey = apiKeyOverride || getNextApiKey(runtime.apiKeys);
if (!apiKey) return null;
const startedAt = Date.now();
const createRes = await requestArk(runtime.baseUrl, '/responses', apiKey, {
method: 'POST',
body: JSON.stringify({
model: runtime.model,
thinking: { type: 'disabled' },
// 长送货单 JSON 易被默认输出上限截断,截断后会触发重试/补漏,总耗时翻倍
max_output_tokens: options?.maxOutputTokens || Number(process.env.ARK_MAX_OUTPUT_TOKENS || 8192),
...body,
}),
});
if (!createRes.ok) {
const errText = await createRes.text();
assertArkHttpOk(createRes.status, errText);
console.error('ARK Responses API failed:', createRes.status, errText.slice(0, 300));
return null;
}
const created = (await createRes.json()) as ArkResponsePayload;
const status = created.status || 'completed';
if (status === 'completed') {
const text = extractResponseText(created);
console.info('ARK response completed:', {
model: runtime.model,
branchCode: options?.branchCode || null,
elapsedMs: Date.now() - startedAt,
textLength: text.length,
});
if (!text.trim()) {
console.warn('ARK response completed but text empty:', {
model: runtime.model,
outputTypes: (created.output || []).flatMap((item) =>
(item.content || []).map((part) => part.type || 'unknown')
),
});
}
return created;
}
if (!created.id) {
console.error('ARK create missing response id');
return null;
}
if (status === 'failed' || status === 'cancelled' || status === 'incomplete') {
console.error('ARK create failed:', created.error?.message || status);
return null;
}
console.info('ARK response pending poll:', {
responseId: created.id,
model: runtime.model,
branchCode: options?.branchCode || null,
createMs: Date.now() - startedAt,
});
return pollArkResponse(created.id, apiKey, runtime);
}
async function callArkChatCompletions(
messages: unknown[],
options?: ArkCallOptions,
apiKeyOverride?: string | null
): Promise<string | null> {
const runtime = await resolveArkRuntimeConfig(options);
const apiKey = apiKeyOverride || getNextApiKey(runtime.apiKeys);
if (!apiKey) return null;
const body: Record<string, unknown> = {
model: runtime.model,
messages,
temperature: 0.1,
max_tokens: options?.maxOutputTokens || Number(process.env.ARK_CHAT_MAX_TOKENS || 8192),
};
// 深度思考默认关闭。
// 豆包 Seed 2.0 默认开启深度思考(thinking),会让录单/识图等短任务多出
// 数秒到十几秒的思考开销;调用方几乎都是「短 JSON / 短识图」场景,统一默认关。
// - 历史做法:仅称重台显式传 disableThinking(设计 20260910-weigh-disable-thinking),
// 其余 ~20 处调用点漏传,导致长尾变慢;
// - 现改为默认关:未显式传参即关闭;确需思考的场景传 disableThinking: false;
// - ARK_ENABLE_THINKING=1 可全局临时恢复(应急用,例如怀疑关思考影响准确率)。
// 实测(doubao-seed-2-0-lite-260428,20 条商品文本解析):
// 思考默认 5574ms / 输出 667 字符 vs 关闭 5723ms / 输出 667 字符
// —— 该样本下开关对耗时与输出无差异,故本次改动不改变结果质量,仅按用户要求统一关闭。
const thinkingEnabled = options?.disableThinking === false || process.env.ARK_ENABLE_THINKING === '1';
if (!thinkingEnabled) {
body.thinking = { type: 'disabled' };
}
// 便于排查「为什么慢」:记录本次是否关闭思考(不含任何用户内容/密钥)
console.info('ARK chat thinking:', thinkingEnabled ? 'enabled' : 'disabled');
const response = await requestArk(runtime.baseUrl, '/chat/completions', apiKey, {
method: 'POST',
body: JSON.stringify(body),
});
if (!response.ok) {
const errText = await response.text();
assertArkHttpOk(response.status, errText);
console.error('ARK Chat API failed:', response.status, errText.slice(0, 300));
return null;
}
const result = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> };
return result.choices?.[0]?.message?.content || '';
}
export async function callArkWithText(systemPrompt: string, userText: string, options?: ArkCallOptions): Promise<string | null> {
const response = await createArkResponse({
input: [
{
role: 'user',
content: [{ type: 'input_text', text: `${systemPrompt}\n\n${userText}` }],
},
],
}, options);
if (response) return extractResponseText(response);
return callArkChatCompletions([
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userText },
], options);
}
function decodeDataPayload(raw: string): { mime: string; base64: string; bytes: Buffer } | null {
const trimmed = String(raw || '').trim();
if (!trimmed) return null;
const dataUrl = /^data:([^;,]+);base64,(.+)$/i.exec(trimmed);
const mime = dataUrl ? dataUrl[1].toLowerCase() : 'application/pdf';
const base64 = (dataUrl ? dataUrl[2] : trimmed).replace(/\s+/g, '');
if (!base64) return null;
try {
const bytes = Buffer.from(base64, 'base64');
if (!bytes.length) return null;
return { mime, base64, bytes };
} catch {
return null;
}
}
async function uploadArkUserFile(
runtime: ArkRuntimeConfig,
apiKey: string,
bytes: Buffer,
filename: string,
mime: string
): Promise<string | null> {
const form = new FormData();
form.append('purpose', 'user_data');
form.append('file', new Blob([new Uint8Array(bytes)], { type: mime }), filename);
const res = await fetch(`${runtime.baseUrl}/files`, {
method: 'POST',
signal: AbortSignal.timeout(arkFetchTimeoutMs()),
headers: { Authorization: `Bearer ${apiKey}` },
body: form,
});
if (!res.ok) {
const errText = await res.text();
console.error('ARK Files API failed:', res.status, errText.slice(0, 300));
return null;
}
const payload = (await res.json()) as { id?: string; status?: string };
return payload.id || null;
}
function isArkFileReadyStatus(status: string): boolean {
const s = status.toLowerCase();
return s === 'processed' || s === 'active' || s === 'ready' || s === 'completed' || s === 'success';
}
function isArkFilePendingStatus(status: string): boolean {
const s = status.toLowerCase();
return (
!s ||
s === 'processing' ||
s === 'pending' ||
s === 'running' ||
s === 'uploaded' ||
s === 'in_progress'
);
}
/** PDF 上传后会先处于 processing,必须等 processed 才能用 file_id */
async function waitForArkFileReady(
runtime: ArkRuntimeConfig,
apiKey: string,
fileId: string
): Promise<boolean> {
const maxAttempts = Number(process.env.ARK_FILE_POLL_MAX_ATTEMPTS || 40);
const intervalMs = Number(process.env.ARK_FILE_POLL_INTERVAL_MS || 500);
let retrieveFailed = 0;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
const res = await requestArk(runtime.baseUrl, `/files/${encodeURIComponent(fileId)}`, apiKey, {
method: 'GET',
});
if (res.ok) {
retrieveFailed = 0;
const payload = (await res.json()) as { status?: string; state?: string };
const status = String(payload.status || payload.state || '');
if (isArkFileReadyStatus(status)) {
console.info('ARK file ready:', { fileId, status, attempts: attempt + 1 });
return true;
}
if (status && !isArkFilePendingStatus(status)) {
console.error('ARK file processing failed:', { fileId, status });
return false;
}
} else {
retrieveFailed += 1;
if (retrieveFailed === 1) {
const errText = await res.text();
console.warn('ARK file retrieve failed:', res.status, errText.slice(0, 200));
}
// 部分账号没有 retrieve 接口:等几秒后直接尝试推理
if (retrieveFailed >= 3) {
await sleep(Math.max(intervalMs, 2000));
return true;
}
}
await sleep(intervalMs);
}
console.error('ARK file still processing after poll timeout:', fileId);
return false;
}
/** 文档理解:先 Files API 上传并等待 processed,再用 type=file / input_file */
export async function callArkWithFile(
systemPrompt: string,
fileBase64: string,
options?: ArkCallOptions & { filename?: string; mime?: string }
): Promise<string | null> {
const decoded = decodeDataPayload(fileBase64);
if (!decoded) return null;
const mime = options?.mime || decoded.mime || 'application/pdf';
const filename = options?.filename || (mime.includes('pdf') ? 'document.pdf' : 'document.bin');
const dataUrl = `data:${mime};base64,${decoded.base64}`;
const runtime = await resolveArkRuntimeConfig(options);
const apiKey = getNextApiKey(runtime.apiKeys);
if (!apiKey) return null;
const fileId = await uploadArkUserFile(runtime, apiKey, decoded.bytes, filename, mime);
if (fileId) {
const ready = await waitForArkFileReady(runtime, apiKey, fileId);
if (ready) {
const byId = await createArkResponse(
{
input: [
{
role: 'user',
content: [
{ type: 'input_file', file_id: fileId },
{ type: 'input_text', text: systemPrompt },
],
},
],
},
options,
apiKey
);
if (byId) return extractResponseText(byId);
const chatById = await callArkChatCompletions(
[
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: [
{ type: 'file', file: { file_id: fileId } },
{ type: 'text', text: '请严格按系统要求从这份 PDF 报告中抄录字段。' },
],
},
],
options,
apiKey
);
if (chatById) return chatById;
}
}
const byUrl = await createArkResponse(
{
input: [
{
role: 'user',
content: [
{ type: 'input_file', file_url: dataUrl },
{ type: 'input_text', text: systemPrompt },
],
},
],
},
options,
apiKey
);
if (byUrl) return extractResponseText(byUrl);
return callArkChatCompletions(
[
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: [
{ type: 'file', file: { file_data: dataUrl, filename } },
{ type: 'text', text: '请严格按系统要求从这份 PDF 报告中抄录字段。' },
],
},
],
options,
apiKey
);
}
export async function callArkWithImage(systemPrompt: string, imageBase64: string, options?: ArkCallOptions): Promise<string | null> {
const imageUrl = imageBase64.startsWith('data:')
? imageBase64
: `data:image/jpeg;base64,${imageBase64}`;
const userHint = '请分析这张图片,按系统要求输出结果。';
// 称重台等识图:优先 chat/completions(Responses 常对 Seed 图返回空/模板 null,见 20260909-weigh-doubao-chat-completions-prompt)
const chatText = await callArkChatCompletions(
[
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: imageUrl },
},
{
type: 'text',
text: userHint,
},
],
},
],
options
);
if (chatText && chatText.trim()) {
console.info('ARK image via chat/completions', {
model: options?.model || null,
branchCode: options?.branchCode || null,
textLength: chatText.trim().length,
});
return chatText;
}
console.warn('ARK image chat/completions empty, falling back to Responses API', {
model: options?.model || null,
});
const response = await createArkResponse({
input: [
{
role: 'user',
content: [
{ type: 'input_image', image_url: imageUrl },
{ type: 'input_text', text: systemPrompt },
],
},
],
}, options);
return response ? extractResponseText(response) : null;
}
export async function callArkWithImages(
systemPrompt: string,
imagesBase64: string[],
options?: ArkCallOptions
): Promise<string | null> {
const cleaned = (imagesBase64 || []).map((b) => String(b || '').trim()).filter(Boolean);
if (!cleaned.length) return null;
if (cleaned.length === 1) return callArkWithImage(systemPrompt, cleaned[0], options);
const urls = cleaned.map((b) => (b.startsWith('data:') ? b : `data:image/jpeg;base64,${b}`));
const userHint = `以上是同一批入库的 ${urls.length} 张照片,可能是同一商品的不同角度,请按系统要求合并后输出。`;
// 与单图一致:优先 chat/completions(Responses 常对 Seed 图返回空)
const content: Array<Record<string, unknown>> = urls.map((url) => ({
type: 'image_url',
image_url: { url },
}));
content.push({ type: 'text', text: userHint });
const chatText = await callArkChatCompletions(
[
{ role: 'system', content: systemPrompt },
{ role: 'user', content },
],
options
);
if (chatText && chatText.trim()) {
console.info('ARK images via chat/completions', {
model: options?.model || null,
branchCode: options?.branchCode || null,
imageCount: urls.length,
textLength: chatText.trim().length,
});
return chatText;
}
console.warn('ARK images chat/completions empty, falling back to Responses API', {
model: options?.model || null,
imageCount: urls.length,
});
const response = await createArkResponse(
{
input: [
{
role: 'user',
content: [
...urls.map((url) => ({ type: 'input_image', image_url: url })),
{ type: 'input_text', text: systemPrompt },
],
},
],
},
options
);
return response ? extractResponseText(response) : null;
}
export async function callArkWithAudio(
systemPrompt: string,
audioBase64: string,
audioFormat = 'webm',
options?: ArkCallOptions
): Promise<string | null> {
const normalizedFormat = audioFormat.replace(/^audio\//, '').split(';')[0] || 'webm';
const mimeType = normalizedFormat === 'mp3' ? 'audio/mpeg' : `audio/${normalizedFormat}`;
const audioDataUri = audioBase64.startsWith('data:')
? audioBase64
: `data:${mimeType};base64,${audioBase64}`;
const uriResponse = await createArkResponse({
input: [
{
role: 'user',
content: [
{ type: 'input_audio', audio_url: audioDataUri },
{ type: 'input_text', text: systemPrompt },
],
},
],
}, options);
if (uriResponse) return extractResponseText(uriResponse);
return null;
}
export function hasArkApiKey() {
return isArkConfigured();
}
export async function hasArkRuntimeConfig(options?: ArkCallOptions) {
const runtime = await resolveArkRuntimeConfig(options);
return runtime.apiKeys.length > 0;
}