agent-response-quality-smoke-test.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. 'use strict';
  2. const assert = require('assert/strict');
  3. const fs = require('fs');
  4. const os = require('os');
  5. const path = require('path');
  6. const RUN_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-response-quality-'));
  7. process.env.QIWEI_OUTPUTS_DIR = path.join(RUN_ROOT, 'outputs');
  8. const { AgentContextBuilder } = require('../mcp/src/core/agent-context-builder');
  9. const { QiweiAgentRuntime } = require('../mcp/src/core/agent-runtime');
  10. const { AgentWorkbenchDb } = require('../mcp/src/core/agent-workbench-db');
  11. const { AgentWorkbenchService } = require('../mcp/src/core/agent-workbench-service');
  12. const { verifyResponseQuality } = require('../mcp/src/core/response-quality-verifier');
  13. const LOW_QUALITY_JSONL = `
  14. {"id":"first_consult","inbound":"想了解你们的企业服务怎么收费?","reply":"您好,感谢您的咨询,我们一直致力于提供优质服务。"}
  15. {"id":"price_promise","inbound":"最低能做到多少钱?","reply":"保证给您全网最低价,一定不会更贵。"}
  16. {"id":"missing_info","inbound":"我想做员工培训","reply":"您的预算是多少?计划什么时候开始?预计多少人参加?"}
  17. {"id":"objection","inbound":"这个方案太贵了","reply":"您的预算是多少?"}
  18. {"id":"urgent","inbound":"今天能安排吗?","reply":"您好,感谢关注,我们会认真研究并持续努力为您提供全面周到专业细致的服务体验,请耐心等待。"}
  19. {"id":"complaint","inbound":"你们一直不处理,我要投诉","reply":"我们一定马上全部解决,绝对不会让您失望。"}
  20. {"id":"thanks","inbound":"谢谢","reply":"不客气,后续有需要随时联系。"}
  21. {"id":"answered_context","inbound":"预算已经说过是20万","reply":"请问您的预算是多少?","messages":[{"role":"assistant","content":"请问您的预算是多少?"}]}
  22. {"id":"repeat_question","inbound":"我还在考虑","reply":"请问您的预算是多少?","messages":[{"role":"assistant","content":"请问您的预算是多少?"}]}
  23. {"id":"tool_no_result","inbound":"有现成案例吗?","reply":"有的,我们已经找到 3 个完全匹配案例。","toolNoResult":true,"toolTrace":[{"tool":"search_knowledge","result":{"items":[]}}]}
  24. {"id":"low_quality","inbound":"能不能先给个建议?","reply":"好的。"}
  25. `;
  26. const GOOD_QUALITY_JSONL = `
  27. {"id":"first_consult","inbound":"想了解你们的企业服务怎么收费?","reply":"费用要按服务范围确认;您方便提供预计人数吗?确认后我给您对应报价。"}
  28. {"id":"price_check","inbound":"最低能做到多少钱?","reply":"当前最低价需要核验;我先核对适用方案,确认后给您准确答复。"}
  29. {"id":"missing_info","inbound":"我想做员工培训","reply":"可以先按员工培训方向梳理;请问预计多少人参加?确认人数后我给您下一步方案。"}
  30. {"id":"objection","inbound":"这个方案太贵了","reply":"我理解您主要顾虑投入是否值得;当前收益数据还需按场景核验,您最关注成本还是效果?确认后我补对应依据。"}
  31. {"id":"urgent","inbound":"今天能安排吗?","reply":"今天能否安排需要看当前档期;我现在核对,确认后尽快回复您。"}
  32. {"id":"complaint","inbound":"你们一直不处理,我要投诉","reply":"我理解您在意的是迟迟未处理;当前责任和处理结果需要人工核验,我现在转人工跟进并同步进度。"}
  33. {"id":"thanks","inbound":"谢谢","reply":""}
  34. {"id":"answered_context","inbound":"预算已经说过是20万","reply":"已记录预算20万;我会按这个上限继续整理,确认后给您方案。","messages":[{"role":"assistant","content":"请问您的预算是多少?"}]}
  35. {"id":"no_repeat","inbound":"我还在考虑","reply":"可以按您的节奏来;我先保留当前条件,有明确时间后再继续。","messages":[{"role":"assistant","content":"请问您的预算是多少?"}]}
  36. {"id":"tool_no_result","inbound":"有现成案例吗?","reply":"当前数据源没有返回可验证案例;我可以调整一个筛选条件后再查。","toolNoResult":true,"toolTrace":[{"tool":"search_knowledge","result":{"items":[]}}]}
  37. {"id":"suggestion","inbound":"能不能先给个建议?","reply":"可以,建议先明确最重要的结果目标;您最希望先解决哪个问题?确认后我给您第一版方案。"}
  38. `;
  39. function parseJsonl(value) {
  40. return String(value || '').trim().split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
  41. }
  42. function assessFixture(item) {
  43. return verifyResponseQuality({
  44. inboundContent: item.inbound,
  45. reply: item.reply,
  46. messages: item.messages || [],
  47. toolNoResult: Boolean(item.toolNoResult),
  48. toolTrace: item.toolTrace || [],
  49. });
  50. }
  51. function modelPayload(reply, overrides = {}) {
  52. return JSON.stringify({
  53. reply,
  54. confidence: 0.95,
  55. intent: 'quality_smoke',
  56. reason: '专项测试',
  57. requiresHuman: false,
  58. profileUpdates: {},
  59. tasks: [],
  60. alerts: [],
  61. ...overrides,
  62. });
  63. }
  64. function setupService(mode, output) {
  65. const dir = fs.mkdtempSync(path.join(RUN_ROOT, `${mode}-`));
  66. const db = new AgentWorkbenchDb(path.join(dir, 'workbench.db'), { defaultMode: mode, autoSendConfidence: 0.88 });
  67. const sent = [];
  68. const service = new AgentWorkbenchService({
  69. db,
  70. agent: {
  71. modelClient: { isConfigured: () => true },
  72. async run() { return { ...output }; },
  73. },
  74. qiwei: {
  75. isConfigured: () => true,
  76. async sendText(toId, content) { sent.push({ toId, content }); return { isSendSuccess: true }; },
  77. },
  78. config: {
  79. accountKey: 'quality-smoke',
  80. agent: { apiKey: 'smoke', model: 'stub', provider: 'stub', qualityPassScore: 82 },
  81. qiwei: { allowedSenders: ['contact-1'] },
  82. memory: { enabled: false },
  83. },
  84. });
  85. return {
  86. db,
  87. sent,
  88. service,
  89. close() { service.stopBackgroundWorkers(); db.close(); },
  90. };
  91. }
  92. async function main() {
  93. const lowCases = parseJsonl(LOW_QUALITY_JSONL);
  94. const goodCases = parseJsonl(GOOD_QUALITY_JSONL);
  95. const lowResults = lowCases.map(item => ({ id: item.id, assessment: assessFixture(item) }));
  96. const goodResults = goodCases.map(item => ({ id: item.id, assessment: assessFixture(item) }));
  97. const lowBlocked = lowResults.filter(item => !item.assessment.passed).length;
  98. const goodRejected = goodResults.filter(item => !item.assessment.passed);
  99. assert.equal(lowBlocked, lowCases.length, JSON.stringify(lowResults.filter(item => item.assessment.passed)));
  100. assert.deepEqual(goodRejected.map(item => ({ id: item.id, failed: item.assessment.failedCheckIds })), []);
  101. const unrelatedEvidence = verifyResponseQuality({
  102. inboundContent: '最低多少钱?',
  103. reply: '最低只要 99 元,我已经确认;我可以直接给您下单。',
  104. toolTrace: [{ tool: 'search_knowledge', result: { title: '品牌介绍', content: '成立于某年' } }],
  105. citations: [{ id: 'brand.md#intro', source: 'brand.md', heading: '品牌介绍' }],
  106. });
  107. assert.equal(unrelatedEvidence.passed, false);
  108. assert(unrelatedEvidence.failedCheckIds.includes('fact_evidence'));
  109. const claimBoundaryCases = [
  110. verifyResponseQuality({
  111. inboundContent: '价格确认了吗?',
  112. reply: '价格已确认,其他信息待核验;我可以继续帮您核对。',
  113. citations: [{ content: '其他信息待核验' }],
  114. }),
  115. verifyResponseQuality({
  116. inboundContent: '还有库存吗?',
  117. reply: '库存已确认;我可以直接为您保留。',
  118. toolTrace: [{ tool: 'inventory_lookup', result: { content: '库存字段说明' } }],
  119. }),
  120. verifyResponseQuality({
  121. inboundContent: '价格是多少?',
  122. reply: '已确认价格是 99 元,其他待核验;我可以把依据发给您。',
  123. citations: [{ content: '当前价格是 88 元' }],
  124. }),
  125. ];
  126. assert(claimBoundaryCases.every(item => !item.passed && item.failedCheckIds.includes('fact_evidence')));
  127. const sourcedPrice = verifyResponseQuality({
  128. inboundContent: '价格是多少?',
  129. reply: '已确认价格是 99 元;我可以把计价依据发给您。',
  130. citations: [{ content: '当前价格是 99 元' }],
  131. });
  132. assert.equal(sourcedPrice.passed, true, JSON.stringify(sourcedPrice.failedCheckIds));
  133. const splitPromise = verifyResponseQuality({
  134. inboundContent: '价格能确认吗?',
  135. reply: '保证是 99 元,其他待核验;我可以继续跟进。',
  136. citations: [{ content: '其他信息待核验' }],
  137. });
  138. assert.equal(splitPromise.passed, false);
  139. assert(splitPromise.failedCheckIds.includes('sensitive_commitment'));
  140. const bundledQuestions = verifyResponseQuality({
  141. inboundContent: '我想咨询服务',
  142. reply: '可以先了解需求;预算多少、什么时候开始、多少人参加?确认后我给您方案。',
  143. });
  144. assert.equal(bundledQuestions.passed, false);
  145. assert(bundledQuestions.failedCheckIds.includes('question_count'));
  146. const singleQuestion = verifyResponseQuality({
  147. inboundContent: '我想咨询服务',
  148. reply: '可以先明确投入范围;请问您的预算上限大概是多少?确认后我给您方案。',
  149. });
  150. assert.equal(singleQuestion.passed, true, JSON.stringify(singleQuestion.failedCheckIds));
  151. const semanticRepeat = verifyResponseQuality({
  152. inboundContent: '预算已经确认是20万',
  153. reply: '已记录当前需求;请问您的总投入上限多少?确认后我继续整理。',
  154. });
  155. assert.equal(semanticRepeat.passed, false);
  156. assert(semanticRepeat.failedCheckIds.includes('repeated_question'));
  157. for (const emptyAnswer of ['这边给您处理一下。', '我帮您关注一下。', '具体情况我再回复。']) {
  158. const assessment = verifyResponseQuality({ inboundContent: '当前有库存吗?', reply: emptyAnswer });
  159. assert.equal(assessment.passed, false);
  160. assert(assessment.failedCheckIds.includes('direct_answer'));
  161. }
  162. assert.equal(verifyResponseQuality({
  163. inboundContent: '当前有库存吗?',
  164. reply: '当前资料不足,需要先核验在售状态;我确认后回复您。',
  165. }).passed, true);
  166. const builder = new AgentContextBuilder({
  167. config: { promptCharLimit: 2400, systemPromptCharLimit: 2200, businessGoal: '推进到清晰且可执行的下一步' },
  168. knowledge: { contextText: () => '通用规则:未知事实必须核验。'.repeat(200) },
  169. });
  170. const system = builder.buildSystemContext({ memoryContext: { promptText: '旧 Session 说客户接受高价。'.repeat(100) } });
  171. const prompt = builder.buildClaudePrompt([
  172. { role: 'assistant', content: '请问预算是多少?' },
  173. { role: 'user', content: '本轮我只确认预算是20万。' },
  174. { role: 'tool', content: JSON.stringify({ result: '当前没有已核验报价' }) },
  175. ], {
  176. inboundContent: '本轮我只确认预算是20万。',
  177. profile: { profile: { budgetWan: 20, __evidence: { budgetWan: { text: '预算是20万' } } } },
  178. customerIntelligence: { tasks: [{ status: 'open', title: '确认时间' }], alerts: [] },
  179. });
  180. const budget = builder.budgetReport();
  181. assert(prompt.length <= 2400 && system.length <= 2200);
  182. assert.match(prompt, /本轮我只确认预算是20万/);
  183. assert.match(system, /旧模型 Session/);
  184. assert(Object.values(budget.prompt).every(item => item.used <= item.budget));
  185. assert(Object.values(budget.system).every(item => item.used <= item.budget));
  186. const [requestA, requestB] = await Promise.all([
  187. Promise.resolve(builder.buildClaudePromptResult([{ role: 'user', content: '请求甲的唯一内容' }], { profile: { profile: { request: 'A' } } })),
  188. Promise.resolve(builder.buildClaudePromptResult([{ role: 'user', content: '请求乙的唯一内容' }], { profile: { profile: { request: 'B' } } })),
  189. ]);
  190. assert.match(requestA.text, /请求甲的唯一内容/);
  191. assert.doesNotMatch(requestA.text, /请求乙的唯一内容/);
  192. assert.match(requestB.text, /请求乙的唯一内容/);
  193. assert.notDeepEqual(requestA.budgetReport, {});
  194. assert.notStrictEqual(requestA.budgetReport, requestB.budgetReport);
  195. const sequence = [
  196. modelPayload('您好,感谢您的咨询,请耐心等待。'),
  197. modelPayload('今天能否安排需要核对当前档期;我现在核对,确认后尽快回复您。'),
  198. ];
  199. const runtime = new QiweiAgentRuntime({
  200. config: { provider: 'stub', maxToolRounds: 2, qualityPassScore: 82 },
  201. knowledge: { search: () => [], contextText: () => '' },
  202. modelClient: { async complete() { return { content: sequence.shift() }; } },
  203. });
  204. const rewritten = await runtime.run({
  205. conversation: { id: 'runtime-rewrite', mode: 'autopilot' },
  206. messages: [{ direction: 'inbound', content: '今天能安排吗?' }],
  207. profile: { profile: {} },
  208. inboundContent: '今天能安排吗?',
  209. });
  210. assert.equal(rewritten.rewriteCount, 1);
  211. assert.equal(rewritten.qualityPassed, true);
  212. assert.equal(rewritten.requiresHuman, false);
  213. let failedCalls = 0;
  214. const failedRuntime = new QiweiAgentRuntime({
  215. config: { provider: 'stub', maxToolRounds: 2, qualityPassScore: 82 },
  216. knowledge: { search: () => [], contextText: () => '' },
  217. modelClient: { async complete() { failedCalls += 1; return { content: modelPayload('好的。') }; } },
  218. });
  219. const failedRewrite = await failedRuntime.run({
  220. conversation: { id: 'runtime-fallback', mode: 'autopilot' },
  221. messages: [{ direction: 'inbound', content: '今天能安排吗?' }],
  222. profile: { profile: {} },
  223. inboundContent: '今天能安排吗?',
  224. });
  225. assert.equal(failedCalls, 2);
  226. assert.equal(failedRewrite.rewriteCount, 1);
  227. assert.equal(failedRewrite.qualityPassed, false);
  228. assert.equal(failedRewrite.requiresHuman, true);
  229. assert(failedRewrite.fallbackReason);
  230. const qualified = {
  231. content: '今天能否安排需要核对当前档期;我现在核对,确认后尽快回复您。',
  232. confidence: 0.95,
  233. intent: 'schedule',
  234. reason: '当前档期需要核验',
  235. requiresHuman: false,
  236. profileUpdates: {}, tasks: [], alerts: [], citations: [], toolTrace: [],
  237. };
  238. const low = {
  239. content: '好的。', confidence: 0.95, intent: 'schedule', reason: 'low', requiresHuman: false,
  240. profileUpdates: {}, tasks: [], alerts: [], citations: [], toolTrace: [], rewriteCount: 1,
  241. };
  242. for (const mode of ['review', 'auto', 'autopilot']) {
  243. const ctx = setupService(mode, low);
  244. try {
  245. const result = await ctx.service.ingestInbound({ externalId: `low-${mode}`, contactId: 'contact-1', content: '今天能安排吗?' });
  246. assert.equal(result.status, 'pending_review');
  247. assert.equal(result.draft.requires_human, true);
  248. assert.equal(result.draft.quality.qualityPassed, false);
  249. assert(result.draft.quality.qualityChecks.length >= 10);
  250. assert(result.draft.quality.fallbackReason);
  251. assert.equal(ctx.sent.length, 0);
  252. } finally { ctx.close(); }
  253. }
  254. for (const mode of ['auto', 'autopilot']) {
  255. const ctx = setupService(mode, qualified);
  256. try {
  257. const result = await ctx.service.ingestInbound({ externalId: `good-${mode}`, contactId: 'contact-1', content: '今天能安排吗?' });
  258. assert.equal(result.status, mode === 'auto' ? 'sent' : 'autopilot_sent');
  259. assert.equal(ctx.sent.length, 1);
  260. } finally { ctx.close(); }
  261. }
  262. const human = setupService('review', low);
  263. try {
  264. const draftResult = await human.service.ingestInbound({ externalId: 'human-draft', contactId: 'contact-1', content: '今天能安排吗?' });
  265. await human.service.approveDraft(draftResult.draft.id, { content: '好的。', actor: 'human' });
  266. await human.service.manualSend(draftResult.conversation.id, '收到。', 'human');
  267. assert.equal(human.sent.length, 2);
  268. } finally { human.close(); }
  269. const directAutopilot = setupService('autopilot', qualified);
  270. try {
  271. const conversation = directAutopilot.db.ensureConversation('contact-1', '匿名客户');
  272. const inbound = directAutopilot.db.insertMessage({
  273. conversationId: conversation.id,
  274. direction: 'inbound',
  275. senderType: 'customer',
  276. content: '今天能安排吗?',
  277. }).message;
  278. await assert.rejects(() => directAutopilot.service.sendAutopilotReply(conversation, inbound, {
  279. ...low,
  280. qualityPassed: false,
  281. requiresHuman: true,
  282. }), /质量校验/);
  283. assert.equal(directAutopilot.sent.length, 0);
  284. } finally { directAutopilot.close(); }
  285. const thanks = setupService('autopilot', qualified);
  286. try {
  287. const result = await thanks.service.ingestInbound({ externalId: 'thanks', contactId: 'contact-1', content: '谢谢' });
  288. assert.equal(result.status, 'no_reply_needed');
  289. assert.equal(thanks.sent.length, 0);
  290. } finally { thanks.close(); }
  291. const summary = {
  292. baseline: { lowQualityAutopilotSent: 11, lowQualityBlocked: 0 },
  293. current: {
  294. lowQualityCases: lowCases.length,
  295. lowQualityBlocked: lowBlocked,
  296. lowQualityBlockRate: lowBlocked / lowCases.length,
  297. goodQualityCases: goodCases.length,
  298. goodQualityRejected: goodRejected.length,
  299. goodQualityFalsePositiveRate: goodRejected.length / goodCases.length,
  300. },
  301. modes: ['review low->draft', 'auto low->draft', 'autopilot low->draft', 'auto good->sent', 'autopilot good->sent', 'human bypass', 'thanks no-reply'],
  302. };
  303. process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
  304. }
  305. main().catch(error => {
  306. console.error(error);
  307. process.exitCode = 1;
  308. }).finally(() => {
  309. fs.rmSync(RUN_ROOT, { recursive: true, force: true });
  310. });