74 lines
2.6 KiB
Python
74 lines
2.6 KiB
Python
import json
|
|
import urllib.request
|
|
from typing import List, Dict, Any, Optional
|
|
from fastapi import FastAPI, Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel
|
|
|
|
from llm.agent import process_chat_message
|
|
from llm.db_tools import db_get_tasks
|
|
|
|
API_TOKEN = "scud_secret_token_2026"
|
|
OLLAMA_URL = "http://192.168.11.3:11434/api/chat"
|
|
MODEL_NAME = "qwen2.5:14b"
|
|
|
|
security = HTTPBearer()
|
|
|
|
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
|
if credentials.credentials != API_TOKEN:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Неверный токен доступа",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return credentials.credentials
|
|
|
|
app = FastAPI(title="SCUD Orion AI Context API")
|
|
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
|
|
class ChatRequest(BaseModel):
|
|
session_id: str
|
|
message: str
|
|
|
|
@app.get("/")
|
|
def read_root():
|
|
return FileResponse("static/index.html")
|
|
|
|
@app.get("/api/v1/tasks")
|
|
def get_tasks(token: str = Depends(verify_token)):
|
|
return db_get_tasks()
|
|
|
|
@app.post("/api/v1/chat")
|
|
def chat_endpoint(req: ChatRequest, token: str = Depends(verify_token)):
|
|
reply, _ = process_chat_message(req.message)
|
|
return {"reply": reply}
|
|
|
|
# Эндпоинт для гостевого режима (без авторизации и без привязки к проекту)
|
|
@app.post("/api/v1/chat/guest")
|
|
def guest_chat_endpoint(req: ChatRequest):
|
|
payload = {
|
|
"model": MODEL_NAME,
|
|
"messages": [
|
|
{"role": "system", "content": "Ты — полезный ИИ-ассистент. Отвечай на вопросы пользователя четко и по существу."},
|
|
{"role": "user", "content": req.message}
|
|
],
|
|
"stream": False,
|
|
"options": {"num_predict": 2048, "temperature": 0.3}
|
|
}
|
|
|
|
try:
|
|
req_ollama = urllib.request.Request(
|
|
OLLAMA_URL,
|
|
data=json.dumps(payload).encode("utf-8"),
|
|
headers={"Content-Type": "application/json"}
|
|
)
|
|
with urllib.request.urlopen(req_ollama) as response:
|
|
res_data = json.loads(response.read().decode("utf-8"))
|
|
reply = res_data.get("message", {}).get("content", "").strip()
|
|
return {"reply": reply}
|
|
except Exception as e:
|
|
return {"reply": f"Ошибка связи с локальной нейросетью: {e}"}
|