Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,64 +10,77 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
#
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
"""
|
| 15 |
-
Meta-Llama-3-8B-Instruct
|
| 16 |
"""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 20 |
self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 21 |
|
| 22 |
-
# Fetch the token from
|
| 23 |
self.api_token = os.getenv("HF_TOKEN")
|
| 24 |
if not self.api_token:
|
| 25 |
-
raise ValueError("Hugging Face API token not found. Please set
|
| 26 |
|
| 27 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 28 |
-
print(f"BasicAgent initialized
|
| 29 |
|
| 30 |
-
def __call__(self, question: str
|
|
|
|
|
|
|
|
|
|
| 31 |
"""
|
| 32 |
Takes a question, sends it to the LLM via the Inference API, and returns the answer.
|
| 33 |
"""
|
| 34 |
-
print(f"Agent received question (
|
| 35 |
|
| 36 |
-
# Llama-3
|
| 37 |
-
# We construct a simple user prompt and let the API handle the full template.
|
| 38 |
payload = {
|
| 39 |
-
"inputs":
|
|
|
|
|
|
|
|
|
|
| 40 |
"parameters": {
|
| 41 |
-
"max_new_tokens":
|
| 42 |
-
"return_full_text": False,
|
| 43 |
-
"temperature":
|
| 44 |
-
"top_p":
|
| 45 |
}
|
| 46 |
}
|
| 47 |
|
| 48 |
try:
|
| 49 |
-
print("Querying
|
| 50 |
-
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=
|
| 51 |
-
response.raise_for_status()
|
| 52 |
|
| 53 |
result = response.json()
|
| 54 |
|
| 55 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
if isinstance(result, list) and result:
|
| 57 |
-
answer = result[0].get("generated_text", "
|
| 58 |
else:
|
| 59 |
answer = f"Error: Unexpected API response format: {result}"
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
print(f"Agent returning answer (first 80 chars): {answer.strip()[:80]}...")
|
| 63 |
return answer.strip()
|
| 64 |
|
| 65 |
except requests.exceptions.RequestException as e:
|
| 66 |
-
print(f"
|
| 67 |
return f"Error: Could not connect to the Inference API. Details: {e}"
|
| 68 |
except Exception as e:
|
| 69 |
-
print(f"
|
| 70 |
-
return f"Error:
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
#
|
| 13 |
+
|
| 14 |
+
|
| 15 |
class BasicAgent:
|
| 16 |
"""
|
| 17 |
+
Default: Meta-Llama-3-8B-Instruct
|
| 18 |
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, model_id: str = "meta-llama/Meta-Llama-3-8B-Instruct"):
|
| 21 |
+
# Allow custom model_id
|
| 22 |
+
self.model_id = model_id
|
| 23 |
self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 24 |
|
| 25 |
+
# Fetch the token from environment
|
| 26 |
self.api_token = os.getenv("HF_TOKEN")
|
| 27 |
if not self.api_token:
|
| 28 |
+
raise ValueError("❌ Hugging Face API token not found. Please set 'HF_TOKEN' as env variable.")
|
| 29 |
|
| 30 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 31 |
+
print(f"✅ BasicAgent initialized with model: {model_id}")
|
| 32 |
|
| 33 |
+
def __call__(self, question: str,
|
| 34 |
+
max_new_tokens: int = 512,
|
| 35 |
+
temperature: float = 0.6,
|
| 36 |
+
top_p: float = 0.9) -> str:
|
| 37 |
"""
|
| 38 |
Takes a question, sends it to the LLM via the Inference API, and returns the answer.
|
| 39 |
"""
|
| 40 |
+
print(f"📝 Agent received question (preview): {question[:80]}...")
|
| 41 |
|
| 42 |
+
# Prompt formatting for Llama-3 style
|
|
|
|
| 43 |
payload = {
|
| 44 |
+
"inputs": (
|
| 45 |
+
f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
|
| 46 |
+
f"{question}\n<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 47 |
+
),
|
| 48 |
"parameters": {
|
| 49 |
+
"max_new_tokens": max_new_tokens,
|
| 50 |
+
"return_full_text": False,
|
| 51 |
+
"temperature": temperature,
|
| 52 |
+
"top_p": top_p,
|
| 53 |
}
|
| 54 |
}
|
| 55 |
|
| 56 |
try:
|
| 57 |
+
print("🚀 Querying Hugging Face Inference API...")
|
| 58 |
+
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=60)
|
| 59 |
+
response.raise_for_status() # Raise an error for bad status codes
|
| 60 |
|
| 61 |
result = response.json()
|
| 62 |
|
| 63 |
+
# Handle error response from HF
|
| 64 |
+
if isinstance(result, dict) and "error" in result:
|
| 65 |
+
print(f"⚠️ HF API Error: {result['error']}")
|
| 66 |
+
return f"Error: {result['error']}"
|
| 67 |
+
|
| 68 |
+
# Normal expected case: list of dicts
|
| 69 |
if isinstance(result, list) and result:
|
| 70 |
+
answer = result[0].get("generated_text", "")
|
| 71 |
else:
|
| 72 |
answer = f"Error: Unexpected API response format: {result}"
|
| 73 |
+
|
| 74 |
+
print(f"🤖 Agent returning answer (preview): {answer.strip()[:80]}...")
|
|
|
|
| 75 |
return answer.strip()
|
| 76 |
|
| 77 |
except requests.exceptions.RequestException as e:
|
| 78 |
+
print(f"❌ API request error: {e}")
|
| 79 |
return f"Error: Could not connect to the Inference API. Details: {e}"
|
| 80 |
except Exception as e:
|
| 81 |
+
print(f"🔥 Unexpected error in agent: {e}")
|
| 82 |
+
return f"Error: Unexpected failure while processing. Details: {e}"
|
| 83 |
+
|
| 84 |
|
| 85 |
|
| 86 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|