Spaces:
Sleeping
Sleeping
Update server.py
Browse files
server.py
CHANGED
|
@@ -9,18 +9,16 @@ from fastapi import FastAPI, HTTPException
|
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from fastapi.responses import StreamingResponse
|
| 11 |
from pydantic import BaseModel
|
| 12 |
-
from huggingface_hub import
|
| 13 |
-
from llama_cpp import Llama
|
| 14 |
|
| 15 |
# --- Configuration ---
|
| 16 |
-
# שימוש ב
|
| 17 |
-
|
| 18 |
-
FILENAME = "qwen2.5-1.5b-instruct-q4_k_m.gguf" # גרסה מכווצת ומהירה
|
| 19 |
-
|
| 20 |
PORT = int(os.environ.get("PORT", 8000))
|
| 21 |
HOST = "0.0.0.0"
|
| 22 |
DB_FILE = "chatbot.db"
|
| 23 |
JSON_SOURCE = "database.json"
|
|
|
|
| 24 |
|
| 25 |
logging.basicConfig(level=logging.INFO)
|
| 26 |
logger = logging.getLogger(__name__)
|
|
@@ -35,8 +33,8 @@ app.add_middleware(
|
|
| 35 |
allow_headers=["*"],
|
| 36 |
)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
|
| 41 |
# --- מילון מונחים לחיפוש ---
|
| 42 |
SEARCH_MAP = {
|
|
@@ -50,15 +48,11 @@ SEARCH_MAP = {
|
|
| 50 |
}
|
| 51 |
|
| 52 |
def init_db():
|
| 53 |
-
# הערה: הסרתי את המחיקה האוטומטית כדי שאם תמצא שרת עם דיסק קבוע, ההיסטוריה תישמר
|
| 54 |
-
# if os.path.exists(DB_FILE): os.remove(DB_FILE)
|
| 55 |
-
|
| 56 |
conn = sqlite3.connect(DB_FILE)
|
| 57 |
cursor = conn.cursor()
|
| 58 |
cursor.execute('CREATE TABLE IF NOT EXISTS knowledge (id INTEGER PRIMARY KEY, topic TEXT, content TEXT)')
|
| 59 |
cursor.execute('CREATE TABLE IF NOT EXISTS history (id INTEGER PRIMARY KEY, role TEXT, content TEXT)')
|
| 60 |
|
| 61 |
-
# טעינת המידע מקובץ ה-JSON אם הטבלה ריקה
|
| 62 |
cursor.execute('SELECT count(*) FROM knowledge')
|
| 63 |
if cursor.fetchone()[0] == 0 and os.path.exists(JSON_SOURCE):
|
| 64 |
try:
|
|
@@ -165,93 +159,73 @@ class ChatCompletionRequest(BaseModel):
|
|
| 165 |
|
| 166 |
@app.on_event("startup")
|
| 167 |
async def startup_event():
|
| 168 |
-
global llm
|
| 169 |
init_db()
|
| 170 |
-
logger.info(
|
| 171 |
-
try:
|
| 172 |
-
# הורדת המודל המכווץ מ-HuggingFace
|
| 173 |
-
model_path = hf_hub_download(
|
| 174 |
-
repo_id=REPO_ID,
|
| 175 |
-
filename=FILENAME
|
| 176 |
-
)
|
| 177 |
-
logger.info(f"🚀 Loading Llama model from {model_path}...")
|
| 178 |
-
|
| 179 |
-
# טעינת המודל לזיכרון (מותאם ל-CPU)
|
| 180 |
-
llm = Llama(
|
| 181 |
-
model_path=model_path,
|
| 182 |
-
n_ctx=4096, # אורך הקונטקסט (כמות הטקסט שהמודל זוכר)
|
| 183 |
-
n_threads=2, # מספר הליבות לשימוש (מותאם ל-HF Free Tier)
|
| 184 |
-
verbose=False
|
| 185 |
-
)
|
| 186 |
-
logger.info("✅ Model loaded successfully!")
|
| 187 |
-
except Exception as e:
|
| 188 |
-
logger.error(f"❌ Load failed: {e}")
|
| 189 |
-
raise RuntimeError("Model failed to load")
|
| 190 |
|
| 191 |
@app.post("/v1/chat/completions")
|
| 192 |
async def chat_completions(request: ChatCompletionRequest):
|
| 193 |
-
if not llm: raise HTTPException(503, "Model is loading...")
|
| 194 |
-
|
| 195 |
last_user_msg = next((m for m in reversed(request.messages) if m.role == "user"), None)
|
| 196 |
|
| 197 |
-
# שליפת מידע מהמסד
|
| 198 |
context = ""
|
| 199 |
if last_user_msg:
|
| 200 |
save_message("user", last_user_msg.content)
|
| 201 |
context = query_knowledge_base(last_user_msg.content)
|
| 202 |
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
if context:
|
| 205 |
-
sys_msg =
|
| 206 |
-
"תפקידך: טכנאי מומחה לפרויקט 'בית חכם תלם'.\n"
|
| 207 |
-
"הנחיות:\n"
|
| 208 |
-
"1. דבר בעברית טבעית בלבד.\n"
|
| 209 |
-
"2. השתמש במידע הטכני המצורף כדי לענות.\n"
|
| 210 |
-
"3. אם יש שרטוט, הצג אותו בצורה ברורה.\n"
|
| 211 |
-
f"\nמידע טכני רלוונטי:\n{context}"
|
| 212 |
-
)
|
| 213 |
else:
|
| 214 |
-
sys_msg = "א
|
| 215 |
|
| 216 |
-
# עדכון הודעת המערכת ברשימת ההודעות
|
| 217 |
messages_payload = [msg.dict() for msg in request.messages]
|
| 218 |
if messages_payload[0]['role'] == 'system':
|
| 219 |
messages_payload[0]['content'] = sys_msg
|
| 220 |
else:
|
| 221 |
messages_payload.insert(0, {"role": "system", "content": sys_msg})
|
| 222 |
|
| 223 |
-
# הרצת המודל
|
| 224 |
-
try:
|
| 225 |
-
# שימוש בפונקציה המובנית של Llama לניהול שיחה
|
| 226 |
-
response_iter = llm.create_chat_completion(
|
| 227 |
-
messages=messages_payload,
|
| 228 |
-
max_tokens=request.max_tokens,
|
| 229 |
-
temperature=request.temperature,
|
| 230 |
-
stream=request.stream
|
| 231 |
-
)
|
| 232 |
-
except Exception as e:
|
| 233 |
-
logger.error(f"Generation error: {e}")
|
| 234 |
-
raise HTTPException(500, str(e))
|
| 235 |
-
|
| 236 |
-
# טיפול ב-Streaming
|
| 237 |
if request.stream:
|
| 238 |
async def stream_generator():
|
| 239 |
full_text = ""
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
return StreamingResponse(stream_generator(), media_type="text/event-stream; charset=utf-8")
|
| 251 |
|
| 252 |
-
#
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
if __name__ == "__main__":
|
| 257 |
uvicorn.run("server:app", host=HOST, port=PORT, reload=False)
|
|
|
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from fastapi.responses import StreamingResponse
|
| 11 |
from pydantic import BaseModel
|
| 12 |
+
from huggingface_hub import InferenceClient
|
|
|
|
| 13 |
|
| 14 |
# --- Configuration ---
|
| 15 |
+
# שימוש ב-API של Hugging Face במקום הרצה מקומית
|
| 16 |
+
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
|
|
|
|
|
|
|
| 17 |
PORT = int(os.environ.get("PORT", 8000))
|
| 18 |
HOST = "0.0.0.0"
|
| 19 |
DB_FILE = "chatbot.db"
|
| 20 |
JSON_SOURCE = "database.json"
|
| 21 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # הטוקן שלך
|
| 22 |
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
logger = logging.getLogger(__name__)
|
|
|
|
| 33 |
allow_headers=["*"],
|
| 34 |
)
|
| 35 |
|
| 36 |
+
# לקוח ה-API
|
| 37 |
+
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
|
| 38 |
|
| 39 |
# --- מילון מונחים לחיפוש ---
|
| 40 |
SEARCH_MAP = {
|
|
|
|
| 48 |
}
|
| 49 |
|
| 50 |
def init_db():
|
|
|
|
|
|
|
|
|
|
| 51 |
conn = sqlite3.connect(DB_FILE)
|
| 52 |
cursor = conn.cursor()
|
| 53 |
cursor.execute('CREATE TABLE IF NOT EXISTS knowledge (id INTEGER PRIMARY KEY, topic TEXT, content TEXT)')
|
| 54 |
cursor.execute('CREATE TABLE IF NOT EXISTS history (id INTEGER PRIMARY KEY, role TEXT, content TEXT)')
|
| 55 |
|
|
|
|
| 56 |
cursor.execute('SELECT count(*) FROM knowledge')
|
| 57 |
if cursor.fetchone()[0] == 0 and os.path.exists(JSON_SOURCE):
|
| 58 |
try:
|
|
|
|
| 159 |
|
| 160 |
@app.on_event("startup")
|
| 161 |
async def startup_event():
|
|
|
|
| 162 |
init_db()
|
| 163 |
+
logger.info("✅ Server started in API Mode")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
@app.post("/v1/chat/completions")
|
| 166 |
async def chat_completions(request: ChatCompletionRequest):
|
|
|
|
|
|
|
| 167 |
last_user_msg = next((m for m in reversed(request.messages) if m.role == "user"), None)
|
| 168 |
|
|
|
|
| 169 |
context = ""
|
| 170 |
if last_user_msg:
|
| 171 |
save_message("user", last_user_msg.content)
|
| 172 |
context = query_knowledge_base(last_user_msg.content)
|
| 173 |
|
| 174 |
+
sys_msg = (
|
| 175 |
+
"תפקידך: טכנאי מומחה לפרויקט 'בית חכם תלם'.\n"
|
| 176 |
+
"הנחיות:\n"
|
| 177 |
+
"1. דבר בעברית טבעית בלבד.\n"
|
| 178 |
+
"2. השתמש במידע הטכני המצורף כדי לענות.\n"
|
| 179 |
+
"3. אם יש שרטוט, הצג אותו בצורה ברורה.\n"
|
| 180 |
+
)
|
| 181 |
if context:
|
| 182 |
+
sys_msg += f"\nמידע טכני רלוונטי:\n{context}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
else:
|
| 184 |
+
sys_msg += "\n(לא נמצא מידע ספציפי במערכת, ענה מהידע הכללי שלך אך סייג את דבריך)."
|
| 185 |
|
|
|
|
| 186 |
messages_payload = [msg.dict() for msg in request.messages]
|
| 187 |
if messages_payload[0]['role'] == 'system':
|
| 188 |
messages_payload[0]['content'] = sys_msg
|
| 189 |
else:
|
| 190 |
messages_payload.insert(0, {"role": "system", "content": sys_msg})
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
if request.stream:
|
| 193 |
async def stream_generator():
|
| 194 |
full_text = ""
|
| 195 |
+
try:
|
| 196 |
+
# קריאה ל-API של Hugging Face
|
| 197 |
+
for chunk in client.chat_completion(
|
| 198 |
+
messages=messages_payload,
|
| 199 |
+
max_tokens=request.max_tokens,
|
| 200 |
+
temperature=request.temperature,
|
| 201 |
+
stream=True
|
| 202 |
+
):
|
| 203 |
+
delta = chunk.choices[0].delta.content
|
| 204 |
+
if delta:
|
| 205 |
+
full_text += delta
|
| 206 |
+
yield f"data: {json.dumps({'choices': [{'delta': {'content': delta}}]}, ensure_ascii=False)}\n\n"
|
| 207 |
+
save_message("assistant", full_text)
|
| 208 |
+
yield "data: [DONE]\n\n"
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.error(f"API Error: {e}")
|
| 211 |
+
yield f"data: {json.dumps({'error': str(e)})}\n\n"
|
| 212 |
|
| 213 |
return StreamingResponse(stream_generator(), media_type="text/event-stream; charset=utf-8")
|
| 214 |
|
| 215 |
+
# מצב ללא סטרימינג
|
| 216 |
+
try:
|
| 217 |
+
response = client.chat_completion(
|
| 218 |
+
messages=messages_payload,
|
| 219 |
+
max_tokens=request.max_tokens,
|
| 220 |
+
temperature=request.temperature,
|
| 221 |
+
stream=False
|
| 222 |
+
)
|
| 223 |
+
content = response.choices[0].message.content
|
| 224 |
+
save_message("assistant", content)
|
| 225 |
+
return response
|
| 226 |
+
except Exception as e:
|
| 227 |
+
logger.error(f"API Error: {e}")
|
| 228 |
+
raise HTTPException(500, f"Hugging Face API Error: {str(e)}")
|
| 229 |
|
| 230 |
if __name__ == "__main__":
|
| 231 |
uvicorn.run("server:app", host=HOST, port=PORT, reload=False)
|