mattibuzzo13 commited on
Commit
6929ee0
·
verified ·
1 Parent(s): 9123f7a

Update app.py

Browse files

Add tools to perform the tasks

Files changed (1) hide show
  1. app.py +149 -4
app.py CHANGED
@@ -3,21 +3,166 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ import re
7
+ import math
8
+ import json
9
+ import unicodedata
10
+ from langgraph.prebuilt import create_react_agent
11
+ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
12
+ from langchain_core.tools import tool
13
+ from langchain_community.tools import DuckDuckGoSearchRun
14
+ from langchain_community.utilities import WikipediaAPIWrapper
15
 
16
  # (Keep Constants as is)
17
  # --- Constants ---
18
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
19
 
20
+ @tool
21
+ def web_search(query: str) -> str:
22
+ """Search the web using DuckDuckGo. Use for current events, facts, and general knowledge."""
23
+ try:
24
+ search = DuckDuckGoSearchRun()
25
+ return search.run(query)
26
+ except Exception as e:
27
+ return f"Search error: {e}"
28
+
29
+
30
+ @tool
31
+ def wikipedia_search(query: str) -> str:
32
+ """Search Wikipedia for encyclopedic knowledge, historical facts, biographies, science."""
33
+ try:
34
+ wiki = WikipediaAPIWrapper(top_k_results=2, doc_content_chars_max=3000)
35
+ return wiki.run(query)
36
+ except Exception as e:
37
+ return f"Wikipedia error: {e}"
38
+
39
+
40
+ @tool
41
+ def python_repl(code: str) -> str:
42
+ """
43
+ Execute Python code for math calculations, data processing, logic.
44
+ Always print() the final result.
45
+ Example: print(2 + 2)
46
+ """
47
+ import io, sys
48
+ old_stdout = sys.stdout
49
+ sys.stdout = io.StringIO()
50
+ try:
51
+ exec(code, {
52
+ "math": math, "json": json, "re": re,
53
+ "unicodedata": unicodedata, "__builtins__": __builtins__
54
+ })
55
+ output = sys.stdout.getvalue()
56
+ return output.strip() if output.strip() else "Code executed with no output. Use print()."
57
+ except Exception as e:
58
+ return f"Code error: {e}"
59
+ finally:
60
+ sys.stdout = old_stdout
61
+
62
+
63
+ @tool
64
+ def calculator(expression: str) -> str:
65
+ """
66
+ Evaluate a simple math expression.
67
+ Examples: '2 + 2', '100 * 1.07 ** 5', 'math.sqrt(144)'
68
+ """
69
+ try:
70
+ result = eval(expression, {"math": math, "__builtins__": {}})
71
+ return str(result)
72
+ except Exception as e:
73
+ return f"Calculation error: {e}"
74
+
75
+
76
+ @tool
77
+ def get_task_file(task_id: str) -> str:
78
+ """
79
+ Fetch the file associated with a GAIA task by its task_id.
80
+ Use this when the question mentions an attached file or document.
81
+ """
82
+ try:
83
+ url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
84
+ response = requests.get(url, timeout=15)
85
+ if response.status_code == 200:
86
+ content_type = response.headers.get("Content-Type", "")
87
+ if "text" in content_type or "json" in content_type:
88
+ return response.text[:5000]
89
+ elif "image" in content_type:
90
+ return f"[Image file - content-type: {content_type}]"
91
+ elif "audio" in content_type:
92
+ return f"[Audio file - content-type: {content_type}]"
93
+ else:
94
+ return f"[File attached: {content_type}]"
95
+ return f"No file found for task {task_id}"
96
+ except Exception as e:
97
+ return f"Error fetching task file: {e}"
98
+
99
+
100
+ SYSTEM_PROMPT = """You are a precise expert AI solving GAIA benchmark questions.
101
+
102
+ ## Answer Format (CRITICAL)
103
+ - Give ONLY the bare answer: a number, word, name, date, or short phrase.
104
+ - NO explanations, NO punctuation at the end, NO "The answer is...".
105
+ - Correct examples: `42`, `Marie Curie`, `Paris`, `1969`, `blue`
106
+ - For lists: `item1, item2, item3`
107
+
108
+ ## Strategy
109
+ 1. Read carefully — identify exactly what is asked.
110
+ 2. Use tools to find and verify the answer.
111
+ 3. Double-check calculations with calculator or python_repl.
112
+ 4. If the question mentions a file or attachment, use get_task_file.
113
+
114
+ ## Final Answer
115
+ Always end with:
116
+ FINAL ANSWER: <your answer here>
117
+ """
118
+
119
+
120
  # --- Basic Agent Definition ---
121
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
122
  class BasicAgent:
123
  def __init__(self):
124
+ print("Initializing LangGraph ReAct Agent with Llama 3.3 70B...")
125
+
126
+ llm_endpoint = HuggingFaceEndpoint(
127
+ repo_id="meta-llama/Llama-3.3-70B-Instruct",
128
+ huggingfacehub_api_token=os.getenv("HF_TOKEN"),
129
+ task="text-generation",
130
+ max_new_tokens=1024,
131
+ temperature=0.1,
132
+ do_sample=False,
133
+ )
134
+ llm = ChatHuggingFace(llm=llm_endpoint)
135
+
136
+ tools = [
137
+ web_search,
138
+ wikipedia_search,
139
+ python_repl,
140
+ calculator,
141
+ get_task_file,
142
+ ]
143
+
144
+ self.agent = create_react_agent(
145
+ model=llm,
146
+ tools=tools,
147
+ state_modifier=SYSTEM_PROMPT,
148
+ )
149
+ print("Agent ready.")
150
+
151
  def __call__(self, question: str) -> str:
152
  print(f"Agent received question (first 50 chars): {question[:50]}...")
153
+ try:
154
+ result = self.agent.invoke({"messages": [("user", question)]})
155
+ last_message = result["messages"][-1].content
156
+
157
+ # Estrai FINAL ANSWER se presente
158
+ match = re.search(r"FINAL ANSWER:\s*(.+?)(?:\n|$)", last_message, re.IGNORECASE)
159
+ answer = match.group(1).strip() if match else last_message.strip().split("\n")[-1]
160
+
161
+ print(f"Agent returning answer: {answer}")
162
+ return answer
163
+ except Exception as e:
164
+ print(f"Agent error: {e}")
165
+ return f"AGENT ERROR: {e}"
166
 
167
  def run_and_submit_all( profile: gr.OAuthProfile | None):
168
  """