2 Commits
Author SHA1 Message Date
anorandClaude Fable 5 4d178710e3 refactor(4.3): вынести роутер в routing.decide_engine + детерминированный юнит-тест (поведение не меняется)
Закрывает аудит-претензию «хрупкий нетестируемый keyword-роутер»: логика
идентична прежней inline-версии, но теперь покрыта прямым тестом (5 кейсов) в CI.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 18:23:55 +10:00
anorandClaude Fable 5 861da5e981 refactor(4.2): удалить мёртвый код — batch_v2.py (слит в batch_v3) + claude_bridge_direct.py.deprecated
Не импортируются нигде. batch.py оставлен (используется ручными scripts/test_*batch*).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 18:21:16 +10:00
6 changed files with 127 additions and 668 deletions
+1 -1
View File
@@ -12,4 +12,4 @@ jobs:
- name: Синтаксис всех модулей (py_compile)
run: python3 -m py_compile *.py
- name: Юнит-тесты без живого сервера
run: python3 -m pytest tests/test_chat_context.py tests/test_code_validator.py tests/test_gge_deep.py -q
run: python3 -m pytest tests/test_chat_context.py tests/test_code_validator.py tests/test_gge_deep.py tests/test_routing.py -q
-473
View File
@@ -1,473 +0,0 @@
"""Batch V2: Claude Code analyzes ALL files, generates custom script.
Unlike V1 (GLM + deterministic template), V2 uses Claude Code (1M context)
to read actual file contents and generate a tailored Python script.
Flow:
1. User uploads zip (smetas) + target xlsx + task description
2. Server extracts, converts ALL xlsx → CSV (handles broken openpyxl files)
3. Claude Code reads CSVs + target, generates Python script
4. User confirms → script executes on all files
5. Result: updated target xlsx
"""
import asyncio
import csv
import json
import os
import shutil
import time
import traceback
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import AsyncGenerator
from batch import read_xlsx_xml, extract_zip
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")
# Batch V2 jobs storage
_jobs: dict[str, dict] = {}
# Token estimation: ~0.3 tokens per byte for CSV text
TOKENS_PER_BYTE = 0.3
MAX_CONTEXT_TOKENS = 800_000 # leave headroom from 1M
MAX_SAMPLE_FILES = 15 # sample xlsx for Claude to read
MAX_SAMPLE_BYTES = 500_000 # max total bytes of sample CSVs
def convert_xlsx_to_csv(xlsx_path: str, output_dir: str) -> list[str]:
"""Convert xlsx to CSV files via XML parser (handles broken styles).
Returns list of created CSV file paths.
"""
data = read_xlsx_xml(xlsx_path, max_rows=9999)
if "_error" in data and len(data) == 1:
return []
created = []
stem = Path(xlsx_path).stem
for sheet_name, rows in data.items():
if sheet_name == "_error":
continue
# Skip empty sheets
if not rows or all(not any(cell for cell in row) for row in rows):
continue
safe_name = "".join(c if c.isalnum() or c in " _-" else "_" for c in sheet_name)
csv_path = Path(output_dir) / f"{stem}__{safe_name}.csv"
with open(csv_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
created.append(str(csv_path))
return created
def convert_all_to_csv(source_dir: str, csv_dir: str) -> dict:
"""Convert all xlsx files in source_dir to CSV in csv_dir.
Returns {"files": [...], "total_bytes": int, "estimated_tokens": int}.
"""
Path(csv_dir).mkdir(parents=True, exist_ok=True)
all_csv = []
total_bytes = 0
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
xlsx_files = sorted(
f for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and not f.name.startswith("._")
)
for xlsx in xlsx_files:
# .gge/.esw are XML — copy as-is (no xlsx conversion needed)
if xlsx.suffix.lower() in ('.gge', '.esw', '.xml'):
dst = Path(csv_dir) / f"{xlsx.stem}.xml"
import shutil
shutil.copy2(str(xlsx), str(dst))
size = dst.stat().st_size
all_csv.append({"path": str(dst), "name": dst.name, "bytes": size})
total_bytes += size
continue
csvs = convert_xlsx_to_csv(str(xlsx), csv_dir)
for c in csvs:
size = Path(c).stat().st_size
all_csv.append({"path": c, "name": Path(c).name, "bytes": size})
total_bytes += size
return {
"files": all_csv,
"total_bytes": total_bytes,
"estimated_tokens": int(total_bytes * TOKENS_PER_BYTE),
"xlsx_count": len(xlsx_files),
}
def select_samples(source_dir: str, csv_info: dict) -> list[str]:
"""Select a diverse sample of xlsx files for Claude to analyze.
Strategy: pick files of different sizes and from different subdirs.
Returns list of xlsx file paths (originals, not CSV).
"""
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
xlsx_files = sorted(
[f for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and not f.name.startswith("._")],
key=lambda f: f.stat().st_size,
)
if len(xlsx_files) <= MAX_SAMPLE_FILES:
return [str(f) for f in xlsx_files]
# Pick diverse: smallest, largest, and evenly spaced
n = len(xlsx_files)
indices = set()
indices.add(0) # smallest
indices.add(n - 1) # largest
# Evenly spaced
step = max(1, n // (MAX_SAMPLE_FILES - 2))
for i in range(0, n, step):
indices.add(i)
if len(indices) >= MAX_SAMPLE_FILES:
break
# If still room, add from different directories
if len(indices) < MAX_SAMPLE_FILES:
dirs_seen = set()
for i, f in enumerate(xlsx_files):
d = str(f.parent)
if d not in dirs_seen:
dirs_seen.add(d)
indices.add(i)
if len(indices) >= MAX_SAMPLE_FILES:
break
return [str(xlsx_files[i]) for i in sorted(indices)][:MAX_SAMPLE_FILES]
def prepare_samples(source_dir: str, job_dir: Path, csv_info: dict) -> dict:
"""Convert only sample files to CSV in /data/sample_csv/ for Claude.
Returns {"sample_files": [...], "sample_csv_dir": str}.
"""
sample_xlsx = select_samples(source_dir, csv_info)
sample_csv_dir = job_dir / "sample_csv"
sample_csv_dir.mkdir(parents=True, exist_ok=True)
converted_xlsx = []
sample_csvs = []
total_bytes = 0
for xlsx in sample_xlsx:
# .gge/.esw/.xml — copy as-is, no xlsx conversion
if Path(xlsx).suffix.lower() in ('.gge', '.esw', '.xml'):
import shutil as _shutil
dst = sample_csv_dir / f"{Path(xlsx).stem}.xml"
_shutil.copy2(xlsx, str(dst))
converted_xlsx.append(xlsx)
sample_csvs.append(str(dst))
total_bytes += dst.stat().st_size
continue
csvs = convert_xlsx_to_csv(xlsx, str(sample_csv_dir))
converted_xlsx.append(xlsx)
for c in csvs:
size = Path(c).stat().st_size
sample_csvs.append(c)
total_bytes += size
if total_bytes > MAX_SAMPLE_BYTES:
break
return {
"sample_files": converted_xlsx,
"sample_csv_dir": str(sample_csv_dir),
"sample_csv_count": len(sample_csvs),
"sample_bytes": total_bytes,
}
def build_claude_prompt(
task_description: str,
sample_csv_dir: str,
target_csv_dir: str,
target_filename: str,
total_xlsx_count: int,
sample_xlsx_names: list[str],
) -> str:
"""Build the prompt for Claude Code to analyze sample files and generate script."""
sample_names = "\n".join(f"- {Path(f).name}" for f in sample_xlsx_names)
return f"""You are an expert in Russian construction cost estimation (smeta).
## Task
{task_description}
## Source files
There are {total_xlsx_count} xlsx source files total. You have {len(sample_xlsx_names)} SAMPLE files
converted to CSV in /data/sample_csv/ for analysis.
CSV naming: {{original_xlsx_stem}}__{{sheet_name}}.csv
Sample files:
{sample_names}
## Target file
The target summary file is converted to CSV in /data/target_csv/.
Original filename: {target_filename}
NOTE: In the script, use the `target_file` variable (not a hardcoded path).
## Your job
1. Read the sample CSV files in /data/sample_csv/ — understand their structure
2. Read the target CSV files in /data/target_csv/ — understand where data goes
3. Figure out: what to extract from each source, how to match to target rows
4. FIRST write /data/batch_summary.json, THEN write /data/batch_script.py
## MANDATORY: /data/batch_summary.json — write this FIRST!
The user is a construction estimator, not a programmer. This summary is shown to them for review.
JSON with these fields (in Russian):
```json
{{
"description": "Краткое описание что будет сделано",
"source_patterns": {{
"sheet": "на каком листе искать данные",
"id_field": "где шифр/название сметы (например: имя файла, ячейка B5)",
"totals": {{
"строительные работы": "паттерн поиска (например: ВСЕГО строительные работы)",
"монтажные работы": "паттерн поиска",
"оборудование": "паттерн поиска",
"прочие затраты": "паттерн поиска"
}},
"value_column": "в каком столбце значения (например: A или H)",
"units": "рубли или тыс.руб"
}},
"target_mapping": {{
"sheet": "на какой лист сводного файла записывать",
"match_column": "столбец с шифрами для сопоставления (например: B)",
"value_columns": {{
"строительные работы": "столбец (например: D)",
"монтажные работы": "столбец (например: E)",
"оборудование": "столбец (например: F)",
"прочие затраты": "столбец (например: G)"
}},
"units": "тыс.руб"
}},
"conversion": "делить на 1000 (руб → тыс.руб)" или "без конвертации",
"preview": [
{{
"source_file": "имя файла источника",
"source_values": {{"строительные работы": 15460805.77, "монтажные работы": 0}},
"target_sheet": "ССРСС ТУЦ",
"target_row": "строка 17 (ЛС-01-02-2-00-01 Устройство насыпи)",
"target_values": {{"D": 15460.81, "E": 0, "F": 0, "G": 0}}
}}
]
}}
```
The "preview" array must contain entries for ALL sample files — show the actual extracted values
and where they will go in the target. This is the most important part for the user to verify!
### File 2: /data/batch_script.py — Python script
## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples!
The script must handle any file with the same general structure as the samples.
## Script execution context (these variables will be available):
- `source_files`: list[str] — paths to ALL {total_xlsx_count} original xlsx files
- `target_file`: str — path to target xlsx (a copy, safe to modify)
- `job`: dict — job["processed"] += 1 per file, job["errors"].append("msg") for errors
- `read_xlsx_xml(path, max_rows=9999)`: dict[sheet_name, list[list[str]]]
IMPORTANT: ALWAYS pass max_rows=9999! Default is only 50 rows — totals are at the END of files!
Column indices: A=0, B=1, C=2, ..., H=7, etc. Values are strings.
- `openpyxl`: for writing to target xlsx
- `Path`, `csv`, `json`, `re`, `os`
## Script requirements
- Self-contained, using ONLY the variables above
- NO `if __name__` or `def main()` wrappers — top-level code
- Robust: skip files with unexpected structure, log to job["errors"]
- Track progress: job["processed"] += 1 after each successful file
- Save at the end: wb.save(target_file)
"""
def _read_result_files(job_dir: Path) -> dict:
"""Read batch_script.py and batch_summary.json from job dir."""
script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists():
return {"script": script_path.read_text(encoding="utf-8"), "summary": summary}
return {"script": "", "result": "Script not generated", "summary": summary}
async def run_claude_analysis(
job_dir: Path,
task_description: str,
target_filename: str,
total_xlsx_count: int,
sample_info: dict,
) -> AsyncGenerator[dict, None]:
"""Run Claude Code in Docker to analyze files and generate script.
Yields SSE-like dicts: {"type": "text", "text": "..."} or {"type": "tool", "tool": "..."}
Final yield: {"type": "done", "script": "..."} or {"type": "error", "error": "..."}
"""
target_csv_dir = str(job_dir / "target_csv")
prompt = build_claude_prompt(
task_description,
sample_info["sample_csv_dir"],
target_csv_dir,
target_filename,
total_xlsx_count,
sample_info["sample_files"],
)
# Docker command — mount job_dir as /data
cmd = [
"docker", "run", "--rm",
"--memory=1g",
"--cpus=2",
"--network=host",
# Mount job directory as /data (rw)
"-v", f"{job_dir.resolve()}:/data",
# Mount Claude auth
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
# Environment
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
"-e", "HOME=/home/worker",
"-w", "/data",
DOCKER_IMAGE,
# Claude args
"-p", prompt,
"--output-format", "stream-json",
"--verbose",
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
"--max-turns", "30",
]
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL, # don't capture stderr — prevents buffer deadlock
)
except FileNotFoundError:
yield {"type": "done", "script": "", "result": "Docker not found"}
return
got_result = False
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:
continue
etype = event.get("type", "")
if etype == "assistant":
msg = event.get("message", {})
for block in msg.get("content", []):
if block.get("type") == "text":
yield {"type": "text", "text": block["text"]}
elif block.get("type") == "tool_use":
yield {"type": "tool", "tool": block.get("name", "")}
elif etype == "result":
got_result = True
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
finally:
if proc.returncode is None:
proc.terminate()
try:
await asyncio.wait_for(proc.wait(), timeout=5)
except asyncio.TimeoutError:
proc.kill()
# Fallback: Claude exited without result event — check files on disk
if not got_result:
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str):
"""Execute the Claude-generated script. Same as V1 but with more imports."""
job = _jobs[job_id]
job["status"] = "running"
job["started_at"] = time.time()
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
source_files = [
str(f) for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and not f.name.startswith("._")
]
job["total_files"] = len(source_files)
job["processed"] = 0
job["errors"] = []
# Copy target to output
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
shutil.copy2(target_file, output_file)
try:
exec_globals = {
"__builtins__": __builtins__,
"source_files": source_files,
"target_file": output_file,
"job": job,
"read_xlsx_xml": read_xlsx_xml,
"Path": Path,
"csv": csv,
"json": json,
"zipfile": zipfile,
"ET": ET,
"os": os,
"re": __import__("re"),
}
try:
import openpyxl
exec_globals["openpyxl"] = openpyxl
except ImportError:
pass
exec(script, exec_globals)
job["status"] = "completed"
job["output_file"] = output_file
except Exception as e:
job["status"] = "failed"
job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
job["finished_at"] = time.time()
def create_job(job_id: str) -> dict:
_jobs[job_id] = {
"id": job_id,
"status": "created",
"total_files": 0,
"processed": 0,
"errors": [],
}
return _jobs[job_id]
def get_job(job_id: str) -> dict | None:
return _jobs.get(job_id)
-150
View File
@@ -1,150 +0,0 @@
"""Bridge between FastAPI and Claude Code CLI subprocess."""
import asyncio
import json
import os
from pathlib import Path
from typing import AsyncGenerator
CLAUDE_BIN = os.environ.get(
"CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude")
)
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
APP_DIR = Path(__file__).parent
# Session tracking: (username, tab_id) -> claude session_id (#12)
_sessions: dict[tuple[str, str], str] = {}
# Concurrency limit (#11 DoS)
_semaphore = asyncio.Semaphore(3)
def get_work_dir(username: str, tab_id: str) -> Path:
d = DATA_DIR / username / tab_id
d.mkdir(parents=True, exist_ok=True)
return d
def get_session_id(username: str, tab_id: str) -> str | None:
return _sessions.get((username, tab_id))
def set_session_id(username: str, tab_id: str, sid: str):
_sessions[(username, tab_id)] = sid
def clear_session(username: str, tab_id: str):
_sessions.pop((username, tab_id), None)
# Whitelist of allowed file extensions (#6)
ALLOWED_EXTENSIONS = {
".xlsx", ".xls", ".docx", ".doc", ".pdf",
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
".gge", ".esw", ".ges", ".smr", ".smt",
".zip", ".rar", ".7z",
}
def is_allowed_file(filename: str) -> bool:
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
# Minimal env for subprocess (#7 — don't leak all env vars)
def _build_claude_env() -> dict[str, str]:
env = {
"HOME": os.environ.get("HOME", "/home/mcp-user"),
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
"LANG": os.environ.get("LANG", "en_US.UTF-8"),
"HTTPS_PROXY": os.environ.get("HTTPS_PROXY", "http://127.0.0.1:10809"),
"HTTP_PROXY": os.environ.get("HTTP_PROXY", "http://127.0.0.1:10809"),
}
# Claude Code needs XDG dirs
for k in ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "NODE_PATH"):
if k in os.environ:
env[k] = os.environ[k]
return env
async def stream_claude(
message: str,
username: str,
tab_id: str = "default",
) -> AsyncGenerator[str, None]:
"""Run claude CLI, yield SSE-formatted events."""
async with _semaphore:
work_dir = get_work_dir(username, tab_id)
session_id = get_session_id(username, tab_id)
instructions = APP_DIR / "claude_project_instructions.md"
cmd = [
CLAUDE_BIN, "-p", message,
"--output-format", "stream-json",
"--verbose",
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
]
if instructions.exists():
cmd.extend(["--append-system-prompt-file", str(instructions)])
if session_id:
cmd.extend(["--resume", session_id])
env = _build_claude_env()
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(work_dir),
env=env,
)
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:
continue
etype = event.get("type", "")
if etype == "assistant":
msg = event.get("message", {})
for block in msg.get("content", []):
if block.get("type") == "text":
text = block["text"]
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
elif block.get("type") == "tool_use":
name = block.get("name", "")
yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n"
elif etype == "result":
sid = event.get("session_id", "")
if sid:
set_session_id(username, tab_id, sid)
result_text = event.get("result", "")
yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n"
finally:
if proc.returncode is None:
proc.terminate()
await proc.wait()
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
"""List files in user's work directory."""
work_dir = get_work_dir(username, tab_id)
files = []
for f in sorted(work_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
files.append({
"name": f.name,
"size": f.stat().st_size,
})
return files
+5 -44
View File
@@ -34,30 +34,12 @@ elif AI_BACKEND == "hybrid":
stream_claude as _stream_glm,
)
from claude_bridge import stream_claude as _stream_claude
from routing import decide_engine
async def stream_claude(message: str, username: str, tab_id: str = "default"):
msg_lower = message.lower()
# Сильные индикаторы агентской задачи → Claude CLI
agent_actions = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь файл", "открой файл",
"загруж", "прикреп", ".xlsx", ".xlsm", ".docx", ".pdf", ".csv",
"ячейк", "столбец d", "столбец e", "лист 15", "вкладк",
"заполни пункт", "сматчи", "сопостав", "извлеки",
]
# Сильные индикаторы нормативки → DeepSeek
reference_words = [
"какой нр", "какой сп", "какая нр", "какая сп",
"коэффициент", "зимнее удорожан", "временные здани",
"расценк", "найди расценку", "найди норму",
"сметная цена", "цена материал",
"приказ ", "фснб", "методик",
"посчитай нр", "посчитай сп", "рассчитай",
"что ты умеешь", "помощь", "help",
]
# Файл из work_dir упомянут по имени → Claude
# Файл из work_dir упомянут по имени → агентский путь (mentions_file).
from claude_bridge_glm import get_work_dir as _gw
msg_lower = message.lower()
work_dir = _gw(username, tab_id)
mentions_file = False
if work_dir.exists():
@@ -68,29 +50,8 @@ elif AI_BACKEND == "hybrid":
if any(p in msg_lower for p in parts):
mentions_file = True
break
is_agent = mentions_file or any(kw in msg_lower for kw in agent_actions)
is_reference = any(kw in msg_lower for kw in reference_words)
# Расчёт сметы по объёмам работ → агентный Claude (Sonnet): он тянет
# реальные цены корпуса и считает пошагово (страховка в claude_bridge).
# Реальный смета-запрос (составь/посчитай смету на объект) — даже без
# явных единиц объёма. Агентный путь тянет реальные коды/цены корпуса,
# может проверить материалы в интернете и при нехватке объёмов переспросит.
# Раньше требовались единицы (м3/м2…), из-за чего «составь смету на туалет»
# уходил на одно-проходный DeepSeek и выдумывал цены/материалы/«файлы».
is_smeta_calc = (
(("смет" in msg_lower or "стоимост" in msg_lower)
and any(k in msg_lower for k in ("посчита", "рассчита", "составь", "сделай смет", "построй смет")))
or ("смета на" in msg_lower or "смету на" in msg_lower))
if is_smeta_calc:
stream_fn = _stream_claude # расчёт сметы — только агентный путь
elif is_agent and not is_reference:
stream_fn = _stream_claude
elif is_reference and not is_agent:
stream_fn = _stream_glm
elif is_agent and is_reference:
stream_fn = _stream_claude # ambiguous → агент сильнее
else:
stream_fn = _stream_glm
# Решение вынесено в routing.decide_engine (детерминированный юнит-тест).
stream_fn = _stream_claude if decide_engine(message, mentions_file) == "claude" else _stream_glm
async for chunk in stream_fn(message, username, tab_id):
yield chunk
elif AI_BACKEND == "auto":
+63
View File
@@ -0,0 +1,63 @@
"""Гибридный роутер: выбор движка ответа по тексту сообщения.
GLM (DeepSeek) — нормативные вопросы (НР/СП/коэффициенты/индексы/расценки),
~95% запросов; дёшево и быстро. Claude CLI (Docker + MCP) — агентские задачи
с файлами и расчёт смет.
Вынесено из main.py БЕЗ изменения логики, чтобы покрыть детерминированным
юнит-тестом: в диалоговом харнессе роутинг — слабый сигнал (определяется по
tool-событиям и шумит), поэтому решение тестируем напрямую. См. tests/test_routing.py.
"""
# Сильные индикаторы агентской задачи (работа с файлами/таблицами) → Claude.
AGENT_ACTIONS = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь файл", "открой файл",
"загруж", "прикреп", ".xlsx", ".xlsm", ".docx", ".pdf", ".csv",
"ячейк", "столбец d", "столбец e", "лист 15", "вкладк",
"заполни пункт", "сматчи", "сопостав", "извлеки",
]
# Сильные индикаторы нормативного вопроса → GLM.
REFERENCE_WORDS = [
"какой нр", "какой сп", "какая нр", "какая сп",
"коэффициент", "зимнее удорожан", "временные здани",
"расценк", "найди расценку", "найди норму",
"сметная цена", "цена материал",
"приказ ", "фснб", "методик",
"посчитай нр", "посчитай сп", "рассчитай",
"что ты умеешь", "помощь", "help",
]
def decide_engine(message: str, mentions_file: bool = False) -> str:
"""Вернуть 'claude' (агентный путь) или 'glm' (нормативка).
Логика идентична прежней inline-версии в main.py (поведение не меняется):
1) явный расчёт сметы → claude;
2) агентская задача без признаков нормативки → claude;
3) нормативка без признаков агента → glm;
4) и то и другое (ambiguous) → claude (агент сильнее);
5) иначе → glm.
mentions_file=True ставится вызывающим, когда в сообщении упомянут файл из
рабочего каталога пользователя.
"""
msg_lower = message.lower()
is_agent = mentions_file or any(kw in msg_lower for kw in AGENT_ACTIONS)
is_reference = any(kw in msg_lower for kw in REFERENCE_WORDS)
is_smeta_calc = (
(("смет" in msg_lower or "стоимост" in msg_lower)
and any(k in msg_lower for k in ("посчита", "рассчита", "составь",
"сделай смет", "построй смет")))
or ("смета на" in msg_lower or "смету на" in msg_lower))
if is_smeta_calc:
return "claude"
if is_agent and not is_reference:
return "claude"
if is_reference and not is_agent:
return "glm"
if is_agent and is_reference:
return "claude"
return "glm"
+58
View File
@@ -0,0 +1,58 @@
"""Детерминированный тест гибридного роутера (routing.decide_engine).
Роутинг — слабый сигнал в диалоговом харнессе (определяется по tool-событиям и
шумит), поэтому решение «GLM vs Claude» тестируем напрямую на реальных примерах
из корпуса пользовательских вопросов. Mutation: сломай ветку в decide_engine —
соответствующий тест упадёт.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from routing import decide_engine
def test_normative_questions_go_to_glm():
cases = [
"Какой процент НР для железнодорожного строительства?",
"Какой коэффициент стеснённых условий в населённых пунктах при строительстве?",
"Какой индекс пересчёта для Московской области на 1 квартал 2026?",
"Какая зона зимнего удорожания для Ленинградской области?",
"Какой максимальный резерв на непредвиденные для производственных объектов?",
"Посчитай НР и СП для земляных работ механизированным способом при ФОТ 500 000 руб",
"что ты умеешь",
]
for c in cases:
assert decide_engine(c, mentions_file=False) == "glm", c
def test_smeta_calc_goes_to_claude():
cases = [
"Посчитай смету: устройство бетонной подготовки 50 м3, армирование 2 т",
"составь смету на туалет",
"построй смету на дождевую канализацию",
]
for c in cases:
assert decide_engine(c, mentions_file=False) == "claude", c
def test_agent_actions_go_to_claude():
cases = [
"Открой файл и покажи итоги",
"Создай файл сметы по этим данным",
"Проанализируй вкладку 15.СМ файла РеестрСМ.xlsm",
"заполни пункт 5 в реестре",
]
for c in cases:
assert decide_engine(c, mentions_file=False) == "claude", c
def test_named_file_mention_goes_to_claude():
# mentions_file ставит вызывающий, когда имя файла из work_dir встречено в тексте
assert decide_engine("из ЛС-01 взять стоимость строительных работ", mentions_file=True) == "claude"
def test_ambiguous_prefers_claude():
# reference (коэффициент) + agent (открой файл) → агент сильнее
assert decide_engine("открой файл и скажи коэффициент стеснённых условий",
mentions_file=False) == "claude"