Zenkad commited on
Commit
92bb2fe
·
verified ·
1 Parent(s): ac04e02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -75
app.py CHANGED
@@ -3,14 +3,14 @@ from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import os
5
  import requests
6
- import time
7
 
8
  # =========================
9
  # CONFIG
10
  # =========================
11
- HF_MODEL = "tiiuae/falcon-1b-instruct"
12
- HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
13
- HF_TOKEN = os.getenv("HF_TOKEN") # Ortam değişkeninden al
 
14
 
15
  # =========================
16
  # FASTAPI
@@ -37,86 +37,57 @@ async def chat(req: Request):
37
  return JSONResponse(status_code=400, content={"response": "Mesaj boş olamaz."})
38
 
39
  if not HF_TOKEN:
40
- return {"response": "⚠️ HF_TOKEN tanımlı değil. Lütfen ortam değişkenini ayarla."}
41
-
42
- prompt = f"""
43
- Sen ZenkaMind'sin, bir yapay zeka asistanısın.
44
- Sadece Türkçe konuş.
45
- Net, kısa ve dostane cevaplar ver.
46
 
47
- Kullanıcı: {message}
48
- ZenkaMind:"""
 
 
49
 
50
- try:
51
- headers = {
52
- "Authorization": f"Bearer {HF_TOKEN}",
53
- "Content-Type": "application/json"
54
- }
55
-
56
- payload = {
57
- "inputs": prompt,
58
- "parameters": {
59
- "max_new_tokens": 150,
60
- "temperature": 0.7,
61
- "top_p": 0.9,
62
- "do_sample": True,
63
- "return_full_text": False
64
  }
65
- }
 
 
 
66
 
 
67
  response = requests.post(
68
- HF_API_URL,
69
  headers=headers,
70
  json=payload,
71
- timeout=30
72
  )
73
 
74
- # Model yükleniyorsa
75
- if response.status_code == 503:
76
- estimated_time = response.json().get("estimated_time", 30)
77
- return {"response": f"⏳ Model yükleniyor, lütfen {int(estimated_time)} saniye sonra tekrar deneyin."}
78
-
79
- # Başarılı ise
80
- if response.status_code == 200:
81
- result = response.json()
82
-
83
- # Hugging Face yanıt formatını işle
84
- generated_text = ""
85
-
86
- if isinstance(result, list):
87
- # Liste formatı: [{"generated_text": "..."}]
88
- if len(result) > 0 and isinstance(result[0], dict):
89
- generated_text = result[0].get("generated_text", "")
90
- elif isinstance(result, dict):
91
- # Dict formatı: {"generated_text": "..."}
92
- generated_text = result.get("generated_text", "")
93
-
94
- # Temizleme
95
- if generated_text:
96
- # Prompt'u kaldır (eğer return_full_text=False çalışmazsa)
97
- if prompt in generated_text:
98
- generated_text = generated_text.replace(prompt, "")
99
- # Fazla boşlukları temizle
100
- generated_text = generated_text.strip()
101
- # Birden fazla satır varsa düzenle
102
- generated_text = " ".join(generated_text.split())
103
-
104
- if generated_text:
105
- return {"response": generated_text}
106
-
107
- return {"response": "⚠️ Model geçerli bir cevap üretemedi. Lütfen tekrar deneyin."}
108
-
109
- # Diğer hatalar
110
- else:
111
- error_detail = response.json().get("error", "Bilinmeyen hata")
112
- return {"response": f"❌ API Hatası ({response.status_code}): {error_detail}"}
113
 
114
  except requests.exceptions.Timeout:
115
- return {"response": "⏱️ İstek zaman aşımına uğradı. Lütfen tekrar deneyin."}
116
-
117
- except requests.exceptions.ConnectionError:
118
- return {"response": "🔌 Bağlantı hatası. İnternet bağlantınızı kontrol edin."}
119
-
120
  except Exception as e:
121
- print(f"Sunucu Hatası: {str(e)}")
122
- return {"response": "❌ Sunucuda beklenmeyen bir hata oluştu."}
 
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import os
5
  import requests
 
6
 
7
  # =========================
8
  # CONFIG
9
  # =========================
10
+ HF_TOKEN = os.getenv("HF_TOKEN")
11
+
12
+ HF_ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
13
+ MODEL = "Qwen/Qwen2.5-3B-Instruct" # hafif, hızlı, stabil
14
 
15
  # =========================
16
  # FASTAPI
 
37
  return JSONResponse(status_code=400, content={"response": "Mesaj boş olamaz."})
38
 
39
  if not HF_TOKEN:
40
+ return {"response": "⚠️ HF_TOKEN tanımlı değil."}
 
 
 
 
 
41
 
42
+ headers = {
43
+ "Authorization": f"Bearer {HF_TOKEN}",
44
+ "Content-Type": "application/json"
45
+ }
46
 
47
+ payload = {
48
+ "model": MODEL,
49
+ "messages": [
50
+ {
51
+ "role": "system",
52
+ "content": (
53
+ "Sen ZenkaMind adlı, Türkiye merkezli bir yapay zekasın. "
54
+ "Sadece Türkçe konuş. Net, kısa, gerçekçi cevaplar ver."
55
+ )
56
+ },
57
+ {
58
+ "role": "user",
59
+ "content": message
 
60
  }
61
+ ],
62
+ "temperature": 0.7,
63
+ "max_tokens": 256
64
+ }
65
 
66
+ try:
67
  response = requests.post(
68
+ HF_ROUTER_URL,
69
  headers=headers,
70
  json=payload,
71
+ timeout=60
72
  )
73
 
74
+ if response.status_code != 200:
75
+ return {
76
+ "response": f"❌ HF Router Hatası ({response.status_code})"
77
+ }
78
+
79
+ result = response.json()
80
+
81
+ if "choices" in result and len(result["choices"]) > 0:
82
+ return {
83
+ "response": result["choices"][0]["message"]["content"].strip()
84
+ }
85
+
86
+ return {"response": "⚠️ Model cevap üretmedi."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  except requests.exceptions.Timeout:
89
+ return {"response": "⏱️ Zaman aşımı. Tekrar dene."}
90
+
 
 
 
91
  except Exception as e:
92
+ print("HATA:", str(e))
93
+ return {"response": "❌ Sunucu hatası oluştu."}