Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import urllib.request
|
| 2 |
+
import os
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from llama_cpp import Llama
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
|
| 8 |
+
MODEL_URL = "VOTRE_LIEN_DE_TELECHARGEMENT_DIRECT"
|
| 9 |
+
MODEL_PATH = "Phi-3-mini-4k-instruct-q4.gguf"
|
| 10 |
+
|
| 11 |
+
print("Vérification et téléchargement du modèle sur le serveur cloud...")
|
| 12 |
+
if not os.path.exists(MODEL_PATH):
|
| 13 |
+
print("Téléchargement des 2 Go en cours (depuis le réseau du cloud)...")
|
| 14 |
+
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
|
| 15 |
+
print("Téléchargement terminé !")
|
| 16 |
+
else:
|
| 17 |
+
print("Le modèle est déjà présent sur le serveur.")
|
| 18 |
+
|
| 19 |
+
app = FastAPI()
|
| 20 |
+
|
| 21 |
+
app.add_middleware(
|
| 22 |
+
CORSMiddleware,
|
| 23 |
+
allow_origins=["*"],
|
| 24 |
+
allow_credentials=True,
|
| 25 |
+
allow_methods=["*"],
|
| 26 |
+
allow_headers=["*"],
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
llm = Llama(model_path=MODEL_PATH, n_ctx=2048, n_threads=2)
|
| 31 |
+
print("Modèle chargé en mémoire avec succès.")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print("Erreur lors du chargement du modèle :", e)
|
| 34 |
+
|
| 35 |
+
class ChatRequest(BaseModel):
|
| 36 |
+
message: str
|
| 37 |
+
history: list = []
|
| 38 |
+
|
| 39 |
+
@app.post("/api/chat")
|
| 40 |
+
def chat_endpoint(req: ChatRequest):
|
| 41 |
+
prompt = (
|
| 42 |
+
"You are BEGA AI, a helpful AI assistant developed by BEGA Company. "
|
| 43 |
+
"Reply in the same language used in the user's message.\n\n"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
for human_msg, assistant_msg in req.history:
|
| 47 |
+
prompt += f"User: {human_msg}\nAssistant: {assistant_msg}\n"
|
| 48 |
+
|
| 49 |
+
prompt += f"User: {req.message}\nAssistant:"
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
output = llm(
|
| 53 |
+
prompt,
|
| 54 |
+
max_tokens=350,
|
| 55 |
+
stop=["User:", "\nUser:", "Assistant:", "\nAssistant:"],
|
| 56 |
+
temperature=0.3
|
| 57 |
+
)
|
| 58 |
+
reply = output['choices'][0]['text'].strip()
|
| 59 |
+
return {"response": reply}
|
| 60 |
+
except Exception as e:
|
| 61 |
+
raise HTTPException(status_code=500, detail=str(e))
|