AxL95 commited on
Commit
d3378a2
·
verified ·
1 Parent(s): edd6f91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -17
app.py CHANGED
@@ -27,7 +27,6 @@ app.add_middleware(
27
  allow_headers=["*"],
28
  )
29
 
30
- HF_TOKEN = os.getenv("REACT_APP_HF_TOKEN")
31
 
32
  @app.get("/invert")
33
  async def invert(text: str):
@@ -36,25 +35,41 @@ async def invert(text: str):
36
  "inverted": text[::-1],
37
  }
38
 
 
 
 
 
 
 
 
 
 
 
39
  @app.post("/api/chat")
40
  async def chat(request: Request):
41
  data = await request.json()
42
- user_message = data.get("message", "")
43
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
44
- payload = {
45
- "inputs": {
46
- "past_user_inputs": [],
47
- "generated_responses": [],
48
- "text": user_message
49
- }
50
- }
51
- response = requests.post(
52
- "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3",
53
- headers=headers,
54
- json=payload
55
- )
56
- result = response.json()
57
- return {"response": result}
 
 
 
 
 
 
58
 
59
 
60
  @app.get("/data")
 
27
  allow_headers=["*"],
28
  )
29
 
 
30
 
31
  @app.get("/invert")
32
  async def invert(text: str):
 
35
  "inverted": text[::-1],
36
  }
37
 
38
+ HF_TOKEN = os.getenv("REACT_APP_HF_TOKEN")
39
+ if not HF_TOKEN:
40
+ raise RuntimeError("Le token Hugging Face (HF_TOKEN) n'est pas défini dans les variables d'environnement.")
41
+
42
+ # Initialisation du client HF
43
+ hf_client = InferenceClient(
44
+ provider="novita",
45
+ api_key=HF_TOKEN,
46
+ )
47
+
48
  @app.post("/api/chat")
49
  async def chat(request: Request):
50
  data = await request.json()
51
+ user_message = data.get("message", "").strip()
52
+ if not user_message:
53
+ raise HTTPException(status_code=400, detail="Le champ 'message' est requis.")
54
+
55
+ try:
56
+ # Appel au modèle en mode chat
57
+ completion = hf_client.chat.completions.create(
58
+ model="mistralai/Mistral-7B-Instruct-v0.3",
59
+ messages=[
60
+ {"role": "system", "content": "Tu es un assistant médical spécialisé en schizophrénie."},
61
+ {"role": "user", "content": user_message}
62
+ ],
63
+ max_tokens=512,
64
+ temperature=0.7,
65
+ )
66
+
67
+ bot_msg = completion.choices[0].message.content
68
+ return {"response": bot_msg}
69
+
70
+ except Exception as e:
71
+ # En cas d'erreur d'inférence
72
+ raise HTTPException(status_code=502, detail=f"Erreur d'inférence HF : {e}")
73
 
74
 
75
  @app.get("/data")