Ishikawa7 commited on
Commit
f866b07
·
verified ·
1 Parent(s): c10e885

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -68
app.py CHANGED
@@ -1,92 +1,82 @@
1
- import os
2
  import gradio as gr
3
- import requests
4
  import inspect
5
- import pandas as pd
6
- from smolagents.agents import ToolUseAgent
7
- from smolagents.tools import Tool
8
- import ast
9
- import math
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
- # ---- Tool 1: Calculator ----
15
- def safe_eval_math(expr: str) -> str:
 
 
 
 
 
 
 
 
16
  try:
17
- # Only allow safe functions and math operators
18
- allowed_names = {"sqrt": math.sqrt, "log": math.log, "pow": pow, "abs": abs, "round": round}
19
- code = compile(expr, "<string>", "eval")
20
- for node in ast.walk(code):
21
- if isinstance(node, ast.Name) and node.id not in allowed_names:
22
- raise ValueError(f"Use of '{node.id}' not allowed")
23
- return str(eval(code, {"__builtins__": {}}, allowed_names))
24
  except Exception as e:
25
  return f"Error: {e}"
26
 
27
- calculator_tool = Tool(
28
- name="calculator",
29
- description="Evaluates basic math expressions like '2 + 2 * sqrt(9)'",
30
- func=safe_eval_math,
31
- )
32
-
33
- # ---- Tool 2: Python Code Evaluator ----
34
- def run_python_code(code: str) -> str:
 
 
35
  try:
36
- # Eval in restricted namespace
37
- local_vars = {}
38
- exec(code, {"__builtins__": {}}, local_vars)
39
- return str(local_vars)
 
 
40
  except Exception as e:
41
- return f"Code Error: {e}"
42
-
43
- python_tool = Tool(
44
- name="python_eval",
45
- description="Runs simple Python code blocks and returns the result. Use this for code-based reasoning.",
46
- func=run_python_code,
47
- )
48
 
49
- # ---- Tool 3: File Downloader (Optional, if GAIA task uses /files/{task_id}) ----
50
- def download_file(task_id: str) -> str:
51
- base_url = os.getenv("DEFAULT_API_URL", "https://agents-course-unit4-scoring.hf.space")
52
- url = f"{base_url}/files/{task_id}"
 
 
 
 
 
 
 
 
53
  try:
54
- r = requests.get(url)
55
- r.raise_for_status()
56
- file_path = f"/tmp/{task_id}"
57
- with open(file_path, "wb") as f:
58
- f.write(r.content)
59
- return f"File downloaded to {file_path}"
60
  except Exception as e:
61
- return f"Failed to download file: {e}"
62
 
63
- file_tool = Tool(
64
- name="download_file",
65
- description="Downloads file for a given GAIA task_id.",
66
- func=download_file,
67
- )
68
 
69
- # ---- The Smart Tool Agent ----
70
  class ToolAgent:
71
  def __init__(self):
72
- print("Initializing ToolAgent with smolagents...")
73
- self.agent = ToolUseAgent(
74
- tools=[calculator_tool, python_tool, file_tool],
75
- system_prompt=(
76
- "You are a helpful agent for solving GAIA benchmark questions. "
77
- "Use tools when appropriate. Return only the exact answer."
78
- )
79
- )
80
 
81
  def __call__(self, question: str) -> str:
82
- print(f"Agent received: {question[:80]}")
83
- try:
84
- result = self.agent.run(question)
85
- print(f"Raw Result: {result}")
86
- return result.strip()
87
- except Exception as e:
88
- print(f"Error while answering: {e}")
89
- return "Agent error"
90
 
91
  def run_and_submit_all( profile: gr.OAuthProfile | None):
92
  """
 
 
1
  import gradio as gr
 
2
  import inspect
3
+ from smolagents import CodeAgent, load_tool, InferenceClientModel
4
+ from smolagents.tool import tool
5
+ import math, ast, os, requests, pandas as pd
 
 
6
  # (Keep Constants as is)
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+ # --- Tool: Safe Math Evaluator ---
11
+ @tool
12
+ def calc(expr: str) -> str:
13
+ """
14
+ Evaluate an arithmetic expression safely.
15
+ Args:
16
+ expr (str): math expression like '2+3*sqrt(16)'.
17
+ Returns:
18
+ str: the numeric result or an error message.
19
+ """
20
  try:
21
+ allowed = {"sqrt": math.sqrt, "log": math.log, "pow": pow, "abs": abs, "round": round}
22
+ tree = ast.parse(expr, mode="eval")
23
+ for node in ast.walk(tree):
24
+ if isinstance(node, ast.Name) and node.id not in allowed:
25
+ return f"Error: '{node.id}' not allowed"
26
+ return str(eval(compile(tree, "<", "eval"), {"__builtins__": {}}, allowed))
 
27
  except Exception as e:
28
  return f"Error: {e}"
29
 
30
+ # --- Tool: Python Code Runner ---
31
+ @tool
32
+ def run_py(code: str) -> str:
33
+ """
34
+ Execute snippet and return printed output or resulting variables.
35
+ Args:
36
+ code (str): Python code block.
37
+ Returns:
38
+ str: result or error text.
39
+ """
40
  try:
41
+ gl = {}
42
+ loc = {}
43
+ exec(code, gl, loc)
44
+ if loc:
45
+ return str(loc)
46
+ return ""
47
  except Exception as e:
48
+ return f"Error: {e}"
 
 
 
 
 
 
49
 
50
+ # --- Tool: File Downloader for GAIA ---
51
+ @tool
52
+ def download(task_id: str) -> str:
53
+ """
54
+ Download GAIA task file.
55
+ Args:
56
+ task_id (str): ID from GET /random-question.
57
+ Returns:
58
+ str: local file path or error.
59
+ """
60
+ base = os.getenv("DEFAULT_API_URL", "https://agents-course-unit4-scoring.hf.space")
61
+ url = f"{base}/files/{task_id}"
62
  try:
63
+ r = requests.get(url); r.raise_for_status()
64
+ path = f"/tmp/{task_id}"
65
+ with open(path, "wb") as f: f.write(r.content)
66
+ return path
 
 
67
  except Exception as e:
68
+ return f"Error: {e}"
69
 
70
+ model = InferenceClientModel()
71
+ agent = CodeAgent(tools=[calc, run_py, download], model=model)
 
 
 
72
 
 
73
  class ToolAgent:
74
  def __init__(self):
75
+ self.agent = agent # from above
 
 
 
 
 
 
 
76
 
77
  def __call__(self, question: str) -> str:
78
+ result = self.agent.run(question)
79
+ return result.strip()
 
 
 
 
 
 
80
 
81
  def run_and_submit_all( profile: gr.OAuthProfile | None):
82
  """