barunsaha commited on
Commit
4e29b9c
·
1 Parent(s): fdbcb87

Add app files and dependencies

Browse files
Files changed (6) hide show
  1. .gitignore +3 -0
  2. Gradio_UI.py +308 -0
  3. app.py +198 -1
  4. prompts.yaml +323 -0
  5. requirements.txt +6 -0
  6. tools/final_answer.py +16 -0
.gitignore CHANGED
@@ -1,5 +1,8 @@
1
  .idea/
2
 
 
 
 
3
 
4
  # User-specific stuff
5
  .idea/**/workspace.xml
 
1
  .idea/
2
 
3
+ .gradio/certificate.pem
4
+
5
+
6
 
7
  # User-specific stuff
8
  .idea/**/workspace.xml
Gradio_UI.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import mimetypes
17
+ import os
18
+ import re
19
+ import shutil
20
+ from typing import Optional
21
+
22
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
23
+ from smolagents.agents import ActionStep, MultiStepAgent
24
+ from smolagents.memory import MemoryStep
25
+ from smolagents.utils import _is_package_available
26
+
27
+
28
+ def pull_messages_from_step(
29
+ step_log: MemoryStep,
30
+ ):
31
+ """Extract ChatMessage objects from agent steps with proper nesting"""
32
+ import gradio as gr
33
+
34
+ if isinstance(step_log, ActionStep):
35
+ # Output the step number
36
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
+ yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
+
39
+ # First yield the thought/reasoning from the LLM
40
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
+ # Clean up the LLM output
42
+ model_output = step_log.model_output.strip()
43
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
+ model_output = model_output.strip()
48
+ yield gr.ChatMessage(role="assistant", content=model_output)
49
+
50
+ # For tool calls, create a parent message
51
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
+ first_tool_call = step_log.tool_calls[0]
53
+ used_code = first_tool_call.name == "python_interpreter"
54
+ parent_id = f"call_{len(step_log.tool_calls)}"
55
+
56
+ # Tool call becomes the parent message with timing info
57
+ # First we will handle arguments based on type
58
+ args = first_tool_call.arguments
59
+ if isinstance(args, dict):
60
+ content = str(args.get("answer", str(args)))
61
+ else:
62
+ content = str(args).strip()
63
+
64
+ if used_code:
65
+ # Clean up the content by removing any end code tags
66
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
+ content = content.strip()
69
+ if not content.startswith("```python"):
70
+ content = f"```python\n{content}\n```"
71
+
72
+ parent_message_tool = gr.ChatMessage(
73
+ role="assistant",
74
+ content=content,
75
+ metadata={
76
+ "title": f"🛠️ Used tool {first_tool_call.name}",
77
+ "id": parent_id,
78
+ "status": "pending",
79
+ },
80
+ )
81
+ yield parent_message_tool
82
+
83
+ # Nesting execution logs under the tool call if they exist
84
+ if hasattr(step_log, "observations") and (
85
+ step_log.observations is not None and step_log.observations.strip()
86
+ ): # Only yield execution logs if there's actual content
87
+ log_content = step_log.observations.strip()
88
+ if log_content:
89
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
90
+ yield gr.ChatMessage(
91
+ role="assistant",
92
+ content=f"{log_content}",
93
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
+ )
95
+
96
+ # Nesting any errors under the tool call
97
+ if hasattr(step_log, "error") and step_log.error is not None:
98
+ yield gr.ChatMessage(
99
+ role="assistant",
100
+ content=str(step_log.error),
101
+ metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
+ )
103
+
104
+ # Update parent message metadata to done status without yielding a new message
105
+ parent_message_tool.metadata["status"] = "done"
106
+
107
+ # Handle standalone errors but not from tool calls
108
+ elif hasattr(step_log, "error") and step_log.error is not None:
109
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
+
111
+ # Calculate duration and token information
112
+ step_footnote = f"{step_number}"
113
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
+ token_str = (
115
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
+ )
117
+ step_footnote += token_str
118
+ if hasattr(step_log, "duration"):
119
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
+ step_footnote += step_duration
121
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
+ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
+ yield gr.ChatMessage(role="assistant", content="-----")
124
+
125
+
126
+ def stream_to_gradio(
127
+ agent,
128
+ task: str,
129
+ reset_agent_memory: bool = False,
130
+ additional_args: Optional[dict] = None,
131
+ ):
132
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
+ if not _is_package_available("gradio"):
134
+ raise ModuleNotFoundError(
135
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
136
+ )
137
+ import gradio as gr
138
+
139
+ total_input_tokens = 0
140
+ total_output_tokens = 0
141
+
142
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
143
+ # Track tokens if model provides them
144
+ if hasattr(agent.model, "last_input_token_count"):
145
+ total_input_tokens += agent.model.last_input_token_count
146
+ total_output_tokens += agent.model.last_output_token_count
147
+ if isinstance(step_log, ActionStep):
148
+ step_log.input_token_count = agent.model.last_input_token_count
149
+ step_log.output_token_count = agent.model.last_output_token_count
150
+
151
+ for message in pull_messages_from_step(
152
+ step_log,
153
+ ):
154
+ yield message
155
+
156
+ final_answer = step_log # Last log is the run's final_answer
157
+ final_answer = handle_agent_output_types(final_answer)
158
+
159
+ if isinstance(final_answer, AgentText):
160
+ yield gr.ChatMessage(
161
+ role="assistant",
162
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
163
+ )
164
+ elif isinstance(final_answer, AgentImage):
165
+ yield gr.ChatMessage(
166
+ role="assistant",
167
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
168
+ )
169
+ elif isinstance(final_answer, AgentAudio):
170
+ yield gr.ChatMessage(
171
+ role="assistant",
172
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
173
+ )
174
+ else:
175
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
176
+
177
+
178
+ class GradioUI:
179
+ """A one-line interface to launch your agent in Gradio"""
180
+
181
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
182
+ if not _is_package_available("gradio"):
183
+ raise ModuleNotFoundError(
184
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
185
+ )
186
+ self.agent = agent
187
+ self.file_upload_folder = file_upload_folder
188
+ if self.file_upload_folder is not None:
189
+ if not os.path.exists(file_upload_folder):
190
+ os.mkdir(file_upload_folder)
191
+
192
+ def interact_with_agent(self, prompt, messages):
193
+ import gradio as gr
194
+
195
+ messages.append(gr.ChatMessage(role="user", content=prompt))
196
+ yield messages
197
+ for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
198
+ messages.append(msg)
199
+ yield messages
200
+ yield messages
201
+
202
+ def upload_file(
203
+ self,
204
+ file,
205
+ file_uploads_log,
206
+ allowed_file_types=[
207
+ "application/pdf",
208
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
209
+ "text/plain",
210
+ ],
211
+ ):
212
+ """
213
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
214
+ """
215
+ import gradio as gr
216
+
217
+ if file is None:
218
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
219
+
220
+ try:
221
+ mime_type, _ = mimetypes.guess_type(file.name)
222
+ except Exception as e:
223
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
224
+
225
+ if mime_type not in allowed_file_types:
226
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
227
+
228
+ # Sanitize file name
229
+ original_name = os.path.basename(file.name)
230
+ sanitized_name = re.sub(
231
+ r"[^\w\-.]", "_", original_name
232
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
233
+
234
+ type_to_ext = {}
235
+ for ext, t in mimetypes.types_map.items():
236
+ if t not in type_to_ext:
237
+ type_to_ext[t] = ext
238
+
239
+ # Ensure the extension correlates to the mime type
240
+ sanitized_name = sanitized_name.split(".")[:-1]
241
+ sanitized_name.append("" + type_to_ext[mime_type])
242
+ sanitized_name = "".join(sanitized_name)
243
+
244
+ # Save the uploaded file to the specified folder
245
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
246
+ shutil.copy(file.name, file_path)
247
+
248
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
249
+
250
+ def log_user_message(self, text_input, file_uploads_log):
251
+ return (
252
+ text_input
253
+ + (
254
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
255
+ if len(file_uploads_log) > 0
256
+ else ""
257
+ ),
258
+ "",
259
+ )
260
+
261
+ def launch(self, **kwargs):
262
+ import gradio as gr
263
+
264
+ with gr.Blocks(fill_height=True) as demo:
265
+ title = '''
266
+ # QoScope 🔭
267
+
268
+ QoS data analysis thousands of school networks under UNICEF/Giga.
269
+
270
+ ## Some sample queries:
271
+ - List all the countries that are there.
272
+ - How many distinct schools are there in each country? Show as a table. Sort by the country names.
273
+ - Show the average download speed and latency of each school in Kenya.
274
+ '''
275
+ gr.Markdown(title)
276
+
277
+ stored_messages = gr.State([])
278
+ file_uploads_log = gr.State([])
279
+ chatbot = gr.Chatbot(
280
+ label="Agent",
281
+ type="messages",
282
+ avatar_images=(
283
+ None,
284
+ "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
285
+ ),
286
+ resizeable=True,
287
+ scale=1,
288
+ )
289
+ # If an upload folder is provided, enable the upload feature
290
+ if self.file_upload_folder is not None:
291
+ upload_file = gr.File(label="Upload a file")
292
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
293
+ upload_file.change(
294
+ self.upload_file,
295
+ [upload_file, file_uploads_log],
296
+ [upload_status, file_uploads_log],
297
+ )
298
+ text_input = gr.Textbox(lines=1, label="Chat Message")
299
+ text_input.submit(
300
+ self.log_user_message,
301
+ [text_input, file_uploads_log],
302
+ [stored_messages, text_input],
303
+ ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
304
+
305
+ demo.launch(debug=True, share=True, **kwargs)
306
+
307
+
308
+ __all__ = ["stream_to_gradio", "GradioUI"]
app.py CHANGED
@@ -1 +1,198 @@
1
- # test
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import yaml
6
+
7
+ import sqlalchemy as sqa
8
+ from Gradio_UI import GradioUI
9
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool, Tool
10
+ from tools.final_answer import FinalAnswerTool
11
+
12
+ DATABASE_PATH = 'sqlite:///resampled_daily_avg.sqlite'
13
+
14
+ db_engine = sqa.create_engine(DATABASE_PATH, echo=False)
15
+
16
+
17
+ @tool
18
+ def run_sql_query(sql_query: str) -> str:
19
+ """
20
+ Run a SQL query on a table in a SQLite database and return the output/result as a string.
21
+ The output contains one row of result(s) in each line.
22
+ The output is simple text without any Markdown styling. An agent should take this plain output
23
+ and format appropriately when required, e.g., as a Markdown table or summarizing the results in words.
24
+
25
+ The only available table in the SQLite database is `school_measurements`.
26
+ The table's CREATE statement (DDL) is as follows:
27
+ CREATE TABLE school_measurements (
28
+ "index" BIGINT,
29
+ date DATETIME,
30
+ download_speed FLOAT,
31
+ upload_speed FLOAT,
32
+ latency FLOAT,
33
+ school_id_giga TEXT,
34
+ school_name TEXT,
35
+ server_location TEXT,
36
+ country TEXT,
37
+ iso3_format TEXT
38
+ )
39
+
40
+ IMPORTANT: You will ONLY execute SELECT queries.
41
+ You will NEVER execute any other types of SQL queries, e.g., INSERT, DELETE, DROP, and so on, which changes the database in any way.
42
+
43
+ Args:
44
+ sql_query: An appropriate, correct SQL query for a SQLite database
45
+
46
+ Returns:
47
+ The result of running the SQL query as a string.
48
+ """
49
+
50
+ # Source: https://huggingface.co/docs/smolagents/en/examples/text_to_sql
51
+
52
+ output = ''
53
+ with db_engine.connect() as con:
54
+ rows = con.execute(sqa.text(sql_query))
55
+ for row in rows:
56
+ # Each row is a tuple
57
+ print(f'\n\n>>>{row=}')
58
+ output += '\n' + str(row)
59
+
60
+ return output
61
+
62
+
63
+ # @tool
64
+ def plot_line_diagram(
65
+ x_values,
66
+ y_values_list,
67
+ labels=None,
68
+ title='Line Diagram',
69
+ xlabel='X-axis',
70
+ ylabel='Y-axis'
71
+ ):
72
+ """
73
+ Plots a line diagram with one or more y-values.
74
+
75
+ :param x_values: List of x-values.
76
+ :param y_values_list: List of lists containing y-values. Each inner list represents a separate line.
77
+ :param labels: List of labels for each line (optional).
78
+ :param title: Title of the plot (default: 'Line Diagram').
79
+ :param xlabel: Label for the X-axis (default: 'X-axis').
80
+ :param ylabel: Label for the Y-axis (default: 'Y-axis').
81
+ """
82
+ plt.figure(figsize=(10, 6))
83
+
84
+ for i, y_values in enumerate(y_values_list):
85
+ label = labels[i] if labels and i < len(labels) else f'Line {i + 1}'
86
+ plt.plot(x_values, y_values, label=label)
87
+
88
+ plt.title(title)
89
+ plt.xlabel(xlabel)
90
+ plt.ylabel(ylabel)
91
+ plt.legend()
92
+ plt.grid(True)
93
+ plt.show()
94
+
95
+
96
+ @tool
97
+ def plot_bar_diagram(
98
+ x_values: list,
99
+ y_values_list: list[list[int | float]],
100
+ labels: list[str] | None = None,
101
+ title: str = 'Bar Diagram',
102
+ xlabel: str = 'X-axis',
103
+ ylabel: str = 'Y-axis'
104
+ ) -> str:
105
+ """
106
+ Plot a bar diagram with one or more y-values and save the image to a temporary file.
107
+ Return the path to the saved image file. The path can be used to display the image.
108
+
109
+ Args:
110
+ x_values: List of x-values.
111
+ y_values_list: List of lists containing y-values. Each inner list represents a separate set of bars.
112
+ labels: List of labels for each set of bars (optional).
113
+ title: Title of the plot (default: 'Bar Diagram').
114
+ xlabel: Label for the X-axis (default: 'X-axis').
115
+ ylabel: Label for the Y-axis (default: 'Y-axis').
116
+
117
+ Returns:
118
+ Path to the saved image file.
119
+ """
120
+ bar_width = 0.2
121
+ n = len(y_values_list)
122
+
123
+ # Set positions of bars on X axis
124
+ r = [np.arange(len(x_values))]
125
+ for i in range(1, n):
126
+ r.append([x + bar_width for x in r[i - 1]])
127
+
128
+ plt.figure(figsize=(10, 6))
129
+
130
+ for i, y_values in enumerate(y_values_list):
131
+ label = labels[i] if labels and i < len(labels) else f'Set {i + 1}'
132
+ plt.bar(r[i], y_values, width=bar_width, label=label)
133
+
134
+ # Adding xticks
135
+ plt.xlabel(xlabel)
136
+ plt.ylabel(ylabel)
137
+ plt.title(title)
138
+ plt.xticks(
139
+ [r + bar_width * (n - 1) / 2 for r in range(len(x_values))],
140
+ x_values,
141
+ rotation=45,
142
+ ha='right'
143
+ )
144
+ plt.legend()
145
+ plt.grid(True, axis='y')
146
+ plt.tight_layout()
147
+
148
+ # Save the plot as an image file in a temporary directory
149
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
150
+ plt.savefig(temp_file.name)
151
+ plt.close()
152
+
153
+ return temp_file.name
154
+
155
+
156
+ # class TextToImageTool(Tool):
157
+ # description = "This tool creates an image according to a prompt, which is a text description."
158
+ # name = "image_generator"
159
+ # inputs = {"prompt": {"type": "string", "description": "The image generator prompt. Don't hesitate to add details in the prompt to make the image look better, like 'high-res, photorealistic', etc."}}
160
+ # output_type = "image"
161
+ # model_sdxl = "black-forest-labs/FLUX.1-schnell"
162
+ # client = InferenceClient(model_sdxl)
163
+ #
164
+ #
165
+ # def forward(self, prompt):
166
+ # return self.client.text_to_image(prompt)
167
+
168
+
169
+ ### Main block ###
170
+
171
+ final_answer = FinalAnswerTool()
172
+ code_model = HfApiModel(
173
+ max_tokens=2096,
174
+ temperature=0.2,
175
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
176
+ custom_role_conversions=None,
177
+ )
178
+
179
+ with open('prompts.yaml', 'r') as stream:
180
+ prompt_templates = yaml.safe_load(stream)
181
+
182
+ agent = CodeAgent(
183
+ model=code_model,
184
+ tools=[
185
+ run_sql_query,
186
+ plot_bar_diagram,
187
+ final_answer,
188
+ ],
189
+ max_steps=6,
190
+ verbosity_level=1,
191
+ grammar=None,
192
+ planning_interval=None,
193
+ name=None,
194
+ description=None,
195
+ prompt_templates=prompt_templates
196
+ )
197
+
198
+ GradioUI(agent).launch()
prompts.yaml ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ In general, these tasks relate network speed & latency measurements for millions of schools across the globe.
4
+ The data are stored in a SQLite database.
5
+ 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.
6
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
7
+
8
+ 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.
9
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
10
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
11
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
12
+ In the end you have to return a final answer using the `final_answer` tool.
13
+
14
+ Here are a few examples using notional tools:
15
+ ---
16
+ Task: "Generate an image of the oldest person in this document."
17
+
18
+ Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
19
+ Code:
20
+ ```py
21
+ answer = document_qa(document=document, question="Who is the oldest person mentioned?")
22
+ print(answer)
23
+ ```<end_code>
24
+ Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
25
+
26
+ Thought: I will now generate an image showcasing the oldest person.
27
+ Code:
28
+ ```py
29
+ image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
30
+ final_answer(image)
31
+ ```<end_code>
32
+
33
+ ---
34
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
35
+
36
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
37
+ Code:
38
+ ```py
39
+ result = 5 + 3 + 1294.678
40
+ final_answer(result)
41
+ ```<end_code>
42
+
43
+ ---
44
+ Task:
45
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
46
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
47
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
48
+
49
+ 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.
50
+ Code:
51
+ ```py
52
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
53
+ print(f"The translated question is {translated_question}.")
54
+ answer = image_qa(image=image, question=translated_question)
55
+ final_answer(f"The answer is {answer}")
56
+ ```<end_code>
57
+
58
+ ---
59
+ Task:
60
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
61
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
62
+
63
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
64
+ Code:
65
+ ```py
66
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
67
+ print(pages)
68
+ ```<end_code>
69
+ Observation:
70
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
71
+
72
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
73
+ Code:
74
+ ```py
75
+ pages = search(query="1979 interview Stanislaus Ulam")
76
+ print(pages)
77
+ ```<end_code>
78
+ Observation:
79
+ Found 6 pages:
80
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
81
+
82
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
83
+
84
+ (truncated)
85
+
86
+ Thought: I will read the first 2 pages to know more.
87
+ Code:
88
+ ```py
89
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
90
+ whole_page = visit_webpage(url)
91
+ print(whole_page)
92
+ print("\n" + "="*80 + "\n") # Print separator between pages
93
+ ```<end_code>
94
+ Observation:
95
+ Manhattan Project Locations:
96
+ Los Alamos, NM
97
+ 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
98
+ (truncated)
99
+
100
+ 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.
101
+ Code:
102
+ ```py
103
+ final_answer("diminished")
104
+ ```<end_code>
105
+
106
+ ---
107
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
108
+
109
+ 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.
110
+ Code:
111
+ ```py
112
+ for city in ["Guangzhou", "Shanghai"]:
113
+ print(f"Population {city}:", search(f"{city} population")
114
+ ```<end_code>
115
+ Observation:
116
+ Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
117
+ Population Shanghai: '26 million (2019)'
118
+
119
+ Thought: Now I know that Shanghai has the highest population.
120
+ Code:
121
+ ```py
122
+ final_answer("Shanghai")
123
+ ```<end_code>
124
+
125
+ ---
126
+ Task: "What is the current age of the pope, raised to the power 0.36?"
127
+
128
+ Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
129
+ Code:
130
+ ```py
131
+ pope_age_wiki = wiki(query="current pope age")
132
+ print("Pope age as per wikipedia:", pope_age_wiki)
133
+ pope_age_search = web_search(query="current pope age")
134
+ print("Pope age as per google search:", pope_age_search)
135
+ ```<end_code>
136
+ Observation:
137
+ Pope age: "The pope Francis is currently 88 years old."
138
+
139
+ Thought: I know that the pope is 88 years old. Let's compute the result using python code.
140
+ Code:
141
+ ```py
142
+ pope_current_age = 88 ** 0.36
143
+ final_answer(pope_current_age)
144
+ ```<end_code>
145
+
146
+ 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:
147
+ {%- for tool in tools.values() %}
148
+ - {{ tool.name }}: {{ tool.description }}
149
+ Takes inputs: {{tool.inputs}}
150
+ Returns an output of type: {{tool.output_type}}
151
+ {%- endfor %}
152
+
153
+ {%- if managed_agents and managed_agents.values() | list %}
154
+ You can also give tasks to team members.
155
+ 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.
156
+ Given that this team member is a real human, you should be very verbose in your task.
157
+ Here is a list of the team members that you can call:
158
+ {%- for agent in managed_agents.values() %}
159
+ - {{ agent.name }}: {{ agent.description }}
160
+ {%- endfor %}
161
+ {%- else %}
162
+ {%- endif %}
163
+
164
+ Here are the rules you should always follow to solve your task:
165
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
166
+ 2. Use only variables that you have defined!
167
+ 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?")'.
168
+ 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.
169
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
170
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
171
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
172
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
173
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
174
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
175
+
176
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
177
+ "planning":
178
+ "initial_facts": |-
179
+ Below I will present you a task.
180
+
181
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
182
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
183
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
184
+
185
+ ---
186
+ ### 1. Facts given in the task
187
+ List here the specific facts given in the task that could help you (there might be nothing here).
188
+
189
+ ### 2. Facts to look up
190
+ List here any facts that we may need to look up.
191
+ 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.
192
+
193
+ ### 3. Facts to derive
194
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
195
+
196
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
197
+ ### 1. Facts given in the task
198
+ ### 2. Facts to look up
199
+ ### 3. Facts to derive
200
+ Do not add anything else.
201
+ "initial_plan": |-
202
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
203
+
204
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
205
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
206
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
207
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
208
+
209
+ Here is your task:
210
+
211
+ Task:
212
+ ```
213
+ {{task}}
214
+ ```
215
+ You can leverage these tools:
216
+ {%- for tool in tools.values() %}
217
+ - {{ tool.name }}: {{ tool.description }}
218
+ Takes inputs: {{tool.inputs}}
219
+ Returns an output of type: {{tool.output_type}}
220
+ {%- endfor %}
221
+
222
+ {%- if managed_agents and managed_agents.values() | list %}
223
+ You can also give tasks to team members.
224
+ 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.
225
+ Given that this team member is a real human, you should be very verbose in your request.
226
+ Here is a list of the team members that you can call:
227
+ {%- for agent in managed_agents.values() %}
228
+ - {{ agent.name }}: {{ agent.description }}
229
+ {%- endfor %}
230
+ {%- else %}
231
+ {%- endif %}
232
+
233
+ List of facts that you know:
234
+ ```
235
+ {{answer_facts}}
236
+ ```
237
+
238
+ Now begin! Write your plan below.
239
+ "update_facts_pre_messages": |-
240
+ You are a world expert at gathering known and unknown facts based on a conversation.
241
+ 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:
242
+ ### 1. Facts given in the task
243
+ ### 2. Facts that we have learned
244
+ ### 3. Facts still to look up
245
+ ### 4. Facts still to derive
246
+ Find the task and history below:
247
+ "update_facts_post_messages": |-
248
+ Earlier we've built a list of facts.
249
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
250
+ Please update your list of facts based on the previous history, and provide these headings:
251
+ ### 1. Facts given in the task
252
+ ### 2. Facts that we have learned
253
+ ### 3. Facts still to look up
254
+ ### 4. Facts still to derive
255
+
256
+ Now write your new list of facts below.
257
+ "update_plan_pre_messages": |-
258
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
259
+
260
+ You have been given a task:
261
+ ```
262
+ {{task}}
263
+ ```
264
+
265
+ 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.
266
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
267
+ If you are stalled, you can make a completely new plan starting from scratch.
268
+ "update_plan_post_messages": |-
269
+ You're still working towards solving this task:
270
+ ```
271
+ {{task}}
272
+ ```
273
+
274
+ You can leverage these tools:
275
+ {%- for tool in tools.values() %}
276
+ - {{ tool.name }}: {{ tool.description }}
277
+ Takes inputs: {{tool.inputs}}
278
+ Returns an output of type: {{tool.output_type}}
279
+ {%- endfor %}
280
+
281
+ {%- if managed_agents and managed_agents.values() | list %}
282
+ You can also give tasks to team members.
283
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
284
+ 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.
285
+ Here is a list of the team members that you can call:
286
+ {%- for agent in managed_agents.values() %}
287
+ - {{ agent.name }}: {{ agent.description }}
288
+ {%- endfor %}
289
+ {%- else %}
290
+ {%- endif %}
291
+
292
+ Here is the up to date list of facts that you know:
293
+ ```
294
+ {{facts_update}}
295
+ ```
296
+
297
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
298
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
299
+ Beware that you have {remaining_steps} steps remaining.
300
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
301
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
302
+
303
+ Now write your new plan below.
304
+ "managed_agent":
305
+ "task": |-
306
+ You're a helpful agent named '{{name}}'.
307
+ You have been submitted this task by your manager.
308
+ ---
309
+ Task:
310
+ {{task}}
311
+ ---
312
+ 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.
313
+
314
+ Your final_answer WILL HAVE to contain these parts:
315
+ ### 1. Task outcome (short version):
316
+ ### 2. Task outcome (extremely detailed version):
317
+ ### 3. Additional context (if relevant):
318
+
319
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
320
+ 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.
321
+ "report": |-
322
+ Here is the final answer from your managed agent '{{name}}':
323
+ {{final_answer}}
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ markdownify
2
+ smolagents
3
+ pandas
4
+ SQLAlchemy
5
+ gradio
6
+ matplotlib
tools/final_answer.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from smolagents.tools import Tool
3
+
4
+ class FinalAnswerTool(Tool):
5
+ name = 'final_answer'
6
+ description = 'Provides a final answer to the given problem.'
7
+ inputs = {
8
+ 'answer': {'type': 'any', 'description': 'The final answer to the problem'}
9
+ }
10
+ output_type = 'any'
11
+
12
+ def forward(self, answer: Any) -> Any:
13
+ return answer
14
+
15
+ def __init__(self, *args, **kwargs):
16
+ self.is_initialized = False