- 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>
216 lines
6.6 KiB
Python
216 lines
6.6 KiB
Python
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
|
|
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
|
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from auth import authenticate, verify_token
|
|
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")
|
|
|
|
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
|
MAX_MESSAGE_LEN = 10_000
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup():
|
|
init_db()
|
|
|
|
|
|
def _get_user(request: Request) -> str:
|
|
auth = request.headers.get("authorization", "")
|
|
token = auth.removeprefix("Bearer ").strip()
|
|
if not token:
|
|
raise HTTPException(401, "No token")
|
|
user = verify_token(token)
|
|
if not user:
|
|
raise HTTPException(401, "Invalid token")
|
|
return user
|
|
|
|
|
|
def _get_tab(request: Request, body: dict | None = None) -> str:
|
|
if body and "tab_id" in body:
|
|
return body["tab_id"]
|
|
return request.headers.get("x-tab-id", "default")
|
|
|
|
|
|
@app.get("/", response_class=HTMLResponse)
|
|
async def index():
|
|
return Path("static/chat.html").read_text(encoding="utf-8")
|
|
|
|
|
|
@app.post("/api/login")
|
|
async def login(request: Request):
|
|
body = await request.json()
|
|
username = body.get("username", "")
|
|
password = body.get("password", "")
|
|
client_ip = request.client.host if request.client else ""
|
|
token = authenticate(username, password, client_ip)
|
|
if not token:
|
|
raise HTTPException(401, "Wrong credentials")
|
|
return {"token": token, "username": username}
|
|
|
|
|
|
async def _stream_and_save(message: str, user: str, tab_id: str):
|
|
"""Wrap stream_claude to save messages to DB."""
|
|
save_message(user, tab_id, "user", message)
|
|
full_response = ""
|
|
async for chunk in stream_claude(message, user, tab_id):
|
|
yield chunk
|
|
# Collect text for saving
|
|
if "event: text" in chunk:
|
|
import json
|
|
for line in chunk.split("\n"):
|
|
if line.startswith("data: "):
|
|
try:
|
|
d = json.loads(line[6:])
|
|
full_response += d.get("text", "")
|
|
except Exception:
|
|
pass
|
|
elif "event: done" in chunk:
|
|
import json
|
|
for line in chunk.split("\n"):
|
|
if line.startswith("data: "):
|
|
try:
|
|
d = json.loads(line[6:])
|
|
if not full_response and d.get("result"):
|
|
full_response = d["result"]
|
|
except Exception:
|
|
pass
|
|
if full_response:
|
|
save_message(user, tab_id, "assistant", full_response)
|
|
|
|
|
|
@app.post("/api/chat")
|
|
async def chat(request: Request):
|
|
user = _get_user(request)
|
|
body = await request.json()
|
|
message = body.get("message", "").strip()
|
|
tab_id = _get_tab(request, body)
|
|
if not message:
|
|
raise HTTPException(400, "Empty message")
|
|
if len(message) > MAX_MESSAGE_LEN:
|
|
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
|
|
|
|
return StreamingResponse(
|
|
_stream_and_save(message, user, tab_id),
|
|
media_type="text/event-stream",
|
|
headers={
|
|
"Cache-Control": "no-cache",
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
)
|
|
|
|
|
|
@app.get("/api/history")
|
|
async def history(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
return get_history(user, tab_id)
|
|
|
|
|
|
@app.get("/api/sessions")
|
|
async def sessions(request: Request):
|
|
user = _get_user(request)
|
|
return list_sessions(user)
|
|
|
|
|
|
@app.post("/api/upload")
|
|
async def upload(request: Request, file: UploadFile):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
work_dir = get_work_dir(user, tab_id)
|
|
|
|
safe_name = Path(file.filename).name
|
|
if not safe_name or safe_name.startswith("."):
|
|
raise HTTPException(400, "Invalid filename")
|
|
|
|
if not is_allowed_file(safe_name):
|
|
raise HTTPException(
|
|
400,
|
|
f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml",
|
|
)
|
|
|
|
chunks = []
|
|
total = 0
|
|
while True:
|
|
chunk = await file.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
total += len(chunk)
|
|
if total > MAX_UPLOAD_SIZE:
|
|
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
|
|
chunks.append(chunk)
|
|
|
|
dest = work_dir / safe_name
|
|
dest.write_bytes(b"".join(chunks))
|
|
save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)")
|
|
return {"filename": safe_name, "size": total}
|
|
|
|
|
|
@app.get("/api/files")
|
|
async def files(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
return list_user_files(user, tab_id)
|
|
|
|
|
|
@app.get("/api/files/{filename}")
|
|
async def download_file(filename: str, request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
safe_name = Path(filename).name
|
|
fpath = get_work_dir(user, tab_id) / safe_name
|
|
if not fpath.exists() or not fpath.is_file():
|
|
raise HTTPException(404, "File not found")
|
|
return FileResponse(fpath, filename=filename)
|
|
|
|
|
|
@app.post("/api/reset")
|
|
async def reset_session(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
clear_session(user, tab_id)
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.post("/api/clear-files")
|
|
async def clear_files(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
work_dir = get_work_dir(user, tab_id)
|
|
for f in work_dir.iterdir():
|
|
if f.name.startswith("."):
|
|
continue
|
|
if f.is_file():
|
|
f.unlink()
|
|
elif f.is_dir():
|
|
shutil.rmtree(f)
|
|
clear_session(user, tab_id)
|
|
return {"status": "ok"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|