ErdemTheFixer commited on
Commit
219a09b
·
verified ·
1 Parent(s): b816295

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -27
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
- def __init__(self):
18
- # The model we want to use
19
- model_id = "meta-llama/Meta-Llama-3-8B-Instruct" #"Qwen/Qwen3-4B-Thinking-2507"
 
20
  self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
21
 
22
- # Fetch the token from Space Secrets
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 the 'HF_TOKEN' secret in your Space settings.")
26
 
27
  self.headers = {"Authorization": f"Bearer {self.api_token}"}
28
- print(f"BasicAgent initialized to use model: {model_id}")
29
 
30
- def __call__(self, question: str) -> 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 (first 80 chars): {question[:80]}...")
35
 
36
- # Llama-3 requires a specific prompt format.
37
- # We construct a simple user prompt and let the API handle the full template.
38
  payload = {
39
- "inputs": f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{question}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n",
 
 
 
40
  "parameters": {
41
- "max_new_tokens": 512, # Limit the length of the answer
42
- "return_full_text": False, # Only return the generated part
43
- "temperature": 0.6, # A bit of creativity
44
- "top_p": 0.9, # Nucleus sampling
45
  }
46
  }
47
 
48
  try:
49
- print("Querying the Inference API...")
50
- response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=45)
51
- response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
52
 
53
  result = response.json()
54
 
55
- # The response is a list containing a dictionary
 
 
 
 
 
56
  if isinstance(result, list) and result:
57
- answer = result[0].get("generated_text", "Error: 'generated_text' key not found in API response.")
58
  else:
59
  answer = f"Error: Unexpected API response format: {result}"
60
- print(answer) # Log the unexpected response
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"Error during API request: {e}")
67
  return f"Error: Could not connect to the Inference API. Details: {e}"
68
  except Exception as e:
69
- print(f"An unexpected error occurred in the agent: {e}")
70
- return f"Error: An unexpected error occurred while processing the question. Details: {e}"
 
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):