Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -2,12 +2,13 @@ import os
|
|
| 2 |
import httpx
|
| 3 |
import json
|
| 4 |
from fastapi import FastAPI, Request, HTTPException
|
| 5 |
-
from fastapi.responses import StreamingResponse
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
from qdrant_client import QdrantClient
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
allow_origins=["*"],
|
|
@@ -18,7 +19,7 @@ app.add_middleware(
|
|
| 18 |
|
| 19 |
COLLECTION_NAME = "equipment_registry"
|
| 20 |
|
| 21 |
-
# Функция для эмбеддингов
|
| 22 |
async def get_openrouter_embedding(text: str, api_key: str):
|
| 23 |
async with httpx.AsyncClient() as client:
|
| 24 |
payload = {
|
|
@@ -34,33 +35,34 @@ async def get_openrouter_embedding(text: str, api_key: str):
|
|
| 34 |
|
| 35 |
@app.post("/api/chat")
|
| 36 |
async def chat(request: Request):
|
| 37 |
-
# П
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
try:
|
| 43 |
body = await request.json()
|
| 44 |
messages = body.get("messages", [])
|
| 45 |
if not messages:
|
| 46 |
return JSONResponse(content={"error": "No messages"}, status_code=400)
|
| 47 |
-
|
| 48 |
user_query = messages[-1].get("content", "")
|
| 49 |
|
| 50 |
# 1. Поиск в Qdrant
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
q_client = QdrantClient(url=Q_URL, api_key=Q_KEY)
|
| 55 |
search_results = q_client.search(
|
| 56 |
collection_name=COLLECTION_NAME,
|
| 57 |
query_vector=vector,
|
| 58 |
limit=5
|
| 59 |
)
|
| 60 |
-
|
| 61 |
-
# Собираем контекст из search_text, который ты загрузил в базу
|
| 62 |
context = "\n\n".join([res.payload.get("search_text", "") for res in search_results if res.payload])
|
| 63 |
-
|
| 64 |
system_prompt = (
|
| 65 |
"Ты — инженерный ИИ-ассистент по реестру научного оборудования. "
|
| 66 |
"Используй предоставленный контекст для точного ответа. "
|
|
@@ -68,7 +70,7 @@ async def chat(request: Request):
|
|
| 68 |
f"КОНТЕКСТ:\n{context}"
|
| 69 |
)
|
| 70 |
|
| 71 |
-
# 2.
|
| 72 |
async def generate():
|
| 73 |
payload = {
|
| 74 |
"model": "deepseek/deepseek-chat",
|
|
@@ -76,7 +78,7 @@ async def chat(request: Request):
|
|
| 76 |
"stream": True
|
| 77 |
}
|
| 78 |
headers = {
|
| 79 |
-
"Authorization": f"Bearer {
|
| 80 |
"Content-Type": "application/json",
|
| 81 |
"HTTP-Referer": "https://huggingface.co/",
|
| 82 |
"X-OpenRouter-Title": "Inventory Assistant"
|
|
@@ -86,7 +88,7 @@ async def chat(request: Request):
|
|
| 86 |
async with client.stream("POST", "https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload) as response:
|
| 87 |
if response.status_code != 200:
|
| 88 |
error_text = await response.aread()
|
| 89 |
-
yield f"
|
| 90 |
return
|
| 91 |
|
| 92 |
async for line in response.aiter_lines():
|
|
@@ -99,27 +101,22 @@ async def chat(request: Request):
|
|
| 99 |
|
| 100 |
try:
|
| 101 |
chunk = json.loads(data_str)
|
| 102 |
-
|
| 103 |
-
# ПРОВЕРКА: Если choices пуст или его нет, пропускаем чанк
|
| 104 |
if not chunk.get('choices'):
|
| 105 |
continue
|
| 106 |
|
| 107 |
-
|
| 108 |
-
content = delta.get('content', '')
|
| 109 |
-
|
| 110 |
if content:
|
|
|
|
| 111 |
yield content
|
| 112 |
-
except
|
| 113 |
-
# Если что-то пошло не так при парсинге чанка, просто идем к следующему
|
| 114 |
continue
|
| 115 |
|
| 116 |
-
# ВАЖНО: media_type="text/plain" и Cache-Control для Vercel AI SDK
|
| 117 |
return StreamingResponse(
|
| 118 |
generate(),
|
| 119 |
media_type="text/plain",
|
| 120 |
headers={
|
| 121 |
"Cache-Control": "no-cache",
|
| 122 |
-
"X-Accel-Buffering": "no" #
|
| 123 |
}
|
| 124 |
)
|
| 125 |
|
|
@@ -129,4 +126,6 @@ async def chat(request: Request):
|
|
| 129 |
|
| 130 |
@app.get("/")
|
| 131 |
async def health():
|
| 132 |
-
|
|
|
|
|
|
|
|
|
| 2 |
import httpx
|
| 3 |
import json
|
| 4 |
from fastapi import FastAPI, Request, HTTPException
|
| 5 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
from qdrant_client import QdrantClient
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
# 1. Настройка CORS
|
| 12 |
app.add_middleware(
|
| 13 |
CORSMiddleware,
|
| 14 |
allow_origins=["*"],
|
|
|
|
| 19 |
|
| 20 |
COLLECTION_NAME = "equipment_registry"
|
| 21 |
|
| 22 |
+
# Функция для эмбеддингов
|
| 23 |
async def get_openrouter_embedding(text: str, api_key: str):
|
| 24 |
async with httpx.AsyncClient() as client:
|
| 25 |
payload = {
|
|
|
|
| 35 |
|
| 36 |
@app.post("/api/chat")
|
| 37 |
async def chat(request: Request):
|
| 38 |
+
# ПРАВИЛЬНЫЕ ИМЕНА ИЗ ТВОИХ SECRETS
|
| 39 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 40 |
+
QDRANT_URL = os.getenv("QDRANT_URL")
|
| 41 |
+
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
|
| 42 |
+
|
| 43 |
+
if not OPENROUTER_API_KEY or not QDRANT_URL or not QDRANT_API_KEY:
|
| 44 |
+
return JSONResponse(content={"error": "Missing environment variables on HF Space"}, status_code=500)
|
| 45 |
|
| 46 |
try:
|
| 47 |
body = await request.json()
|
| 48 |
messages = body.get("messages", [])
|
| 49 |
if not messages:
|
| 50 |
return JSONResponse(content={"error": "No messages"}, status_code=400)
|
| 51 |
+
|
| 52 |
user_query = messages[-1].get("content", "")
|
| 53 |
|
| 54 |
# 1. Поиск в Qdrant
|
| 55 |
+
vector = await get_openrouter_embedding(user_query, OPENROUTER_API_KEY)
|
| 56 |
+
|
| 57 |
+
q_client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
|
|
|
|
| 58 |
search_results = q_client.search(
|
| 59 |
collection_name=COLLECTION_NAME,
|
| 60 |
query_vector=vector,
|
| 61 |
limit=5
|
| 62 |
)
|
| 63 |
+
|
|
|
|
| 64 |
context = "\n\n".join([res.payload.get("search_text", "") for res in search_results if res.payload])
|
| 65 |
+
|
| 66 |
system_prompt = (
|
| 67 |
"Ты — инженерный ИИ-ассистент по реестру научного оборудования. "
|
| 68 |
"Используй предоставленный контекст для точного ответа. "
|
|
|
|
| 70 |
f"КОНТЕКСТ:\n{context}"
|
| 71 |
)
|
| 72 |
|
| 73 |
+
# 2. Стриминг ответа (DeepSeek-V3 через OpenRouter)
|
| 74 |
async def generate():
|
| 75 |
payload = {
|
| 76 |
"model": "deepseek/deepseek-chat",
|
|
|
|
| 78 |
"stream": True
|
| 79 |
}
|
| 80 |
headers = {
|
| 81 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 82 |
"Content-Type": "application/json",
|
| 83 |
"HTTP-Referer": "https://huggingface.co/",
|
| 84 |
"X-OpenRouter-Title": "Inventory Assistant"
|
|
|
|
| 88 |
async with client.stream("POST", "https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload) as response:
|
| 89 |
if response.status_code != 200:
|
| 90 |
error_text = await response.aread()
|
| 91 |
+
yield f"OpenRouter Error: {error_text.decode()}"
|
| 92 |
return
|
| 93 |
|
| 94 |
async for line in response.aiter_lines():
|
|
|
|
| 101 |
|
| 102 |
try:
|
| 103 |
chunk = json.loads(data_str)
|
|
|
|
|
|
|
| 104 |
if not chunk.get('choices'):
|
| 105 |
continue
|
| 106 |
|
| 107 |
+
content = chunk['choices'][0].get('delta', {}).get('content', '')
|
|
|
|
|
|
|
| 108 |
if content:
|
| 109 |
+
# Отдаем чистый ��екст для useChat
|
| 110 |
yield content
|
| 111 |
+
except:
|
|
|
|
| 112 |
continue
|
| 113 |
|
|
|
|
| 114 |
return StreamingResponse(
|
| 115 |
generate(),
|
| 116 |
media_type="text/plain",
|
| 117 |
headers={
|
| 118 |
"Cache-Control": "no-cache",
|
| 119 |
+
"X-Accel-Buffering": "no" # Чтобы HF не тормозил поток
|
| 120 |
}
|
| 121 |
)
|
| 122 |
|
|
|
|
| 126 |
|
| 127 |
@app.get("/")
|
| 128 |
async def health():
|
| 129 |
+
# Проверка, видит ли сервер ключи
|
| 130 |
+
check = "OK" if os.getenv("OPENROUTER_API_KEY") else "MISSING"
|
| 131 |
+
return {"status": "running", "api_key": check}
|