dali4444444 commited on
Commit
e821ed9
·
verified ·
1 Parent(s): 5a30b2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -14
app.py CHANGED
@@ -3,59 +3,95 @@ import requests
3
  import os
4
  from fastapi import FastAPI
5
  from pydantic import BaseModel
6
- import uvicorn
7
 
 
8
  HF_TOKEN = os.environ.get("HF_TOKEN")
 
 
9
  API_URL = "https://router.huggingface.co/hf-inference/models/mistralai/Mistral-7B-Instruct-v0.3"
10
 
11
- SYSTEM_PROMPT = "Tu es l'assistant SAV officiel du Centre Chery Tunisie. Tu réponds en français ou en arabe dialectal tunisien selon la langue du client. Réponds uniquement aux questions liées aux véhicules Chery, la maintenance, les pannes, et le service après-vente."
 
 
 
12
 
 
13
  def chat(message, history):
14
  prompt = f"[INST] <<SYS>>\n{SYSTEM_PROMPT}\n<</SYS>>\n\n"
 
15
  for h in history:
16
  if isinstance(h, dict):
17
- if h["role"] == "user":
18
- prompt += f"{h['content']} [/INST] "
19
  else:
20
- prompt += f"{h['content']} </s><s>[INST] "
21
  else:
22
  prompt += f"{h[0]} [/INST] {h[1]} </s><s>[INST] "
 
23
  prompt += f"{message} [/INST]"
24
 
25
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
 
 
 
 
26
  payload = {
27
  "inputs": prompt,
28
  "parameters": {
29
  "max_new_tokens": 300,
30
  "temperature": 0.7,
 
 
31
  "return_full_text": False
32
  }
33
  }
34
 
35
  try:
36
  response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
 
 
 
 
 
37
  result = response.json()
 
 
38
  if isinstance(result, list):
39
  return result[0].get("generated_text", "Pas de réponse")
40
- elif "error" in result:
41
- return f"Erreur API: {result['error']}"
 
 
 
 
 
42
  return str(result)
 
 
 
43
  except Exception as e:
44
  return f"Erreur: {str(e)}"
45
 
 
 
46
  app = FastAPI()
47
 
48
  class ChatRequest(BaseModel):
49
  message: str
50
  history: list = []
51
 
 
52
  @app.post("/api/chat")
53
  async def api_chat(req: ChatRequest):
54
- response = chat(req.message, req.history)
55
- return {"reply": response}
56
 
57
- demo = gr.ChatInterface(fn=chat, title="Chery SAV Assistant")
58
- app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
59
 
60
- if __name__ == "__main__":
61
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
3
  import os
4
  from fastapi import FastAPI
5
  from pydantic import BaseModel
 
6
 
7
+ # 🔐 Token
8
  HF_TOKEN = os.environ.get("HF_TOKEN")
9
+
10
+ # ✅ Use router endpoint (good choice)
11
  API_URL = "https://router.huggingface.co/hf-inference/models/mistralai/Mistral-7B-Instruct-v0.3"
12
 
13
+ # 🧠 System prompt
14
+ SYSTEM_PROMPT = """Tu es l'assistant SAV officiel du Centre Chery Tunisie.
15
+ Tu réponds en français ou en arabe dialectal tunisien selon la langue du client.
16
+ Réponds uniquement aux questions liées aux véhicules Chery, la maintenance, les pannes et le service après-vente."""
17
 
18
+ # 💬 Chat function
19
  def chat(message, history):
20
  prompt = f"[INST] <<SYS>>\n{SYSTEM_PROMPT}\n<</SYS>>\n\n"
21
+
22
  for h in history:
23
  if isinstance(h, dict):
24
+ if h.get("role") == "user":
25
+ prompt += f"{h.get('content')} [/INST] "
26
  else:
27
+ prompt += f"{h.get('content')} </s><s>[INST] "
28
  else:
29
  prompt += f"{h[0]} [/INST] {h[1]} </s><s>[INST] "
30
+
31
  prompt += f"{message} [/INST]"
32
 
33
+ headers = {
34
+ "Authorization": f"Bearer {HF_TOKEN}",
35
+ "Content-Type": "application/json"
36
+ }
37
+
38
  payload = {
39
  "inputs": prompt,
40
  "parameters": {
41
  "max_new_tokens": 300,
42
  "temperature": 0.7,
43
+ "top_p": 0.9,
44
+ "do_sample": True,
45
  "return_full_text": False
46
  }
47
  }
48
 
49
  try:
50
  response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
51
+
52
+ # ✅ Check HTTP error
53
+ if response.status_code != 200:
54
+ return f"Erreur HTTP {response.status_code}: {response.text}"
55
+
56
  result = response.json()
57
+
58
+ # ✅ Handle response formats
59
  if isinstance(result, list):
60
  return result[0].get("generated_text", "Pas de réponse")
61
+
62
+ if isinstance(result, dict):
63
+ if "error" in result:
64
+ if "loading" in result["error"].lower():
65
+ return "⏳ Le modèle est en cours de chargement, réessayez dans quelques secondes."
66
+ return f"Erreur API: {result['error']}"
67
+
68
  return str(result)
69
+
70
+ except requests.exceptions.Timeout:
71
+ return "⏱️ Timeout: le modèle met trop de temps à répondre."
72
  except Exception as e:
73
  return f"Erreur: {str(e)}"
74
 
75
+
76
+ # 🚀 FastAPI
77
  app = FastAPI()
78
 
79
  class ChatRequest(BaseModel):
80
  message: str
81
  history: list = []
82
 
83
+
84
  @app.post("/api/chat")
85
  async def api_chat(req: ChatRequest):
86
+ return {"reply": chat(req.message, req.history)}
87
+
88
 
89
+ # 🎨 Gradio UI
90
+ demo = gr.ChatInterface(
91
+ fn=chat,
92
+ title="🚗 Chery SAV Assistant",
93
+ description="Assistant intelligent pour le service après-vente Chery Tunisie"
94
+ )
95
 
96
+ # 🔗 Mount Gradio inside FastAPI
97
+ app = gr.mount_gradio_app(app, demo, path="/")