feat: двойной бэкенд — Claude Code + GLM (переключаемый)
- AI_BACKEND=claude|glm в .env для переключения - claude_bridge_glm.py: GLM-5 + CAG context (НР/СП/коэффициенты в промпте) + text search по resources.json для расценок + streaming SSE, история диалогов - main.py: динамический импорт бэкенда по AI_BACKEND - GLM-бэкенд не требует Docker/sandbox — чистый Python - Нужен действующий ZAI_API_KEY (текущий — закончился баланс) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,208 @@
|
||||
"""GLM-5 + CAG/RAG backend — lightweight alternative to Claude Code.
|
||||
|
||||
Uses smeta-railway's CAG context (НР/СП/коэффициенты) as system prompt,
|
||||
resources.json for code lookups, GLM-5 API for generation.
|
||||
No Docker, no subprocess — pure Python, fast.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
import httpx
|
||||
|
||||
SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")))
|
||||
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
|
||||
ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/paas/v4")
|
||||
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-4-plus")
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
|
||||
# Session tracking: (username, tab_id) -> conversation history
|
||||
_conversations: dict[tuple[str, str], list[dict]] = {}
|
||||
MAX_HISTORY = 20 # keep last N messages
|
||||
|
||||
# Preload CAG context and resources
|
||||
_cag_context = ""
|
||||
_resources: dict = {}
|
||||
|
||||
|
||||
def _load_smeta_data():
|
||||
global _cag_context, _resources
|
||||
if _cag_context:
|
||||
return
|
||||
|
||||
# Load CAG context
|
||||
import sys
|
||||
sys.path.insert(0, str(SMETA_DIR / "src"))
|
||||
try:
|
||||
from smeta_railway.ai.cag_context import CAG_CONTEXT
|
||||
_cag_context = CAG_CONTEXT
|
||||
except ImportError:
|
||||
_cag_context = ""
|
||||
|
||||
# Load resources
|
||||
res_path = SMETA_DIR / "resources.json"
|
||||
if res_path.exists():
|
||||
with open(res_path, encoding="utf-8") as f:
|
||||
_resources = json.load(f)
|
||||
|
||||
|
||||
def _build_system_prompt() -> str:
|
||||
_load_smeta_data()
|
||||
return f"""Ты — профессиональный ИИ-ассистент-сметчик железнодорожного строительства.
|
||||
Отвечай ТОЛЬКО на русском языке. Пользователь — сметчик, НЕ программист.
|
||||
НИКОГДА не упоминай названия книг или учебников. Ссылайся только на нормативные документы.
|
||||
|
||||
Ниже — актуальная нормативная база. Используй ТОЛЬКО эти данные для ответов:
|
||||
|
||||
{_cag_context}
|
||||
|
||||
Если вопрос про конкретную расценку ГЭСН — скажи что проверишь по базе."""
|
||||
|
||||
|
||||
def _search_resources(query: str, top_k: int = 5) -> str:
|
||||
"""Simple text search in resources.json."""
|
||||
_load_smeta_data()
|
||||
if not _resources:
|
||||
return ""
|
||||
|
||||
query_lower = query.lower()
|
||||
terms = [t for t in query_lower.split() if len(t) > 2]
|
||||
results = []
|
||||
|
||||
for code, data in _resources.items():
|
||||
if "error" in data:
|
||||
continue
|
||||
name = (data.get("name") or data.get("norm_name") or "").lower()
|
||||
score = sum(1 for t in terms if t in name)
|
||||
if score > 0:
|
||||
results.append((score, code, data))
|
||||
|
||||
results.sort(reverse=True, key=lambda x: x[0])
|
||||
if not results:
|
||||
return ""
|
||||
|
||||
lines = ["Найденные расценки в базе ФСНБ-2022:"]
|
||||
for score, code, data in results[:top_k]:
|
||||
name = data.get("name") or data.get("norm_name") or ""
|
||||
unit = data.get("unit") or ""
|
||||
lines.append(f"- ГЭСН {code}: {name} [{unit}]")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
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 None # GLM doesn't use session IDs
|
||||
|
||||
|
||||
def set_session_id(username: str, tab_id: str, sid: str):
|
||||
pass
|
||||
|
||||
|
||||
def clear_session(username: str, tab_id: str):
|
||||
_conversations.pop((username, tab_id), None)
|
||||
|
||||
|
||||
ALLOWED_EXTENSIONS = {
|
||||
".xlsx", ".xls", ".docx", ".doc", ".pdf",
|
||||
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
|
||||
}
|
||||
|
||||
|
||||
def is_allowed_file(filename: str) -> bool:
|
||||
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
message: str,
|
||||
username: str,
|
||||
tab_id: str = "default",
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Stream GLM-5 response with CAG context."""
|
||||
_load_smeta_data()
|
||||
key = (username, tab_id)
|
||||
|
||||
# Build conversation history
|
||||
if key not in _conversations:
|
||||
_conversations[key] = []
|
||||
history = _conversations[key]
|
||||
|
||||
# Search resources if question looks like a GESN lookup
|
||||
resource_context = ""
|
||||
gesn_patterns = ["расценк", "гэсн", "норм", "28-", "01-", "единиц"]
|
||||
if any(p in message.lower() for p in gesn_patterns):
|
||||
resource_context = _search_resources(message)
|
||||
|
||||
# Build user message with context
|
||||
user_content = message
|
||||
if resource_context:
|
||||
user_content = f"{message}\n\n[Данные из базы ФСНБ-2022]\n{resource_context}"
|
||||
|
||||
history.append({"role": "user", "content": user_content})
|
||||
|
||||
# Trim history
|
||||
if len(history) > MAX_HISTORY:
|
||||
history[:] = history[-MAX_HISTORY:]
|
||||
|
||||
# Prepare messages
|
||||
messages = [{"role": "system", "content": _build_system_prompt()}] + history
|
||||
|
||||
# Stream from GLM API
|
||||
full_response = ""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
resp = await client.post(
|
||||
f"{ZAI_BASE_URL}/chat/completions",
|
||||
headers={"Authorization": f"Bearer {ZAI_API_KEY}"},
|
||||
json={
|
||||
"model": ZAI_MODEL,
|
||||
"messages": messages,
|
||||
"stream": True,
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: "):
|
||||
continue
|
||||
data_str = line[6:]
|
||||
if data_str == "[DONE]":
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data_str)
|
||||
delta = chunk["choices"][0].get("delta", {})
|
||||
text = delta.get("content", "")
|
||||
if text:
|
||||
full_response += text
|
||||
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
|
||||
except (json.JSONDecodeError, KeyError, IndexError):
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Ошибка GLM API: {e}"
|
||||
yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n"
|
||||
full_response = error_msg
|
||||
|
||||
# Save assistant response to history
|
||||
if full_response:
|
||||
history.append({"role": "assistant", "content": full_response})
|
||||
|
||||
yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
|
||||
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
|
||||
@@ -1,4 +1,4 @@
|
||||
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code."""
|
||||
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
@@ -9,15 +9,22 @@ from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from auth import authenticate, verify_token
|
||||
from claude_bridge import (
|
||||
clear_session,
|
||||
get_work_dir,
|
||||
is_allowed_file,
|
||||
list_user_files,
|
||||
stream_claude,
|
||||
)
|
||||
from db import get_history, init_db, list_sessions, save_message
|
||||
|
||||
# Backend selection: "claude" (Docker sandbox) or "glm" (GLM-5 + CAG/RAG)
|
||||
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
|
||||
|
||||
if AI_BACKEND == "glm":
|
||||
from claude_bridge_glm import (
|
||||
clear_session, get_work_dir, is_allowed_file,
|
||||
list_user_files, stream_claude,
|
||||
)
|
||||
else:
|
||||
from claude_bridge import (
|
||||
clear_session, get_work_dir, is_allowed_file,
|
||||
list_user_files, stream_claude,
|
||||
)
|
||||
|
||||
app = FastAPI(title="smeta-web")
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user