Paul720810 commited on
Commit
63d4932
·
verified ·
1 Parent(s): 7adb5ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -4
app.py CHANGED
@@ -141,7 +141,11 @@ class TextToSQLSystem:
141
 
142
  def huggingface_api_call(self, prompt: str) -> str:
143
  """呼叫 Hugging Face Inference API"""
144
- API_URL = "[https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1](https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1)"
 
 
 
 
145
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
146
  payload = {
147
  "inputs": prompt,
@@ -151,14 +155,33 @@ class TextToSQLSystem:
151
  }
152
  }
153
  try:
 
 
 
 
154
  self._log("正在呼叫 Hugging Face API...")
155
- response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
156
- response.raise_for_status()
 
157
  self._log("✅ API 成功回應。")
158
  return response.json()[0]['generated_text']
 
159
  except requests.exceptions.RequestException as e:
160
  self._log(f"❌ API 呼叫失敗: {e}", "ERROR")
161
- return f"API 錯誤: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
  # === 修改開始: 重寫核心處理邏輯 ===
164
  def _build_prompt_for_generation(self, user_question: str, examples: List[Dict]) -> str:
 
141
 
142
  def huggingface_api_call(self, prompt: str) -> str:
143
  """呼叫 Hugging Face Inference API"""
144
+ # === 修正開始 ===
145
+ # 確保 API_URL 是一個乾淨的字串,不包含任何 Markdown "[ ]" 或其他特殊字元
146
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1"
147
+ # === 修正結束 ===
148
+
149
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
150
  payload = {
151
  "inputs": prompt,
 
155
  }
156
  }
157
  try:
158
+ # === 新增除錯日誌 ===
159
+ # 在發送請求前,打印出最終要使用的 URL,以供檢查
160
+ self._log(f"準備向 API 端點發送請求: {API_URL}")
161
+
162
  self._log("正在呼叫 Hugging Face API...")
163
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=90) # 延長超時時間
164
+ response.raise_for_status() # 如果 API 回傳錯誤碼 (如 4xx, 5xx),會在此拋出例外
165
+
166
  self._log("✅ API 成功回應。")
167
  return response.json()[0]['generated_text']
168
+
169
  except requests.exceptions.RequestException as e:
170
  self._log(f"❌ API 呼叫失敗: {e}", "ERROR")
171
+
172
+ # 嘗試解析回應內容,看是否是模型載入中的常見錯誤
173
+ try:
174
+ # 即使請求失敗,有時回應本文中仍有 JSON 錯誤訊息
175
+ error_content = e.response.json() if e.response else {}
176
+ if "error" in error_content and "estimated_time" in error_content["error"]:
177
+ loading_time = error_content["error"]["estimated_time"]
178
+ self._log(f" - 提示: 模型可能正在載入中,預計需要 {loading_time:.1f} 秒。請稍後重試。", "WARNING")
179
+ return f"API 錯誤: 模型正在載入中,請稍後再試一次。"
180
+ except (ValueError, AttributeError):
181
+ # 如果回應不是 JSON 或沒有回應本文,就忽略
182
+ pass
183
+
184
+ return f"API 連線錯誤: {e}"
185
 
186
  # === 修改開始: 重寫核心處理邏輯 ===
187
  def _build_prompt_for_generation(self, user_question: str, examples: List[Dict]) -> str: