tinyagent-py 0.0.8__py3-none-any.whl → 0.0.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ import sys
2
+ import cloudpickle
3
+ from typing import Dict, Any
4
+
5
+
6
+ def clean_response(resp: Dict[str, Any]) -> Dict[str, Any]:
7
+ """
8
+ Clean the response from code execution, keeping only relevant fields.
9
+
10
+ Args:
11
+ resp: Raw response dictionary from code execution
12
+
13
+ Returns:
14
+ Cleaned response with only essential fields
15
+ """
16
+ return {k: v for k, v in resp.items() if k in ['printed_output', 'return_value', 'stderr', 'error_traceback']}
17
+
18
+
19
+ def make_session_blob(ns: dict) -> bytes:
20
+ """
21
+ Create a serialized blob of the session namespace, excluding unserializable objects.
22
+
23
+ Args:
24
+ ns: Namespace dictionary to serialize
25
+
26
+ Returns:
27
+ Serialized bytes of the clean namespace
28
+ """
29
+ clean = {}
30
+ for name, val in ns.items():
31
+ try:
32
+ # Try serializing just this one object
33
+ cloudpickle.dumps(val)
34
+ except Exception:
35
+ # drop anything that fails
36
+ continue
37
+ else:
38
+ clean[name] = val
39
+
40
+ return cloudpickle.dumps(clean)
41
+
42
+
43
+ def _run_python(code: str, globals_dict: Dict[str, Any] = None, locals_dict: Dict[str, Any] = None):
44
+ """
45
+ Execute Python code in a controlled environment with proper error handling.
46
+
47
+ Args:
48
+ code: Python code to execute
49
+ globals_dict: Global variables dictionary
50
+ locals_dict: Local variables dictionary
51
+
52
+ Returns:
53
+ Dictionary containing execution results
54
+ """
55
+ import contextlib
56
+ import traceback
57
+ import io
58
+ import ast
59
+
60
+ # Make copies to avoid mutating the original parameters
61
+ globals_dict = globals_dict or {}
62
+ locals_dict = locals_dict or {}
63
+ updated_globals = globals_dict.copy()
64
+ updated_locals = locals_dict.copy()
65
+
66
+ # Pre-import essential modules into the global namespace
67
+ # This ensures they're available for imports inside functions
68
+ essential_modules = ['requests', 'json', 'os', 'sys', 'time', 'datetime', 're', 'random', 'math']
69
+
70
+ for module_name in essential_modules:
71
+ try:
72
+ module = __import__(module_name)
73
+ updated_globals[module_name] = module
74
+ #print(f"✓ {module_name} module loaded successfully")
75
+ except ImportError:
76
+ print(f"⚠️ Warning: {module_name} module not available")
77
+
78
+ tree = ast.parse(code, mode="exec")
79
+ compiled = compile(tree, filename="<ast>", mode="exec")
80
+ stdout_buf = io.StringIO()
81
+ stderr_buf = io.StringIO()
82
+
83
+ # Execute with stdout+stderr capture and exception handling
84
+ error_traceback = None
85
+ output = None
86
+
87
+ with contextlib.redirect_stdout(stdout_buf), contextlib.redirect_stderr(stderr_buf):
88
+ try:
89
+ # Merge all variables into globals to avoid scoping issues with generator expressions
90
+ # When exec() is called with both globals and locals, generator expressions can't
91
+ # access local variables. By using only globals, everything runs in global scope.
92
+ merged_globals = updated_globals.copy()
93
+ merged_globals.update(updated_locals)
94
+
95
+ # Execute with only globals - this fixes generator expression scoping issues
96
+ output = exec(code, merged_globals)
97
+
98
+ # Update both dictionaries with any new variables created during execution
99
+ for key, value in merged_globals.items():
100
+ if key not in updated_globals and key not in updated_locals:
101
+ updated_locals[key] = value
102
+ elif key in updated_locals or key not in updated_globals:
103
+ updated_locals[key] = value
104
+ updated_globals[key] = value
105
+ except Exception:
106
+ # Capture the full traceback as a string
107
+ error_traceback = traceback.format_exc()
108
+
109
+ printed_output = stdout_buf.getvalue()
110
+ stderr_output = stderr_buf.getvalue()
111
+ error_traceback_output = error_traceback
112
+
113
+ return {
114
+ "printed_output": printed_output,
115
+ "return_value": output,
116
+ "stderr": stderr_output,
117
+ "error_traceback": error_traceback_output,
118
+ "updated_globals": updated_globals,
119
+ "updated_locals": updated_locals
120
+ }
@@ -1,4 +1,5 @@
1
1
  #from .rich_ui_agent import RichUICallback
2
2
  from .rich_ui_callback import RichUICallback
3
+ from .rich_code_ui_callback import RichCodeUICallback
3
4
  from .logging_manager import LoggingManager
4
- __all__ = ["RichUICallback", "LoggingManager"]
5
+ __all__ = ["RichUICallback", "RichCodeUICallback", "LoggingManager"]
@@ -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}}
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyagent-py
3
- Version: 0.0.8
4
- Summary: Tiny Agent with MCP Client and Extendable Hooks, Tiny but powerful
3
+ Version: 0.0.11
4
+ Summary: TinyAgent with MCP Client, Code Agent (Thinking, Planning, and Executing in Python), and Extendable Hooks, Tiny but powerful
5
5
  Author-email: Mahdi Golchin <golchin@askdev.ai>
6
6
  Project-URL: Homepage, https://github.com/askbudi/tinyagent
7
7
  Project-URL: Bug Tracker, https://github.com/askbudi/tinyagent/issues
@@ -25,10 +25,19 @@ Provides-Extra: sqlite
25
25
  Requires-Dist: aiosqlite>=0.18.0; extra == "sqlite"
26
26
  Provides-Extra: gradio
27
27
  Requires-Dist: gradio>=3.50.0; extra == "gradio"
28
+ Provides-Extra: code
29
+ Requires-Dist: jinja2; extra == "code"
30
+ Requires-Dist: pyyaml; extra == "code"
31
+ Requires-Dist: cloudpickle; extra == "code"
32
+ Requires-Dist: modal; extra == "code"
28
33
  Provides-Extra: all
29
34
  Requires-Dist: asyncpg>=0.27.0; extra == "all"
30
35
  Requires-Dist: aiosqlite>=0.18.0; extra == "all"
31
36
  Requires-Dist: gradio>=3.50.0; extra == "all"
37
+ Requires-Dist: jinja2; extra == "all"
38
+ Requires-Dist: pyyaml; extra == "all"
39
+ Requires-Dist: cloudpickle; extra == "all"
40
+ Requires-Dist: modal; extra == "all"
32
41
  Dynamic: license-file
33
42
 
34
43
  # TinyAgent
@@ -52,7 +61,11 @@ Inspired by:
52
61
  - [Build your own Tiny Agent](https://askdev.ai/github/askbudi/tinyagent)
53
62
 
54
63
  ## Overview
55
- This is a tiny agent that uses MCP and LiteLLM to interact with a model. You have full control over the agent, you can add any tools you like from MCP and extend the agent using its event system.
64
+ This is a tiny agent framework that uses MCP and LiteLLM to interact with language models. You have full control over the agent, you can add any tools you like from MCP and extend the agent using its event system.
65
+
66
+ **Two Main Components:**
67
+ - **TinyAgent**: Core agent with MCP tool integration and extensible hooks
68
+ - **TinyCodeAgent**: Specialized agent for secure Python code execution with pluggable providers
56
69
 
57
70
  ## Installation
58
71
 
@@ -64,6 +77,10 @@ pip install tinyagent-py
64
77
  # Install with all optional dependencies
65
78
  pip install tinyagent-py[all]
66
79
 
80
+ # Install with Code Agent support
81
+ pip install tinyagent-py[code]
82
+
83
+
67
84
  # Install with PostgreSQL support
68
85
  pip install tinyagent-py[postgres]
69
86
 
@@ -73,6 +90,10 @@ pip install tinyagent-py[sqlite]
73
90
  # Install with Gradio UI support
74
91
  pip install tinyagent-py[gradio]
75
92
 
93
+
94
+
95
+
96
+
76
97
  ```
77
98
 
78
99
  ### Using uv
@@ -80,6 +101,10 @@ pip install tinyagent-py[gradio]
80
101
  # Basic installation
81
102
  uv pip install tinyagent-py
82
103
 
104
+ # Install with Code Agent support
105
+ uv pip install tinyagent-py[code]
106
+
107
+
83
108
  # Install with PostgreSQL support
84
109
  uv pip install tinyagent-py[postgres]
85
110
 
@@ -92,11 +117,11 @@ uv pip install tinyagent-py[gradio]
92
117
  # Install with all optional dependencies
93
118
  uv pip install tinyagent-py[all]
94
119
 
95
- # Install with development tools
96
- uv pip install tinyagent-py[dev]
97
120
  ```
98
121
 
99
122
  ## Usage
123
+
124
+ ### TinyAgent (Core Agent)
100
125
  [![AskDev.AI | Chat with TinyAgent](https://img.shields.io/badge/AskDev.AI-Chat_with_TinyAgent-blue?style=flat-square)](https://askdev.ai/github/askbudi/tinyagent)
101
126
 
102
127
 
@@ -133,6 +158,114 @@ I need accommodation in Toronto between 15th to 20th of May. Give me 5 options f
133
158
  await test_agent(task, model="gpt-4.1-mini")
134
159
  ```
135
160
 
161
+ ## TinyCodeAgent - Code Execution Made Easy
162
+
163
+ TinyCodeAgent is a specialized agent for executing Python code with enterprise-grade reliability and extensible execution providers.
164
+
165
+ ### Quick Start with TinyCodeAgent
166
+
167
+ ```python
168
+ import asyncio
169
+ from tinyagent import TinyCodeAgent
170
+
171
+ async def main():
172
+ # Initialize with minimal configuration
173
+ agent = TinyCodeAgent(
174
+ model="gpt-4.1-mini",
175
+ api_key="your-openai-api-key"
176
+ )
177
+
178
+ try:
179
+ # Ask the agent to solve a coding problem
180
+ result = await agent.run("Calculate the factorial of 10 and explain the algorithm")
181
+ print(result)
182
+ finally:
183
+ await agent.close()
184
+
185
+ asyncio.run(main())
186
+ ```
187
+
188
+ ### TinyCodeAgent with Gradio UI
189
+
190
+ Launch a complete web interface for interactive code execution:
191
+
192
+ ```python
193
+ from tinyagent.code_agent.example import run_example
194
+ import asyncio
195
+
196
+ # Run the full example with Gradio interface
197
+ asyncio.run(run_example())
198
+ ```
199
+
200
+ ### Key Features
201
+
202
+ - **🔒 Secure Execution**: Sandboxed Python code execution using Modal.com or other providers
203
+ - **🔧 Extensible Providers**: Switch between Modal, Docker, local execution, or cloud functions
204
+ - **🎯 Built for Enterprise**: Production-ready with proper logging, error handling, and resource cleanup
205
+ - **📁 File Support**: Upload and process files through the Gradio interface
206
+ - **🛠️ Custom Tools**: Add your own tools and functions easily
207
+ - **📊 Session Persistence**: Code state persists across executions
208
+
209
+ ### Provider System
210
+
211
+ TinyCodeAgent uses a pluggable provider system - change execution backends with minimal code changes:
212
+
213
+ ```python
214
+ # Use Modal (default) - great for production
215
+ agent = TinyCodeAgent(provider="modal")
216
+
217
+ # Future providers (coming soon)
218
+ # agent = TinyCodeAgent(provider="docker")
219
+ # agent = TinyCodeAgent(provider="local")
220
+ # agent = TinyCodeAgent(provider="lambda")
221
+ ```
222
+
223
+ ### Example Use Cases
224
+
225
+ **Web Scraping:**
226
+ ```python
227
+ result = await agent.run("""
228
+ What are trending spaces on huggingface today?
229
+ """)
230
+ # Agent will create a python tool to request HuggingFace API and find trending spaces
231
+ ```
232
+
233
+ **Use code to solve a task:**
234
+ ```python
235
+ response = await agent.run(dedent("""
236
+ Suggest me 13 tags for my Etsy Listing, each tag should be multiworded and maximum 20 characters. Each word should be used only once in the whole corpus, And tags should cover different ways people are searching for the product on Etsy.
237
+ - You should use your coding abilities to check your answer pass the criteria and continue your job until you get to the answer.
238
+
239
+ My Product is **Wedding Invitation Set of 3, in sage green color, with a gold foil border.**
240
+ """),max_turns=20)
241
+
242
+ print(response)
243
+ # LLM is not good at this task, counting characters, avoid duplicates, but with the power of code, tiny model like gpt-4.1-mini can do it without any problem.
244
+ ```
245
+
246
+
247
+ ### Configuration Options
248
+
249
+ ```python
250
+ from tinyagent import TinyCodeAgent
251
+ from tinyagent.code_agent.tools import get_weather, get_traffic
252
+
253
+ # Full configuration example
254
+ agent = TinyCodeAgent(
255
+ model="gpt-4.1-mini",
256
+ api_key="your-api-key",
257
+ provider="modal",
258
+ tools=[get_weather, get_traffic],
259
+ authorized_imports=["requests", "pandas", "numpy"],
260
+ provider_config={
261
+ "pip_packages": ["requests", "pandas"],
262
+ "sandbox_name": "my-code-sandbox"
263
+ }
264
+ )
265
+ ```
266
+
267
+ For detailed documentation, see the [TinyCodeAgent README](tinyagent/code_agent/README.md).
268
+
136
269
  ## How the TinyAgent Hook System Works
137
270
 
138
271
  TinyAgent is designed to be **extensible** via a simple, event-driven hook (callback) system. This allows you to add custom logic, logging, UI, memory, or any other behavior at key points in the agent's lifecycle.