From a83691ba342fdfe004582c0a5821422515150c94 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 27 Mar 2026 02:24:46 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20Chain-of-Verification=20=E2=80=94=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D1=86=D0=B8?= =?UTF-8?q?=D1=82=D0=B0=D1=82=20=D0=B2=20=D0=BE=D1=82=D0=B2=D0=B5=D1=82?= =?UTF-8?q?=D0=B5=20Claude?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Детерминированная проверка (без второго LLM вызова): - Извлекает из ответа: номера приказов, коды ГЭСН, проценты - Сверяет с CAG+RAG контекстом - Если факт не подтверждён — добавляет ⚠️ disclaimer Тесты: 812/пр+109% → OK, 999/пр+120% → warning, ГЭСН 28-01-999-01 → warning Co-Authored-By: Claude Opus 4.6 (1M context) --- claude_bridge_sonnet.py | 48 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/claude_bridge_sonnet.py b/claude_bridge_sonnet.py index 40ecefb..d2962a6 100644 --- a/claude_bridge_sonnet.py +++ b/claude_bridge_sonnet.py @@ -1,5 +1,8 @@ """Bridge for normative questions: Claude Sonnet via Docker CLI with CAG+RAG context. +Includes Chain-of-Verification: after response, checks cited facts +(order numbers, percentages) against CAG/RAG context. + Replaces GLM-5 for normative/regulatory questions. Uses Docker Claude CLI in non-interactive mode with --model sonnet. Context is passed via system prompt (CAG + RAG), not file mounts. @@ -26,6 +29,8 @@ from claude_bridge_glm import ( ALLOWED_EXTENSIONS, ) +import re + DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox") CLAUDE_CONFIG_DIR = os.environ.get("CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")) DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1") @@ -33,6 +38,42 @@ XRAY_PORT = os.environ.get("XRAY_PORT", "10809") _semaphore = asyncio.Semaphore(3) + +def _verify_response(response: str, system_prompt: str, user_context: str) -> str: + """Deterministic Chain-of-Verification: check cited facts against context. + + Extracts order numbers, percentages, GESN codes from response + and checks if they appear in the provided context. + Returns disclaimer text if unverified facts found. + """ + context = system_prompt + "\n" + user_context + context_lower = context.lower() + unverified = [] + + # Extract order references: "приказ XXX/пр", "приказ №XXX" + orders = re.findall(r"(?:приказ[а-я]*)\s*(?:№\s*)?(\d+)(?:/пр)?", response, re.IGNORECASE) + for order_num in orders: + if order_num not in context: + unverified.append(f"приказ {order_num}") + + # Extract GESN codes: "ГЭСН XX-XX-XXX-XX" + gesn_codes = re.findall(r"ГЭСН\s*(\d{2}-\d{2}-\d{3}-\d{2})", response) + for code in gesn_codes: + if code not in context: + unverified.append(f"ГЭСН {code}") + + # Extract specific percentages with context: "109%", "65%" + pct_claims = re.findall(r"(\d+(?:\.\d+)?)\s*%\s*(?:от\s+ФОТ|от\s+фонда)", response) + for pct in pct_claims: + if pct not in context: + unverified.append(f"{pct}%") + + if not unverified: + return "" + + items = ", ".join(set(unverified[:5])) + return f"\n\n---\n⚠️ *Следующие данные не подтверждены загруженной нормативной базой: {items}. Рекомендуется проверить по первоисточнику.*" + # Conversation history per (user, tab) _conversations: dict[tuple[str, str], list] = {} MAX_HISTORY = 10 @@ -187,6 +228,11 @@ async def stream_claude( except OSError: pass - # Save to history + # Chain-of-Verification: check cited facts against context if full_response: + verification = _verify_response(full_response, system_prompt, user_content) + if verification: + full_response += verification + yield f"event: text\ndata: {json.dumps({'text': verification}, ensure_ascii=False)}\n\n" + history.append({"role": "assistant", "content": full_response})