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 { 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); } }