Mahdiyar commited on
Commit
78098b8
·
1 Parent(s): fd81fb2

Add initial implementation of TinyCodeAgent with Python code execution capabilities

Browse files

- Introduced `app.py` for the main application logic, including a Python code interpreter and tools for weather and traffic information.
- Created `helper.py` for utility functions related to tool translation and template rendering.
- Updated `README.md` to include an overview of TinyCodeAgent and its benefits.
- Added `requirements.txt` for necessary dependencies.
- Included `code_agent.yml` for system prompts and task handling structure.
- Established a logging system for better debugging and monitoring of operations.

Files changed (5) hide show
  1. README.md +35 -0
  2. app.py +365 -0
  3. helper.py +151 -0
  4. prompts/code_agent.yml +329 -0
  5. requirements.txt +5 -0
README.md CHANGED
@@ -12,3 +12,38 @@ short_description: Think in python and execute code to solve a task
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
15
+
16
+
17
+
18
+ ## TinyCodeAgent
19
+
20
+ TinyCodeAgent is an extention to [TinyAgent](https://github.com/askbudi/tinyagent) that think in python and allows you to execute python code to solve a task.
21
+
22
+ You can extend it using TinyAgent Hooks system, and use it with Gradio Integration.
23
+ Your agent could become a MCP Server or tool for another agent.
24
+
25
+ ## Benefits
26
+ - Stateful python code using Modal Functions (Instead of using a sandbox, Faster and cheaper)
27
+ - Use TinyAgent Hooks system to extend your agent
28
+ - Use Gradio Integration to use your agent as a tool for another agent
29
+ - Log System
30
+ - Storage
31
+ - Multi MCP Connections
32
+
33
+
34
+
35
+
36
+ ## Credits
37
+
38
+ - [TinyAgent](https://github.com/askbudi/tinyagent) I have built this project as well.
39
+ - [Modal](https://modal.com/) I use Modal Functions to run python code.
40
+ - [Gradio](https://gradio.app/) I use Gradio to create a web interface for my agent.
41
+ - [Cloudpickle](https://github.com/cloudpipe/cloudpickle) I use Cloudpickle to serialize and deserialize python objects.
42
+ - [SmolAgents](https://github.com/huggingface/smolagents) Use SmolAgents Coding Agent System Prompt as a base for my system prompt.
43
+
44
+
45
+
46
+
47
+
48
+
49
+
app.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from tinyagent import tool
3
+ from textwrap import dedent
4
+ from typing import Optional, List, Dict, Any,Union
5
+ from tinyagent.hooks.logging_manager import LoggingManager
6
+ import modal
7
+ import cloudpickle
8
+
9
+
10
+ def clean_response(resp):
11
+ return {k:v for k,v in resp.items() if k in ['printed_output','return_value','stderr','error_traceback']}
12
+
13
+ def make_session_blob(ns: dict) -> bytes:
14
+ clean = {}
15
+ for name, val in ns.items():
16
+ try:
17
+ # Try serializing just this one object
18
+ cloudpickle.dumps(val)
19
+ except Exception:
20
+ # drop anything that fails
21
+ continue
22
+ else:
23
+ clean[name] = val
24
+
25
+ return cloudpickle.dumps(clean)
26
+
27
+ def _run_python(code: str,globals_dict:Dict[str,Any]={},locals_dict:Dict[str,Any]={}):
28
+
29
+ import contextlib
30
+ import traceback
31
+ import io
32
+ import ast
33
+
34
+ # Make copies to avoid mutating the original parameters
35
+ updated_globals = globals_dict.copy()
36
+ updated_locals = locals_dict.copy()
37
+
38
+ tree = ast.parse(code, mode="exec")
39
+ compiled = compile(tree, filename="<ast>", mode="exec")
40
+ stdout_buf = io.StringIO()
41
+ stderr_buf = io.StringIO()
42
+
43
+ # --- 4. Execute with stdout+stderr capture and exception handling ---
44
+ error_traceback = None
45
+ output = None
46
+
47
+ with contextlib.redirect_stdout(stdout_buf), contextlib.redirect_stderr(stderr_buf):
48
+ try:
49
+ output = exec(code, updated_globals, updated_locals)
50
+ except Exception:
51
+ # Capture the full traceback as a string
52
+ error_traceback = traceback.format_exc()
53
+
54
+
55
+ printed_output = stdout_buf.getvalue()
56
+ stderr_output = stderr_buf.getvalue()
57
+ error_traceback_output = error_traceback
58
+
59
+ return {
60
+ "printed_output": printed_output,
61
+ "return_value": output,
62
+ "stderr": stderr_output,
63
+ "error_traceback": error_traceback_output,
64
+ "updated_globals": updated_globals,
65
+ "updated_locals": updated_locals
66
+ }
67
+
68
+
69
+ class PythonCodeInterpreter:
70
+ executed_default_codes = False
71
+ PYTHON_VERSION = "3.11"
72
+
73
+ app = None
74
+ _app_run_python = None
75
+ _globals_dict = {}
76
+ _locals_dict = {}
77
+ def __init__(self,log_manager: LoggingManager,
78
+ default_python_codes:Optional[List[str]]=[],
79
+ code_tools:List[Dict[str,Any]]=[],
80
+ pip_packages:List[str]=[],
81
+ modal_secrets:Dict[str,Union[str,None]]={},
82
+ lazy_init:bool=True,
83
+ **kwargs):
84
+ self.log_manager = log_manager
85
+ self.code_tools = code_tools
86
+
87
+ self._globals_dict.update(**kwargs.get("globals_dict",{}))
88
+ self._locals_dict.update(**kwargs.get("locals_dict",{}))
89
+
90
+ self.default_python_codes = default_python_codes
91
+
92
+ self.modal_secrets = modal.Secret.from_dict(modal_secrets)
93
+ self.pip_packages = list(set(["cloudpickle"]+pip_packages))
94
+ self.lazy_init = lazy_init
95
+ self.create_app(self.modal_secrets,self.pip_packages,self.code_tools)
96
+ if not self.lazy_init:
97
+ self.sandbox = self.create_sandbox(modal_secrets,pip_packages,self.code_tools)
98
+
99
+ def create_app(self,modal_secrets:Dict[str,Union[str,None]],pip_packages:List[str]=[],code_tools:List[Dict[str,Any]]=[]):
100
+
101
+ agent_image = modal.Image.debian_slim(python_version=self.PYTHON_VERSION).pip_install(
102
+ "tinyagent-py[all]==0.0.6",
103
+ "gradio",
104
+ "arize-phoenix-otel",
105
+ *pip_packages
106
+ )
107
+ self.app = modal.App(
108
+ name=self.sandbox_name,
109
+ image=agent_image,
110
+ secrets=[modal_secrets]
111
+ )
112
+ self._app_run_python = self.app.function()(_run_python)
113
+ self.add_tools(code_tools)
114
+ return self.app
115
+
116
+
117
+ def add_tools(self,tools):
118
+
119
+ tools_str_list = ["import cloudpickle"]
120
+ tools_str_list.append("###########<tools>###########\n")
121
+ for tool in tools:
122
+ tools_str_list.append(f"globals()['{tool._tool_metadata['name']}'] = cloudpickle.loads( {cloudpickle.dumps(tool)})")
123
+ tools_str_list.append("\n\n")
124
+ tools_str_list.append("###########</tools>###########\n")
125
+ tools_str_list.append("\n\n")
126
+ self.default_python_codes.extend(tools_str_list)
127
+
128
+
129
+ def _python_executor(self,code: str,globals_dict:Dict[str,Any]={},locals_dict:Dict[str,Any]={}):
130
+ with self.app.run():
131
+ if self.executed_default_codes:
132
+ print("✔️ default codes already executed")
133
+ full_code = code
134
+ else:
135
+ full_code = "\n".join(self.default_python_codes)+ "\n\n"+(code)
136
+ self.executed_default_codes = True
137
+ return self._app_run_python.remote(full_code,globals_dict,locals_dict)
138
+
139
+
140
+ @tool(name="run_python",description=dedent("""
141
+ This tool receive python code, and execute it,
142
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
143
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
144
+
145
+
146
+ Args:
147
+ code_lines: list[str]: The python code to execute, it should be a valid python code, and it should be able to run without any errors.
148
+ Your code should be include all the steps neccesary for successful run, cover edge cases, error handling
149
+ In case of an error, you will see the error, so get the most out of print function to debug your code.
150
+ Each line of code should be an independent line of code, and it should be able to run without any errors.
151
+
152
+ Returns:
153
+ Status of code execution or error message.
154
+
155
+ """))
156
+
157
+ async def run_python(self,code_lines:list[str],timeout:int=120) -> str:
158
+
159
+
160
+
161
+ if type(code_lines) == str:
162
+ code_lines = [code_lines]
163
+ code = code_lines
164
+
165
+ full_code = "\n".join(code)
166
+ print("##"*50)
167
+ print("#########################code#########################")
168
+ print(full_code)
169
+ print("##"*50)
170
+
171
+ response = self._python_executor(full_code,self._globals_dict,self._locals_dict)
172
+ print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<response>!!!!!!!!!!!!!!!!!!!!!!!!!")
173
+ # Update the instance globals and locals with the execution results
174
+ self._globals_dict = cloudpickle.loads(make_session_blob(response["updated_globals"]))
175
+ self._locals_dict = cloudpickle.loads(make_session_blob(response["updated_locals"]))
176
+
177
+ print("#########################<printed_output>#########################")
178
+ print(response["printed_output"])
179
+ print("#########################</printed_output>#########################")
180
+ print("#########################<return_value>#########################")
181
+ print(response["return_value"])
182
+ print("#########################</return_value>#########################")
183
+ print("#########################<stderr>#########################")
184
+ print(response["stderr"])
185
+ print("#########################</stderr>#########################")
186
+ print("#########################<traceback>#########################")
187
+ print(response["error_traceback"])
188
+ print("#########################</traceback>#########################")
189
+
190
+ return clean_response(response)
191
+
192
+
193
+
194
+ weather_global = '-'
195
+ traffic_global = '-'
196
+
197
+ @tool(name="get_weather",description="Get the weather for a given city.")
198
+ def get_weather(city: str)->str:
199
+ """Get the weather for a given city.
200
+ Args:
201
+ city: The city to get the weather for
202
+
203
+ Returns:
204
+ The weather for the given city
205
+ """
206
+ import random
207
+ global weather_global
208
+ output = f"Last time weather was checked was {weather_global}"
209
+ weather_global = random.choice(['sunny','cloudy','rainy','snowy'])
210
+ output += f"\n\nThe weather in {city} is now {weather_global}"
211
+
212
+ return output
213
+
214
+
215
+ @tool(name="get_traffic",description="Get the traffic for a given city.")
216
+ def get_traffic(city: str)->str:
217
+ """Get the traffic for a given city.
218
+ Args:
219
+ city: The city to get the traffic for
220
+
221
+ Returns:
222
+ The traffic for the given city
223
+ """
224
+ import random
225
+ global traffic_global
226
+ output = f"Last time traffic was checked was {traffic_global}"
227
+ traffic_global = random.choice(['light','moderate','heavy','blocked'])
228
+ output += f"\n\nThe traffic in {city} is now {traffic_global}"
229
+
230
+ return output
231
+
232
+
233
+
234
+ async def run_example():
235
+ """Example usage of GradioCallback with TinyAgent."""
236
+ import os
237
+ import sys
238
+ import tempfile
239
+ import shutil
240
+ import asyncio
241
+ from tinyagent import TinyAgent # Assuming TinyAgent is importable
242
+ from tinyagent.hooks.logging_manager import LoggingManager # Assuming LoggingManager exists
243
+ from tinyagent.hooks.gradio_callback import GradioCallback
244
+ import logging
245
+
246
+
247
+ # --- Logging Setup (Simplified) ---
248
+ log_manager = LoggingManager(default_level=logging.INFO)
249
+ log_manager.set_levels({
250
+ 'tinyagent.hooks.gradio_callback': logging.DEBUG,
251
+ 'tinyagent.tiny_agent': logging.DEBUG,
252
+ 'tinyagent.mcp_client': logging.DEBUG,
253
+ })
254
+ console_handler = logging.StreamHandler(sys.stdout)
255
+ log_manager.configure_handler(
256
+ console_handler,
257
+ format_string='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
258
+ level=logging.DEBUG
259
+ )
260
+ ui_logger = log_manager.get_logger('tinyagent.hooks.gradio_callback')
261
+ agent_logger = log_manager.get_logger('tinyagent.tiny_agent')
262
+ ui_logger.info("--- Starting GradioCallback Example ---")
263
+ # --- End Logging Setup ---
264
+
265
+ api_key = os.environ.get("OPENAI_API_KEY")
266
+ if not api_key:
267
+ ui_logger.error("OPENAI_API_KEY environment variable not set.")
268
+ return
269
+
270
+ # Create a temporary folder for file uploads
271
+ upload_folder = tempfile.mkdtemp(prefix="gradio_uploads_")
272
+ ui_logger.info(f"Created temporary upload folder: {upload_folder}")
273
+
274
+ # Ensure we're using a single event loop for everything
275
+ loop = asyncio.get_event_loop()
276
+ ui_logger.debug(f"Using event loop: {loop}")
277
+
278
+ # Initialize the agent
279
+
280
+ from helper import translate_tool_for_code_agent,load_template,render_system_prompt,prompt_code_example
281
+ tools = [get_weather,get_traffic]
282
+
283
+ tools_meta_data = {}
284
+ for tool in tools:
285
+ metadata = translate_tool_for_code_agent(tool)
286
+ tools_meta_data[metadata["name"]] = metadata
287
+ template_str = load_template("./prompts/code_agent.yaml")
288
+ system_prompt = render_system_prompt(template_str, tools_meta_data, {}, ["tinyagent","gradio","requests","asyncio"]) + prompt_code_example
289
+ agent = TinyAgent(model="gpt-4.1-mini", api_key=api_key,
290
+ logger=agent_logger,
291
+ system_prompt=system_prompt)
292
+ python_interpreter = PythonCodeInterpreter(log_manager=log_manager,code_tools=tools)
293
+ agent.add_tool(python_interpreter.run_python)
294
+
295
+
296
+ # Create the Gradio callback
297
+ gradio_ui = GradioCallback(
298
+ file_upload_folder=upload_folder,
299
+ show_thinking=True,
300
+ show_tool_calls=True,
301
+ logger=ui_logger # Pass the specific logger
302
+ )
303
+ agent.add_callback(gradio_ui)
304
+
305
+ # Connect to MCP servers
306
+ try:
307
+ ui_logger.info("Connecting to MCP servers...")
308
+ # Use standard MCP servers as per contribution guide
309
+ #await agent.connect_to_server("npx",["-y","@openbnb/mcp-server-airbnb","--ignore-robots-txt"])
310
+ await agent.connect_to_server("npx", ["-y", "@modelcontextprotocol/server-sequential-thinking"])
311
+ ui_logger.info("Connected to MCP servers.")
312
+ except Exception as e:
313
+ ui_logger.error(f"Failed to connect to MCP servers: {e}", exc_info=True)
314
+ # Continue without servers - we still have the local get_weather tool
315
+
316
+ # Create the Gradio app but don't launch it yet
317
+ #app = gradio_ui.create_app(
318
+ # agent,
319
+ # title="TinyAgent Chat Interface",
320
+ # description="Chat with TinyAgent. Try asking: 'Plan a trip to Toronto for 7 days in the next month.'",
321
+ #)
322
+
323
+ # Configure the queue without extra parameters
324
+ #app.queue()
325
+
326
+ # Launch the app in a way that doesn't block our event loop
327
+ ui_logger.info("Launching Gradio interface...")
328
+ try:
329
+ # Launch without blocking
330
+ #app.launch(
331
+ # share=False,
332
+ # prevent_thread_lock=True, # Critical to not block our event loop
333
+ # show_error=True
334
+ #)
335
+ gradio_ui.launch(
336
+ agent,
337
+ title="TinyCodeAgent Chat Interface",
338
+ description="Chat with TinyAgent. Try asking: 'I need to know the weather and traffic in Toronto, Montreal, New York, Paris and San Francisco.'",
339
+ share=False,
340
+ prevent_thread_lock=True, # Critical to not block our event loop
341
+ show_error=True
342
+ )
343
+ ui_logger.info("Gradio interface launched (non-blocking).")
344
+
345
+ # Keep the main event loop running to handle both Gradio and MCP operations
346
+ # This is the key part - we need to keep our main event loop running
347
+ # but also allow it to process both Gradio and MCP client operations
348
+ while True:
349
+ await asyncio.sleep(1) # More efficient than an Event().wait()
350
+
351
+ except KeyboardInterrupt:
352
+ ui_logger.info("Received keyboard interrupt, shutting down...")
353
+ except Exception as e:
354
+ ui_logger.error(f"Failed to launch or run Gradio app: {e}", exc_info=True)
355
+ finally:
356
+ # Clean up
357
+ ui_logger.info("Cleaning up resources...")
358
+ if os.path.exists(upload_folder):
359
+ ui_logger.info(f"Removing temporary upload folder: {upload_folder}")
360
+ shutil.rmtree(upload_folder)
361
+ await agent.close()
362
+ ui_logger.info("--- GradioCallback Example Finished ---")
363
+
364
+ if __name__ == "__main__":
365
+ asyncio.run(run_example())
helper.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import yaml
3
+ from jinja2 import Template
4
+ from textwrap import dedent
5
+
6
+ prompt_code_example = dedent("""
7
+ User: How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging? github url: https://github.com/askbudi/tinyagent
8
+
9
+ function_calling: run_python
10
+ run_python("task='How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging?'",
11
+ "repo_result = code_research(repo_url='https://github.com/askbudi/tinyagent',task='How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging?')",
12
+ "print(repo_result)",
13
+ "answer_for_user_review = problem_solver(task=task,context=repo_result)",
14
+ "print(answer_for_user_review)",
15
+
16
+
17
+
18
+ """)
19
+
20
+ def load_template(path: str) -> str:
21
+ """
22
+ Load the YAML file and extract its 'system_prompt' field.
23
+ """
24
+ with open(path, "r") as f:
25
+ data = yaml.safe_load(f)
26
+ return data["system_prompt"]
27
+
28
+ def render_system_prompt(template_str: str,
29
+ tools: dict,
30
+ managed_agents: dict,
31
+ authorized_imports) -> str:
32
+ """
33
+ Render the Jinja2 template with the given context.
34
+ """
35
+ tmpl = Template(template_str)
36
+ return tmpl.render(
37
+ tools=tools,
38
+ managed_agents=managed_agents,
39
+ authorized_imports=authorized_imports
40
+ )
41
+
42
+
43
+ from tinyagent import tool
44
+ import asyncio
45
+ from typing import Any, Dict
46
+ import inspect
47
+ from typing import get_type_hints
48
+
49
+ def translate_tool_for_code_agent(tool_func_or_class: Any) -> Dict[str, Any]:
50
+ """
51
+ Translate a tool decorated with @tool into a format compatible with code_agent.yaml.
52
+
53
+ Args:
54
+ tool_func_or_class: A function or class decorated with @tool
55
+
56
+ Returns:
57
+ A dictionary with the tool configuration in code_agent.yaml format
58
+ """
59
+ def _get_type_as_string(type_hint: Any) -> str:
60
+ """
61
+ Convert a type hint to its string representation.
62
+
63
+ Args:
64
+ type_hint: The type hint to convert
65
+
66
+ Returns:
67
+ String representation of the type
68
+ """
69
+ if type_hint is Any:
70
+ return "Any"
71
+
72
+ # Handle common types
73
+ type_map = {
74
+ str: "str",
75
+ int: "int",
76
+ float: "float",
77
+ bool: "bool",
78
+ list: "List",
79
+ dict: "Dict",
80
+ tuple: "Tuple",
81
+ None: "None"
82
+ }
83
+
84
+ if type_hint in type_map:
85
+ return type_map[type_hint]
86
+
87
+ # Try to get the name attribute
88
+ if hasattr(type_hint, "__name__"):
89
+ return type_hint.__name__
90
+
91
+ # For generic types like List[str], Dict[str, int], etc.
92
+ return str(type_hint).replace("typing.", "")
93
+ # Check if the tool has the required metadata
94
+ if not hasattr(tool_func_or_class, '_tool_metadata'):
95
+ raise ValueError("Tool must be decorated with @tool decorator")
96
+
97
+ metadata = tool_func_or_class._tool_metadata
98
+
99
+ # Check if it's an async function
100
+ is_async = asyncio.iscoroutinefunction(tool_func_or_class)
101
+ if metadata["is_class"] and hasattr(tool_func_or_class, "__call__"):
102
+ is_async = asyncio.iscoroutinefunction(tool_func_or_class.__call__)
103
+
104
+ # Get the function signature for parameter types
105
+ if metadata["is_class"]:
106
+ func_to_inspect = tool_func_or_class.__init__
107
+ else:
108
+ func_to_inspect = tool_func_or_class
109
+
110
+ sig = inspect.signature(func_to_inspect)
111
+ type_hints = get_type_hints(func_to_inspect)
112
+
113
+ # Build inputs dictionary
114
+ inputs = {}
115
+ for name, param in sig.parameters.items():
116
+ if name in ['self', 'cls']:
117
+ continue
118
+
119
+ param_type = type_hints.get(name, Any)
120
+ param_type_str = _get_type_as_string(param_type)
121
+
122
+ # Get parameter description from schema if available
123
+ param_desc = ""
124
+ if metadata["schema"] and "properties" in metadata["schema"]:
125
+ if name in metadata["schema"]["properties"]:
126
+ param_desc = metadata["schema"]["properties"][name].get("description", "")
127
+
128
+ inputs[name] = {
129
+ "type": param_type_str,
130
+ "description": param_desc
131
+ }
132
+
133
+ # Determine output type
134
+ output_type = "Any"
135
+ if "return" in type_hints:
136
+ output_type = _get_type_as_string(type_hints["return"])
137
+
138
+ # Create the tool config
139
+ tool_config = {
140
+ "name": metadata["name"],
141
+ "description": metadata["description"],
142
+ "inputs": inputs,
143
+ "output_type": output_type,
144
+ "is_async": is_async
145
+ }
146
+
147
+ return tool_config
148
+
149
+
150
+
151
+
prompts/code_agent.yml ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Code sequence is a tool call to run_python 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, behaving like regular python functions:
147
+ The following functions are already imported for you and there is no need to import them again, you can use them directly:
148
+ ```python
149
+ {%- for tool in tools.values() %}
150
+ {% if tool.is_async %}async {% endif %}def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
151
+ """{{ tool.description }}
152
+
153
+ Args:
154
+ {%- for arg_name, arg_info in tool.inputs.items() %}
155
+ {{ arg_name }}: {{ arg_info.description }}
156
+ {%- endfor %}
157
+ """
158
+ {% endfor %}
159
+ ```
160
+
161
+ {%- if managed_agents and managed_agents.values() | list %}
162
+ You can also give tasks to team members.
163
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
164
+ 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.
165
+ Here is a list of the team members that you can call:
166
+ ```python
167
+ {%- for agent in managed_agents.values() %}
168
+ def {{ agent.name }}("Your query goes here.") -> str:
169
+ """{{ agent.description }}"""
170
+ {% endfor %}
171
+ ```
172
+ {%- endif %}
173
+
174
+ Here are the rules you should always follow to solve your task:
175
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
176
+ 2. Use only variables that you have defined!
177
+ 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?")'.
178
+ 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.
179
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
180
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
181
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
182
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
183
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
184
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
185
+ 11. You have access to defined tools, you just need to call them with the right arguments. That's it.
186
+
187
+ Now Begin!
188
+ planning:
189
+ initial_plan : |-
190
+ You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
191
+ Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
192
+
193
+ ## 1. Facts survey
194
+ You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
195
+ These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
196
+ ### 1.1. Facts given in the task
197
+ List here the specific facts given in the task that could help you (there might be nothing here).
198
+
199
+ ### 1.2. Facts to look up
200
+ List here any facts that we may need to look up.
201
+ 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.
202
+
203
+ ### 1.3. Facts to derive
204
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
205
+
206
+ Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
207
+
208
+ ## 2. Plan
209
+ Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
210
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
211
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
212
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
213
+
214
+ You can leverage these tools, behaving like regular python functions:
215
+ ```python
216
+ {%- for tool in tools.values() %}
217
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
218
+ """{{ tool.description }}
219
+
220
+ Args:
221
+ {%- for arg_name, arg_info in tool.inputs.items() %}
222
+ {{ arg_name }}: {{ arg_info.description }}
223
+ {%- endfor %}
224
+ """
225
+ {% endfor %}
226
+ ```
227
+
228
+ {%- if managed_agents and managed_agents.values() | list %}
229
+ You can also give tasks to team members.
230
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
231
+ 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.
232
+ Here is a list of the team members that you can call:
233
+ ```python
234
+ {%- for agent in managed_agents.values() %}
235
+ def {{ agent.name }}("Your query goes here.") -> str:
236
+ """{{ agent.description }}"""
237
+ {% endfor %}
238
+ ```
239
+ {%- endif %}
240
+
241
+ ---
242
+ Now begin! Here is your task:
243
+ ```
244
+ {{task}}
245
+ ```
246
+ First in part 1, write the facts survey, then in part 2, write your plan.
247
+ update_plan_pre_messages: |-
248
+ You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
249
+ You have been given the following task:
250
+ ```
251
+ {{task}}
252
+ ```
253
+
254
+ Below you will find a history of attempts made to solve this task.
255
+ You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
256
+ If the previous tries so far have met some success, your updated plan can build on these results.
257
+ If you are stalled, you can make a completely new plan starting from scratch.
258
+
259
+ Find the task and history below:
260
+ update_plan_post_messages: |-
261
+ Now write your updated facts below, taking into account the above history:
262
+ ## 1. Updated facts survey
263
+ ### 1.1. Facts given in the task
264
+ ### 1.2. Facts that we have learned
265
+ ### 1.3. Facts still to look up
266
+ ### 1.4. Facts still to derive
267
+
268
+ Then write a step-by-step high-level plan to solve the task above.
269
+ ## 2. Plan
270
+ ### 2. 1. ...
271
+ Etc.
272
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
273
+ Beware that you have {remaining_steps} steps remaining.
274
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
275
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
276
+
277
+ You can leverage these tools, behaving like regular python functions:
278
+ ```python
279
+ {%- for tool in tools.values() %}
280
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
281
+ """{{ tool.description }}
282
+
283
+ Args:
284
+ {%- for arg_name, arg_info in tool.inputs.items() %}
285
+ {{ arg_name }}: {{ arg_info.description }}
286
+ {%- endfor %}"""
287
+ {% endfor %}
288
+ ```
289
+
290
+ {%- if managed_agents and managed_agents.values() | list %}
291
+ You can also give tasks to team members.
292
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
293
+ 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.
294
+ Here is a list of the team members that you can call:
295
+ ```python
296
+ {%- for agent in managed_agents.values() %}
297
+ def {{ agent.name }}("Your query goes here.") -> str:
298
+ """{{ agent.description }}"""
299
+ {% endfor %}
300
+ ```
301
+ {%- endif %}
302
+
303
+ Now write your updated facts survey below, then your new plan.
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}}
324
+ final_answer:
325
+ pre_messages: |-
326
+ An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
327
+ post_messages: |-
328
+ Based on the above, please provide an answer to the following user task:
329
+ {{task}}
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ tinyagent[all]
2
+ cloudpickle
3
+ modal
4
+ jinja2
5
+ pyyaml