marcos-banik commited on
Commit
6dd8cb8
·
1 Parent(s): 81917a3

♻️ Add some tools

Browse files
Files changed (4) hide show
  1. app.py +161 -45
  2. prompts.yaml +303 -0
  3. pyproject.toml +2 -0
  4. requirements.txt +3 -1
app.py CHANGED
@@ -1,34 +1,104 @@
 
1
  import os
 
2
  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
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -40,7 +110,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
 
 
 
 
 
 
 
 
 
 
 
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
@@ -55,16 +136,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -80,19 +161,39 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
93
 
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
98
 
@@ -113,10 +214,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
113
  results_df = pd.DataFrame(results_log)
114
  return final_status, results_df
115
  except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
 
 
117
  try:
118
  error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
 
 
120
  except requests.exceptions.JSONDecodeError:
121
  error_detail += f" Response: {e.response.text[:500]}"
122
  status_message = f"Submission Failed: {error_detail}"
@@ -162,35 +267,46 @@ with gr.Blocks() as demo:
162
 
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
 
166
  # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
168
 
169
  run_button.click(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
  )
173
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
  # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
 
 
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
 
 
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
  print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
+ from typing import Any
2
  import os
3
+ import yaml
4
  import gradio as gr
 
 
5
  import pandas as pd
6
+ import requests
7
+ from smolagents import (
8
+ CodeAgent,
9
+ Tool,
10
+ Model,
11
+ PromptTemplates,
12
+ FinalAnswerTool,
13
+ HfApiModel,
14
+ VisitWebpageTool,
15
+ WebSearchTool,
16
+ WikipediaSearchTool,
17
+ )
18
 
19
  # (Keep Constants as is)
20
  # --- Constants ---
21
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
 
23
+ final_answer = FinalAnswerTool
24
+ web_search = WebSearchTool(engine="bing")
25
+ visit_webpage = VisitWebpageTool
26
+ wiki_search = WikipediaSearchTool()
27
+
28
+ model = HfApiModel(
29
+ max_tokens=2096,
30
+ temperature=0.5,
31
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
32
+ custom_role_conversions=None,
33
+ )
34
+
35
+ with open("prompts.yaml", "r") as stream:
36
+ prompt_templates = yaml.safe_load(stream)
37
+
38
+
39
+ class GaiaAgent(CodeAgent):
40
+ def __init__(
41
+ self,
42
+ api_url: str,
43
+ tools: list[Tool],
44
+ model: Model,
45
+ prompt_templates: PromptTemplates | None = None,
46
+ additional_authorized_imports: list[str] | None = None,
47
+ planning_interval: int | None = None,
48
+ executor_type: str | None = "local",
49
+ executor_kwargs: dict[str, Any] | None = None,
50
+ max_print_outputs_length: int | None = None,
51
+ stream_outputs: bool = False,
52
+ use_structured_outputs_internally: bool = False,
53
+ grammar: dict[str, str] | None = None,
54
+ **kwargs,
55
+ ):
56
+ super().__init__(
57
+ tools=tools,
58
+ model=model,
59
+ prompt_templates=prompt_templates,
60
+ additional_authorized_imports=additional_authorized_imports,
61
+ planning_interval=planning_interval,
62
+ executor_type=executor_type,
63
+ executor_kwargs=executor_kwargs,
64
+ max_print_outputs_length=max_print_outputs_length,
65
+ use_structured_outputs_internally=use_structured_outputs_internally,
66
+ grammar=grammar,
67
+ **kwargs,
68
+ )
69
+ self._files_base_url = f"{api_url}/files"
70
+
71
+ def __call__(self, item: dict) -> str:
72
+ question = item["question"]
73
+ task_id = item["task_id"]
74
+ file_name = item["file_name"]
75
+ if file_name:
76
+ url = f"{self._files_base_url}/{task_id}"
77
+ resp = requests.get(url, timeout=30)
78
+ resp.raise_for_status()
79
+ content = resp.content
80
+ return super().run(
81
+ question,
82
+ additional_args={
83
+ "file_content": content,
84
+ "file_name": file_name,
85
+ },
86
+ )
87
+ return super().run(question)
88
+
89
+
90
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
91
  """
92
  Fetches all questions, runs the BasicAgent on them, submits all answers,
93
  and displays the results.
94
  """
95
  # --- Determine HF Space Runtime URL and Repo URL ---
96
+ space_id = os.getenv(
97
+ "SPACE_ID"
98
+ ) # Get the SPACE_ID for sending link to the code
99
 
100
  if profile:
101
+ username = f"{profile.username}"
102
  print(f"User logged in: {username}")
103
  else:
104
  print("User not logged in.")
 
110
 
111
  # 1. Instantiate Agent ( modify this part to create your agent)
112
  try:
113
+ agent = GaiaAgent(
114
+ api_url,
115
+ model=model,
116
+ tools=[final_answer, web_search, visit_webpage, wiki_search],
117
+ max_steps=6,
118
+ verbosity_level=1,
119
+ grammar=None,
120
+ planning_interval=None,
121
+ name=None,
122
+ description=None,
123
+ prompt_templates=prompt_templates,
124
+ )
125
  except Exception as e:
126
  print(f"Error instantiating agent: {e}")
127
  return f"Error initializing agent: {e}", None
 
136
  response.raise_for_status()
137
  questions_data = response.json()
138
  if not questions_data:
139
+ print("Fetched questions list is empty.")
140
+ return "Fetched questions list is empty or invalid format.", None
141
  print(f"Fetched {len(questions_data)} questions.")
142
  except requests.exceptions.RequestException as e:
143
  print(f"Error fetching questions: {e}")
144
  return f"Error fetching questions: {e}", None
145
  except requests.exceptions.JSONDecodeError as e:
146
+ print(f"Error decoding JSON response from questions endpoint: {e}")
147
+ print(f"Response text: {response.text[:500]}")
148
+ return f"Error decoding server response for questions: {e}", None
149
  except Exception as e:
150
  print(f"An unexpected error occurred fetching questions: {e}")
151
  return f"An unexpected error occurred fetching questions: {e}", None
 
161
  print(f"Skipping item with missing task_id or question: {item}")
162
  continue
163
  try:
164
+ submitted_answer = agent(item)
165
+ answers_payload.append(
166
+ {"task_id": task_id, "submitted_answer": submitted_answer}
167
+ )
168
+ results_log.append(
169
+ {
170
+ "Task ID": task_id,
171
+ "Question": question_text,
172
+ "Submitted Answer": submitted_answer,
173
+ }
174
+ )
175
  except Exception as e:
176
+ print(f"Error running agent on task {task_id}: {e}")
177
+ results_log.append(
178
+ {
179
+ "Task ID": task_id,
180
+ "Question": question_text,
181
+ "Submitted Answer": f"AGENT ERROR: {e}",
182
+ }
183
+ )
184
 
185
  if not answers_payload:
186
  print("Agent did not produce any answers to submit.")
187
+ return "Agent did not produce any answers to submit.", pd.DataFrame(
188
+ results_log
189
+ )
190
 
191
+ # 4. Prepare Submission
192
+ submission_data = {
193
+ "username": username.strip(),
194
+ "agent_code": agent_code,
195
+ "answers": answers_payload,
196
+ }
197
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
198
  print(status_update)
199
 
 
214
  results_df = pd.DataFrame(results_log)
215
  return final_status, results_df
216
  except requests.exceptions.HTTPError as e:
217
+ error_detail = (
218
+ f"Server responded with status {e.response.status_code}."
219
+ )
220
  try:
221
  error_json = e.response.json()
222
+ error_detail += (
223
+ f" Detail: {error_json.get('detail', e.response.text)}"
224
+ )
225
  except requests.exceptions.JSONDecodeError:
226
  error_detail += f" Response: {e.response.text[:500]}"
227
  status_message = f"Submission Failed: {error_detail}"
 
267
 
268
  run_button = gr.Button("Run Evaluation & Submit All Answers")
269
 
270
+ status_output = gr.Textbox(
271
+ label="Run Status / Submission Result", lines=5, interactive=False
272
+ )
273
  # Removed max_rows=10 from DataFrame constructor
274
+ results_table = gr.DataFrame(
275
+ label="Questions and Agent Answers", wrap=True
276
+ )
277
 
278
  run_button.click(
279
+ fn=run_and_submit_all, outputs=[status_output, results_table]
 
280
  )
281
 
282
  if __name__ == "__main__":
283
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
284
  # Check for SPACE_HOST and SPACE_ID at startup for information
285
  space_host_startup = os.getenv("SPACE_HOST")
286
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
287
 
288
  if space_host_startup:
289
  print(f"✅ SPACE_HOST found: {space_host_startup}")
290
+ print(
291
+ f" Runtime URL should be: https://{space_host_startup}.hf.space"
292
+ )
293
  else:
294
+ print(
295
+ "ℹ️ SPACE_HOST environment variable not found (running locally?)."
296
+ )
297
 
298
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
299
  print(f"✅ SPACE_ID found: {space_id_startup}")
300
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
301
+ print(
302
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
303
+ )
304
  else:
305
+ print(
306
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
307
+ )
308
 
309
+ print("-" * (60 + len(" App Starting ")) + "\n")
310
 
311
  print("Launching Gradio Interface for Basic Agent Evaluation...")
312
+ demo.launch(debug=True, share=False)
prompts.yaml ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "system_prompt": |-
2
+ You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
3
+ To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
4
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
5
+
6
+ At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
7
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
8
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
9
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
10
+ In the end you have to return a final answer using the `final_answer` tool.
11
+
12
+ Here are a few examples using notional tools:
13
+ ---
14
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
15
+
16
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
17
+ Code:
18
+ ```py
19
+ result = 5 + 3 + 1294.678
20
+ final_answer(result)
21
+ ```<end_code>
22
+
23
+ ---
24
+ Task:
25
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
26
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
27
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
28
+
29
+ Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
30
+ Code:
31
+ ```py
32
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
33
+ print(f"The translated question is {translated_question}.")
34
+ answer = image_qa(image=image, question=translated_question)
35
+ final_answer(answer)
36
+ ```<end_code>
37
+
38
+ ---
39
+ Task:
40
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
41
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
42
+
43
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
44
+ Code:
45
+ ```py
46
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
47
+ print(pages)
48
+ ```<end_code>
49
+ Observation:
50
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
51
+
52
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
53
+ Code:
54
+ ```py
55
+ pages = search(query="1979 interview Stanislaus Ulam")
56
+ print(pages)
57
+ ```<end_code>
58
+ Observation:
59
+ Found 6 pages:
60
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
61
+
62
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
63
+
64
+ (truncated)
65
+
66
+ Thought: I will read the first 2 pages to know more.
67
+ Code:
68
+ ```py
69
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
70
+ whole_page = visit_webpage(url)
71
+ print(whole_page)
72
+ print("\n" + "="*80 + "\n") # Print separator between pages
73
+ ```<end_code>
74
+ Observation:
75
+ Manhattan Project Locations:
76
+ Los Alamos, NM
77
+ Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
78
+ (truncated)
79
+
80
+ Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
81
+ Code:
82
+ ```py
83
+ final_answer("diminished")
84
+ ```<end_code>
85
+
86
+ ---
87
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
88
+
89
+ Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
90
+ Code:
91
+ ```py
92
+ for city in ["Guangzhou", "Shanghai"]:
93
+ print(f"Population {city}:", search(f"{city} population")
94
+ ```<end_code>
95
+ Observation:
96
+ Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
97
+ Population Shanghai: '26 million (2019)'
98
+
99
+ Thought: Now I know that Shanghai has the highest population.
100
+ Code:
101
+ ```py
102
+ final_answer("Shanghai")
103
+ ```<end_code>
104
+
105
+ ---
106
+ Task: "What is the current age of the pope, raised to the power 0.36?"
107
+
108
+ Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
109
+ Code:
110
+ ```py
111
+ pope_age_wiki = wiki(query="current pope age")
112
+ print("Pope age as per wikipedia:", pope_age_wiki)
113
+ pope_age_search = web_search(query="current pope age")
114
+ print("Pope age as per google search:", pope_age_search)
115
+ ```<end_code>
116
+ Observation:
117
+ Pope age: "The pope Francis is currently 88 years old."
118
+
119
+ Thought: I know that the pope is 88 years old. Let's compute the result using python code.
120
+ Code:
121
+ ```py
122
+ pope_current_age = 88 ** 0.36
123
+ final_answer(pope_current_age)
124
+ ```<end_code>
125
+
126
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
127
+ {%- for tool in tools.values() %}
128
+ - {{ tool.name }}: {{ tool.description }}
129
+ Takes inputs: {{tool.inputs}}
130
+ Returns an output of type: {{tool.output_type}}
131
+ {%- endfor %}
132
+
133
+ {%- if managed_agents and managed_agents.values() | list %}
134
+ You can also give tasks to team members.
135
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
136
+ Given that this team member is a real human, you should be very verbose in your task.
137
+ Here is a list of the team members that you can call:
138
+ {%- for agent in managed_agents.values() %}
139
+ - {{ agent.name }}: {{ agent.description }}
140
+ {%- endfor %}
141
+ {%- else %}
142
+ {%- endif %}
143
+
144
+ Here are the rules you should always follow to solve your task:
145
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
146
+ 2. Use only variables that you have defined!
147
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
148
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
149
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
150
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
151
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
152
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
153
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
154
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
155
+
156
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
157
+ "planning":
158
+ "initial_facts": |-
159
+ Below I will present you a task.
160
+
161
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
162
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
163
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
164
+
165
+ ---
166
+ ### 1. Facts given in the task
167
+ List here the specific facts given in the task that could help you (there might be nothing here).
168
+
169
+ ### 2. Facts to look up
170
+ List here any facts that we may need to look up.
171
+ Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
172
+
173
+ ### 3. Facts to derive
174
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
175
+
176
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
177
+ ### 1. Facts given in the task
178
+ ### 2. Facts to look up
179
+ ### 3. Facts to derive
180
+ Do not add anything else.
181
+ "initial_plan": |-
182
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
183
+
184
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
185
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
186
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
187
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
188
+
189
+ Here is your task:
190
+
191
+ Task:
192
+ ```
193
+ {{task}}
194
+ ```
195
+ You can leverage these tools:
196
+ {%- for tool in tools.values() %}
197
+ - {{ tool.name }}: {{ tool.description }}
198
+ Takes inputs: {{tool.inputs}}
199
+ Returns an output of type: {{tool.output_type}}
200
+ {%- endfor %}
201
+
202
+ {%- if managed_agents and managed_agents.values() | list %}
203
+ You can also give tasks to team members.
204
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
205
+ Given that this team member is a real human, you should be very verbose in your request.
206
+ Here is a list of the team members that you can call:
207
+ {%- for agent in managed_agents.values() %}
208
+ - {{ agent.name }}: {{ agent.description }}
209
+ {%- endfor %}
210
+ {%- else %}
211
+ {%- endif %}
212
+
213
+ List of facts that you know:
214
+ ```
215
+ {{answer_facts}}
216
+ ```
217
+
218
+ Now begin! Write your plan below.
219
+ "update_facts_pre_messages": |-
220
+ You are a world expert at gathering known and unknown facts based on a conversation.
221
+ Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
222
+ ### 1. Facts given in the task
223
+ ### 2. Facts that we have learned
224
+ ### 3. Facts still to look up
225
+ ### 4. Facts still to derive
226
+ Find the task and history below:
227
+ "update_facts_post_messages": |-
228
+ Earlier we've built a list of facts.
229
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
230
+ Please update your list of facts based on the previous history, and provide these headings:
231
+ ### 1. Facts given in the task
232
+ ### 2. Facts that we have learned
233
+ ### 3. Facts still to look up
234
+ ### 4. Facts still to derive
235
+
236
+ Now write your new list of facts below.
237
+ "update_plan_pre_messages": |-
238
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
239
+
240
+ You have been given a task:
241
+ ```
242
+ {{task}}
243
+ ```
244
+
245
+ Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
246
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
247
+ If you are stalled, you can make a completely new plan starting from scratch.
248
+ "update_plan_post_messages": |-
249
+ You're still working towards solving this task:
250
+ ```
251
+ {{task}}
252
+ ```
253
+
254
+ You can leverage these tools:
255
+ {%- for tool in tools.values() %}
256
+ - {{ tool.name }}: {{ tool.description }}
257
+ Takes inputs: {{tool.inputs}}
258
+ Returns an output of type: {{tool.output_type}}
259
+ {%- endfor %}
260
+
261
+ {%- if managed_agents and managed_agents.values() | list %}
262
+ You can also give tasks to team members.
263
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
264
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
265
+ Here is a list of the team members that you can call:
266
+ {%- for agent in managed_agents.values() %}
267
+ - {{ agent.name }}: {{ agent.description }}
268
+ {%- endfor %}
269
+ {%- else %}
270
+ {%- endif %}
271
+
272
+ Here is the up to date list of facts that you know:
273
+ ```
274
+ {{facts_update}}
275
+ ```
276
+
277
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
278
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
279
+ Beware that you have {remaining_steps} steps remaining.
280
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
281
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
282
+
283
+ Now write your new plan below.
284
+ "managed_agent":
285
+ "task": |-
286
+ You're a helpful agent named '{{name}}'.
287
+ You have been submitted this task by your manager.
288
+ ---
289
+ Task:
290
+ {{task}}
291
+ ---
292
+ You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
293
+
294
+ Your final_answer WILL HAVE to contain these parts:
295
+ ### 1. Task outcome (short version):
296
+ ### 2. Task outcome (extremely detailed version):
297
+ ### 3. Additional context (if relevant):
298
+
299
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
300
+ And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
301
+ "report": |-
302
+ Here is the final answer from your managed agent '{{name}}':
303
+ {{final_answer}}
pyproject.toml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [tool.ruff]
2
+ line-length = 79
requirements.txt CHANGED
@@ -1,2 +1,4 @@
1
  gradio
2
- requests
 
 
 
1
  gradio
2
+ requests
3
+ smolagents[toolkit]
4
+ wikipedia-api