Files
SupplierSystem/server/src/services/assistantTurnLogService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

69 lines
2.2 KiB
TypeScript

import { pool } from '../db';
/**
* 助手逐次请求的用量与收尾原因(P2a,2026-09-22)。
*
* 改前:LLM 调用路径完全不解析 `usage` —— 成本不可见,也没有"这次是不是半途收尾"的留痕。
* 本服务每次 `/chat` 写一行:轮数、工具数、prompt/completion tokens、耗时、stop_reason。
* 全部 best-effort:写失败只告警,绝不影响对话本身。
*/
export type AssistantTurnLogInput = {
conversationId?: string | null;
userId: string;
branchCode: string;
surface: string;
provider?: string | null;
model?: string | null;
rounds?: number;
toolCalls?: number;
promptTokens?: number;
completionTokens?: number;
elapsedMs?: number;
stopReason?: string;
};
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const int = (n: unknown) => {
const v = Math.floor(Number(n) || 0);
return Number.isFinite(v) && v > 0 ? Math.min(v, 100_000_000) : 0;
};
const text = (v: unknown, max: number) => {
const s = String(v || '').trim();
return s ? s.slice(0, max) : null;
};
export async function logAssistantTurn(input: AssistantTurnLogInput): Promise<void> {
const userId = String(input.userId || '').trim();
const branchCode = String(input.branchCode || '').trim();
if (!userId || !branchCode) return;
const conversationId = UUID_RE.test(String(input.conversationId || '').trim())
? String(input.conversationId).trim()
: null;
try {
await pool.query(
`INSERT INTO assistant_turns (
conversation_id, user_id, branch_code, surface, provider, model,
rounds, tool_calls, prompt_tokens, completion_tokens, elapsed_ms, stop_reason
) VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
[
conversationId,
userId,
branchCode,
text(input.surface, 32) || 'web',
text(input.provider, 64),
text(input.model, 120),
int(input.rounds),
int(input.toolCalls),
int(input.promptTokens),
int(input.completionTokens),
int(input.elapsedMs),
text(input.stopReason, 32) || 'final',
]
);
} catch (error) {
console.warn('[assistant] 用量落库失败(不影响对话)', error);
}
}