anssio commited on
Commit
a762b3b
·
verified ·
1 Parent(s): 81917a3

Create agent.py

Browse files
Files changed (1) hide show
  1. agent.py +71 -0
agent.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 17/08/2025 -AO
2
+ import math
3
+ import re
4
+ import requests
5
+ from typing import Optional
6
+
7
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
+
9
+ class BasicAgent:
10
+ """
11
+ Very simple baseline agent.
12
+ - Tries to solve basic arithmetic expressions found in the question.
13
+ - If it cannot, returns a default safe string.
14
+ Keep responses concise because the grader does exact-match comparison.
15
+ """
16
+
17
+ def __init__(self, api_url: str = DEFAULT_API_URL):
18
+ self.api_url = api_url
19
+ # Precompile a simple arithmetic pattern like "12 + 3 * 4" or "(5+2)/7"
20
+ self.expr_pattern = re.compile(r"^[\s\d\+\-\*/\(\)\.]+$")
21
+
22
+ def try_eval_math(self, text: str) -> Optional[str]:
23
+ # Extract a math-like snippet if the whole string looks like math.
24
+ s = text.strip()
25
+ if not s:
26
+ return None
27
+ if self.expr_pattern.match(s):
28
+ try:
29
+ # Safe eval using eval on limited globals/locals.
30
+ val = eval(s, {"__builtins": {}}, {"math": math})
31
+ # Format as plain value string.
32
+ return str(val)
33
+ except Exception:
34
+ return None
35
+ return None
36
+
37
+ def __call__(self, question: str) -> str:
38
+ # Try direct arithmetic
39
+ ans = self.try_eval_math(question)
40
+ if ans is not None:
41
+ return ans
42
+
43
+ # Extremely small heuristics: look for numbers and operations within the sentence.
44
+ digits = re.findall(r"[\d\.]+", question)
45
+ if len(digits) >= 2:
46
+ try:
47
+ # If words like 'sum' or 'add' appear, add the numbers.
48
+ ql = question.lower()
49
+ nums = list(map(float, digits))
50
+ if any(k in ql for k in ["sum", "add", "+"]):
51
+ return str(sum(nums))
52
+ if any(k in ql for k in ["difference", "subtract", "-"]):
53
+ return str(nums[0] - sum(nums[1:]))
54
+ if any(k in ql for k in ["product", "multiply", "*"]):
55
+ p = 1.0
56
+ for n in nums:
57
+ p *= n
58
+ return str(p)
59
+ if any(k in ql for k in ["divide", "ratio", "/"]):
60
+ try:
61
+ res = nums[0]
62
+ for n in nums[1:]:
63
+ res /= n
64
+ return str(res)
65
+ except ZeroDivisionError:
66
+ return "undefined"
67
+ except Exception:
68
+ pass
69
+
70
+ # Fallback default answer; keep minimal for exact-match grading.
71
+ return "unknown"