File size: 2,443 Bytes
db8d405 4ec65b6 db8d405 3d27120 7ae75f5 db8d405 3d27120 4ec65b6 3d27120 7ae75f5 3d27120 db8d405 3d27120 db8d405 3d27120 db8d405 9ad539d 7ae75f5 9ad539d db8d405 7ae75f5 3d27120 7ae75f5 db8d405 3d27120 db8d405 7ae75f5 3d27120 7ae75f5 3d27120 7ae75f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import os
import urllib.request
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from llama_cpp import Llama
from fastapi.middleware.cors import CORSMiddleware
# On garde votre Llama-3.1 8B ultra-léger (Q2_K ou IQ3_XS)
MODEL_URL = "https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3-8B-Instruct-IQ3_XS.gguf"
MODEL_PATH = "llama-3.1-8B-Q2_K.gguf"
print("--- Vérification / Téléchargement de Llama 3.1 8B ---")
if not os.path.exists(MODEL_PATH):
print("Téléchargement du modèle (veuillez patienter quelques minutes)...")
try:
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
print("Téléchargement réussi !")
except Exception as e:
print(f"Erreur téléchargement : {e}")
else:
print("Modèle Llama 3.1 8B détecté sur le disque.")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
print("--- Chargement en mémoire (CPU) ---")
# n_ctx=256 : Contexte très bas pour forcer Llama 8B à rentrer dans la petite RAM du serveur gratuit
llm = Llama(model_path=MODEL_PATH, n_ctx=256, n_threads=2)
print("Moteur Llama 3.1 8B opérationnel !")
class ChatRequest(BaseModel):
message: str
history: list = []
@app.get("/")
def root_check():
return {"status": "BEGA AI API is running with Llama-3.1-8B"}
@app.post("/api/chat")
def chat_endpoint(req: ChatRequest):
global llm
if llm is None:
raise HTTPException(status_code=500, detail="Modèle non chargé.")
prompt = (
"You are BEGA AI, a helpful AI assistant developed by BEGA Company. "
"Reply concisely in the same language used in the user's message.\n\n"
)
for human_msg, assistant_msg in req.history:
prompt += f"User: {human_msg}\nAssistant: {assistant_msg}\n"
prompt += f"User: {req.message}\nAssistant:"
try:
# max_tokens=50 : On demande une réponse très courte pour éviter le crash/timeout du serveur
output = llm(
prompt,
max_tokens=50,
stop=["User:", "\nUser:", "Assistant:", "\nAssistant:"],
temperature=0.4
)
reply = output['choices'][0]['text'].strip()
return {"response": reply}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) |