feat: Chain-of-Verification — проверка цитат в ответе Claude
Детерминированная проверка (без второго LLM вызова): - Извлекает из ответа: номера приказов, коды ГЭСН, проценты - Сверяет с CAG+RAG контекстом - Если факт не подтверждён — добавляет ⚠️ disclaimer Тесты: 812/пр+109% → OK, 999/пр+120% → warning, ГЭСН 28-01-999-01 → warning Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
+47
-1
@@ -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})
|
||||
|
||||
Reference in New Issue
Block a user