Rid3 commited on
Commit
599a0f5
·
verified ·
1 Parent(s): 5c6c743

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -29
app.py CHANGED
@@ -21,11 +21,10 @@ REPO_ID = "Rid3/xtime-v1beta-gguf-storage"
21
  current_llm = None
22
  current_model_name = ""
23
 
24
- # Модели из твоего репозитория
25
  MODELS = {
26
- "medium": "xtime-v1beta-n-m_1p.gguf", # 2.8 ГБ — самая стабильная
27
- "large": "xtime-v1beta-q4_K_M.gguf", # 5.9 ГБ — тяжёлая (пока не используем)
28
- "small": "xtime-v1beta-xp-r_2.gguf" # очень лёгкая
29
  }
30
 
31
  def load_model(model_key: str):
@@ -48,55 +47,54 @@ def load_model(model_key: str):
48
 
49
  current_llm = Llama(
50
  model_path=model_path,
51
- n_ctx=2048, # уменьшено для стабильности
52
  n_threads=os.cpu_count() or 4,
53
- n_gpu_layers=0, # только CPU
54
- verbose=True,
55
- chat_format="llama-3"
56
  )
57
  current_model_name = model_key
58
- print(f"✅ Успешно загружена модель: {model_key}")
59
  except Exception as e:
60
- print(f"❌ Ошибка загрузки модели {model_key}: {e}")
61
- raise HTTPException(status_code=500, detail=f"Не удалось загрузить модель: {str(e)}")
62
 
63
 
64
  @app.on_event("startup")
65
  async def startup_event():
66
- # Загружаем medium по умолчанию — она работает стабильно
67
- load_model("medium")
68
 
69
 
70
  class ChatRequest(BaseModel):
71
  prompt: str
72
- model_type: str = "medium" # по умолчанию medium
73
- api_key: str = "" # пока можно пустой, позже добавим проверку
74
 
75
 
76
  @app.post("/chat")
77
  async def chat(request: ChatRequest):
78
- # Если пользователь попросил другую модель — пытаемся загрузить
79
  if request.model_type != current_model_name:
80
  load_model(request.model_type)
81
 
82
  try:
83
- output = current_llm.create_chat_completion(
84
- messages=[
85
- {"role": "system", "content": "Ты полезный и дружелюбный помощник."},
86
- {"role": "user", "content": request.prompt}
87
- ],
88
  max_tokens=512,
89
- temperature=0.7
 
90
  )
91
- return {"response": output["choices"][0]["message"]["content"].strip()}
 
 
 
92
  except Exception as e:
93
- raise HTTPException(status_code=500, detail=str(e))
 
94
 
95
 
96
  @app.get("/")
97
  async def health():
98
- return {
99
- "status": "online",
100
- "current_model": current_model_name,
101
- "available_models": list(MODELS.keys())
102
- }
 
21
  current_llm = None
22
  current_model_name = ""
23
 
 
24
  MODELS = {
25
+ "medium": "xtime-v1beta-n-m_1p.gguf",
26
+ "small": "xtime-v1beta-xp-r_2.gguf",
27
+ "large": "xtime-v1beta-q4_K_M.gguf"
28
  }
29
 
30
  def load_model(model_key: str):
 
47
 
48
  current_llm = Llama(
49
  model_path=model_path,
50
+ n_ctx=2048,
51
  n_threads=os.cpu_count() or 4,
52
+ n_gpu_layers=0,
53
+ verbose=False,
54
+ chat_format=None # важно! для Phi-2 не используем llama-3
55
  )
56
  current_model_name = model_key
57
+ print(f"✅ Модель {model_key} успешно загружена")
58
  except Exception as e:
59
+ print(f"❌ Ошибка загрузки {model_key}: {e}")
60
+ raise HTTPException(status_code=500, detail=str(e))
61
 
62
 
63
  @app.on_event("startup")
64
  async def startup_event():
65
+ load_model("medium") # по умолчанию самая стабильная
 
66
 
67
 
68
  class ChatRequest(BaseModel):
69
  prompt: str
70
+ model_type: str = "medium"
71
+ api_key: str = ""
72
 
73
 
74
  @app.post("/chat")
75
  async def chat(request: ChatRequest):
 
76
  if request.model_type != current_model_name:
77
  load_model(request.model_type)
78
 
79
  try:
80
+ # Для Phi-2 лучше использовать обычный create_completion
81
+ prompt = f"User: {request.prompt}\nAssistant:"
82
+
83
+ output = current_llm.create_completion(
84
+ prompt=prompt,
85
  max_tokens=512,
86
+ temperature=0.7,
87
+ stop=["User:", "<|endoftext|>"]
88
  )
89
+
90
+ response_text = output["choices"][0]["text"].strip()
91
+ return {"response": response_text}
92
+
93
  except Exception as e:
94
+ print(f"Ошибка при генерации: {e}")
95
+ raise HTTPException(status_code=500, detail="Ошибка генерации ответа")
96
 
97
 
98
  @app.get("/")
99
  async def health():
100
+ return {"status": "online", "model": current_model_name}