"""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. """ import asyncio import json import os from pathlib import Path from typing import AsyncGenerator from claude_bridge_glm import ( _build_system_prompt, _load_smeta_data, _search_normative, _read_work_dir_files, get_work_dir, get_session_id, set_session_id, clear_session, is_allowed_file, list_user_files, 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") 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 def _build_context(message: str, username: str, tab_id: str) -> str: """Build enriched user message with RAG + resources + files context.""" _load_smeta_data() work_dir = get_work_dir(username, tab_id) # Search resources resource_context = "" gesn_patterns = [ "расценк", "гэсн", "норм", "28-", "01-", "единиц", "земляны", "бетон", "монтаж", "насыпь", "балласт", "рельс", "стрелоч", "шпал", "щебен", "щебн", "укладк", "разборк", "кровел", "штукатур", "гидроизоляц", "теплоизоляц", "трубопровод", "кабел", "электромонтаж", "сантехн", "вентиляц", "благоустр", "сварочн", "устройство", "ремонт пути", "всп", "сцб", ] if any(p in message.lower() for p in gesn_patterns): from claude_bridge_glm import _resources from search_engine import _search_resources resource_context = _search_resources(message, _resources) # Normative RAG normative_context = _search_normative(message) # Files in work dir file_context = _read_work_dir_files(work_dir) # Compose user_content = message if file_context: user_content = f"{message}\n\n[Файлы в рабочей директории]{file_context}" if resource_context: user_content += f"\n\n[Данные из базы ФСНБ-2022]\n{resource_context}" if normative_context: user_content += f"\n\n[{normative_context}]" return user_content async def stream_claude( message: str, username: str, tab_id: str = "default", ) -> AsyncGenerator[str, None]: """Stream Claude Sonnet response via Docker CLI with CAG+RAG context.""" async with _semaphore: key = (username, tab_id) # Load history from SQLite (survives restarts) from db import get_history db_history = get_history(username, tab_id, limit=6) # Build system prompt (CAG) and enriched user message (RAG) system_prompt = _build_system_prompt() user_content = _build_context(message, username, tab_id) # Build full prompt from DB history + current message prompt_parts = [] for msg in db_history[-4:]: # last 2 exchanges from DB role = "Пользователь" if msg["role"] == "user" else "Ассистент" prompt_parts.append(f"[{role}]: {msg['content'][:500]}") prompt_parts.append(f"[Пользователь]: {user_content}") full_prompt = "\n\n".join(prompt_parts) # Write both prompts to temp files (avoid "Argument list too long") import tempfile system_file = tempfile.NamedTemporaryFile( mode="w", suffix=".txt", delete=False, encoding="utf-8" ) system_file.write(system_prompt) system_file.close() prompt_file = tempfile.NamedTemporaryFile( mode="w", suffix=".txt", delete=False, encoding="utf-8" ) prompt_file.write(full_prompt) prompt_file.close() # Docker command — mount prompt files, use --entrypoint sh to avoid # Claude CLI intercepting "bash" as a prompt cmd = [ "docker", "run", "--rm", "--memory=512m", "--cpus=1", "--network=host", "-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude", "-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json", "-v", f"{system_file.name}:/tmp/system.txt:ro", "-v", f"{prompt_file.name}:/tmp/prompt.txt:ro", "-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", "HOME=/home/worker", "--entrypoint", "sh", DOCKER_IMAGE, "-c", "cat /tmp/prompt.txt | claude -p --model sonnet --output-format stream-json --verbose --system-prompt-file /tmp/system.txt --max-turns 1", ] try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) except FileNotFoundError: yield f"event: text\ndata: {json.dumps({'text': 'Docker not available'}, ensure_ascii=False)}\n\n" yield f"event: done\ndata: {json.dumps({'result': 'Docker not available'})}\n\n" return import logging logger = logging.getLogger("sonnet_bridge") full_response = "" try: while True: raw_line = await proc.stdout.readline() if not raw_line: break line = raw_line.decode().strip() if not line: continue try: event = json.loads(line) except json.JSONDecodeError: logger.warning("Non-JSON line: %s", line[:100]) continue etype = event.get("type", "") logger.info("Event: %s", etype) if etype == "assistant": msg = event.get("message", {}) for block in msg.get("content", []): if block.get("type") == "text": text = block["text"] full_response += text yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" elif etype == "result": result_text = event.get("result", "") if not full_response and result_text: full_response = result_text yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n" finally: if proc.returncode is None: proc.terminate() try: await asyncio.wait_for(proc.wait(), timeout=5) except asyncio.TimeoutError: proc.kill() # Cleanup temp files for f in [system_file.name, prompt_file.name]: try: os.unlink(f) except OSError: pass # 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"