Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,9 +3,6 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
import time
|
| 7 |
-
from typing import Optional, Dict, Any
|
| 8 |
-
from requests.adapters import HTTPAdapter, Retry
|
| 9 |
|
| 10 |
# (Keep Constants as is)
|
| 11 |
# --- Constants ---
|
|
@@ -20,62 +17,16 @@ class BasicAgent:
|
|
| 20 |
Default: Meta-Llama-3-8B-Instruct
|
| 21 |
"""
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
model_id_env = os.getenv("HF_MODEL_ID")
|
| 26 |
self.model_id = model_id_env.strip() if model_id_env else model_id
|
| 27 |
-
|
| 28 |
-
# Correct HF Inference API endpoint
|
| 29 |
self.api_url = f"https://api-inference.huggingface.co/models/{self.model_id}"
|
| 30 |
-
|
| 31 |
-
# Fetch the token from environment
|
| 32 |
self.api_token = os.getenv("HF_TOKEN")
|
| 33 |
if not self.api_token:
|
| 34 |
raise ValueError("❌ Hugging Face API token not found. Please set 'HF_TOKEN' as env variable.")
|
| 35 |
-
|
| 36 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 37 |
-
|
| 38 |
-
# Requests session with retries/backoff for 429/5xx and model loading
|
| 39 |
-
self.session = requests.Session()
|
| 40 |
-
retries = Retry(
|
| 41 |
-
total=6,
|
| 42 |
-
backoff_factor=1.5,
|
| 43 |
-
status_forcelist=[429, 500, 502, 503, 504],
|
| 44 |
-
allowed_methods=frozenset(["POST", "GET"]),
|
| 45 |
-
raise_on_status=False,
|
| 46 |
-
)
|
| 47 |
-
self.session.mount("https://", HTTPAdapter(max_retries=retries))
|
| 48 |
-
self.session.mount("http://", HTTPAdapter(max_retries=retries))
|
| 49 |
-
|
| 50 |
-
print(f"✅ BasicAgent initialized with model: {self.model_id}")
|
| 51 |
-
|
| 52 |
-
def _post_with_retries(self, url: str, json: Dict[str, Any], timeout: int = 60) -> requests.Response:
|
| 53 |
-
"""
|
| 54 |
-
Additional manual backoff loop to handle model cold starts (HF returns 503 while loading).
|
| 55 |
-
"""
|
| 56 |
-
max_attempts = 8
|
| 57 |
-
delay = 2.0
|
| 58 |
-
for attempt in range(1, max_attempts + 1):
|
| 59 |
-
try:
|
| 60 |
-
resp = self.session.post(url, headers=self.headers, json=json, timeout=timeout)
|
| 61 |
-
# If model is loading or rate-limited, wait and retry
|
| 62 |
-
if resp.status_code in (429, 503):
|
| 63 |
-
msg = ""
|
| 64 |
-
try:
|
| 65 |
-
msg = resp.json().get("error", "")
|
| 66 |
-
except Exception:
|
| 67 |
-
msg = resp.text[:200]
|
| 68 |
-
print(f"⏳ Attempt {attempt}/{max_attempts} - {resp.status_code}: {msg} | waiting {delay:.1f}s")
|
| 69 |
-
time.sleep(delay)
|
| 70 |
-
delay = min(delay * 1.7, 30.0)
|
| 71 |
-
continue
|
| 72 |
-
return resp
|
| 73 |
-
except requests.exceptions.RequestException as e:
|
| 74 |
-
print(f"⚠️ Network issue on attempt {attempt}/{max_attempts}: {e} | waiting {delay:.1f}s")
|
| 75 |
-
time.sleep(delay)
|
| 76 |
-
delay = min(delay * 1.7, 30.0)
|
| 77 |
-
# Final attempt without catching to propagate any error
|
| 78 |
-
return self.session.post(url, headers=self.headers, json=json, timeout=timeout)
|
| 79 |
|
| 80 |
def __call__(self, question: str,
|
| 81 |
max_new_tokens: int = 512,
|
|
@@ -87,12 +38,11 @@ class BasicAgent:
|
|
| 87 |
print(f"📝 Agent received question (preview): {question[:80]}...")
|
| 88 |
|
| 89 |
# Prompt formatting for Llama-3 style
|
| 90 |
-
inputs = (
|
| 91 |
-
f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
|
| 92 |
-
f"{question}\n<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 93 |
-
)
|
| 94 |
payload = {
|
| 95 |
-
"inputs":
|
|
|
|
|
|
|
|
|
|
| 96 |
"parameters": {
|
| 97 |
"max_new_tokens": max_new_tokens,
|
| 98 |
"return_full_text": False,
|
|
@@ -103,28 +53,19 @@ class BasicAgent:
|
|
| 103 |
|
| 104 |
try:
|
| 105 |
print("🚀 Querying Hugging Face Inference API...")
|
| 106 |
-
response =
|
| 107 |
-
# Raise
|
| 108 |
-
response.raise_for_status()
|
| 109 |
|
| 110 |
result = response.json()
|
| 111 |
|
| 112 |
-
# Handle
|
| 113 |
if isinstance(result, dict) and "error" in result:
|
| 114 |
print(f"⚠️ HF API Error: {result['error']}")
|
| 115 |
return f"Error: {result['error']}"
|
| 116 |
|
| 117 |
-
# Normal expected case: list of dicts
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
# Some models return list of dicts
|
| 121 |
-
if isinstance(result[0], dict):
|
| 122 |
-
answer = result[0].get("generated_text", "")
|
| 123 |
-
else:
|
| 124 |
-
answer = str(result[0])
|
| 125 |
-
elif isinstance(result, dict) and "generated_text" in result:
|
| 126 |
-
# Some endpoints may directly return a dict
|
| 127 |
-
answer = result.get("generated_text", "")
|
| 128 |
else:
|
| 129 |
answer = f"Error: Unexpected API response format: {result}"
|
| 130 |
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
|
|
|
| 17 |
Default: Meta-Llama-3-8B-Instruct
|
| 18 |
"""
|
| 19 |
|
| 20 |
+
# In __init__ of BasicAgent
|
| 21 |
+
def __init__(self, model_id: str = "HuggingFaceH4/zephyr-7b-beta"):
|
| 22 |
model_id_env = os.getenv("HF_MODEL_ID")
|
| 23 |
self.model_id = model_id_env.strip() if model_id_env else model_id
|
|
|
|
|
|
|
| 24 |
self.api_url = f"https://api-inference.huggingface.co/models/{self.model_id}"
|
|
|
|
|
|
|
| 25 |
self.api_token = os.getenv("HF_TOKEN")
|
| 26 |
if not self.api_token:
|
| 27 |
raise ValueError("❌ Hugging Face API token not found. Please set 'HF_TOKEN' as env variable.")
|
|
|
|
| 28 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 29 |
+
# ... keep session/retries as you have ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def __call__(self, question: str,
|
| 32 |
max_new_tokens: int = 512,
|
|
|
|
| 38 |
print(f"📝 Agent received question (preview): {question[:80]}...")
|
| 39 |
|
| 40 |
# Prompt formatting for Llama-3 style
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
payload = {
|
| 42 |
+
"inputs": (
|
| 43 |
+
f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
|
| 44 |
+
f"{question}\n<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 45 |
+
),
|
| 46 |
"parameters": {
|
| 47 |
"max_new_tokens": max_new_tokens,
|
| 48 |
"return_full_text": False,
|
|
|
|
| 53 |
|
| 54 |
try:
|
| 55 |
print("🚀 Querying Hugging Face Inference API...")
|
| 56 |
+
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=16)
|
| 57 |
+
response.raise_for_status() # Raise an error for bad status codes
|
|
|
|
| 58 |
|
| 59 |
result = response.json()
|
| 60 |
|
| 61 |
+
# Handle error response from HF
|
| 62 |
if isinstance(result, dict) and "error" in result:
|
| 63 |
print(f"⚠️ HF API Error: {result['error']}")
|
| 64 |
return f"Error: {result['error']}"
|
| 65 |
|
| 66 |
+
# Normal expected case: list of dicts
|
| 67 |
+
if isinstance(result, list) and result:
|
| 68 |
+
answer = result[0].get("generated_text", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
else:
|
| 70 |
answer = f"Error: Unexpected API response format: {result}"
|
| 71 |
|