tinyagent-py 0.0.8__tar.gz → 0.0.9__tar.gz

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.
Files changed (37) hide show
  1. {tinyagent_py-0.0.8/tinyagent_py.egg-info → tinyagent_py-0.0.9}/PKG-INFO +138 -5
  2. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/README.md +127 -3
  3. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/pyproject.toml +14 -3
  4. tinyagent_py-0.0.9/tinyagent/__init__.py +5 -0
  5. tinyagent_py-0.0.9/tinyagent/code_agent/__init__.py +12 -0
  6. tinyagent_py-0.0.9/tinyagent/code_agent/example.py +176 -0
  7. tinyagent_py-0.0.9/tinyagent/code_agent/helper.py +173 -0
  8. tinyagent_py-0.0.9/tinyagent/code_agent/modal_sandbox.py +478 -0
  9. tinyagent_py-0.0.9/tinyagent/code_agent/providers/__init__.py +4 -0
  10. tinyagent_py-0.0.9/tinyagent/code_agent/providers/base.py +152 -0
  11. tinyagent_py-0.0.9/tinyagent/code_agent/providers/modal_provider.py +202 -0
  12. tinyagent_py-0.0.9/tinyagent/code_agent/tiny_code_agent.py +573 -0
  13. tinyagent_py-0.0.9/tinyagent/code_agent/tools/__init__.py +3 -0
  14. tinyagent_py-0.0.9/tinyagent/code_agent/tools/example_tools.py +41 -0
  15. tinyagent_py-0.0.9/tinyagent/code_agent/utils.py +120 -0
  16. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/hooks/__init__.py +2 -1
  17. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9/tinyagent_py.egg-info}/PKG-INFO +138 -5
  18. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent_py.egg-info/SOURCES.txt +11 -0
  19. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent_py.egg-info/requires.txt +10 -0
  20. tinyagent_py-0.0.8/tinyagent/__init__.py +0 -4
  21. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/LICENSE +0 -0
  22. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/setup.cfg +0 -0
  23. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/hooks/gradio_callback.py +0 -0
  24. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/hooks/logging_manager.py +0 -0
  25. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/hooks/rich_code_ui_callback.py +0 -0
  26. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/hooks/rich_ui_callback.py +0 -0
  27. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/mcp_client.py +0 -0
  28. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/memory_manager.py +0 -0
  29. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/__init__.py +0 -0
  30. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/base.py +0 -0
  31. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/json_file_storage.py +0 -0
  32. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/postgres_storage.py +0 -0
  33. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/redis_storage.py +0 -0
  34. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/storage/sqlite_storage.py +0 -0
  35. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent/tiny_agent.py +0 -0
  36. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent_py.egg-info/dependency_links.txt +0 -0
  37. {tinyagent_py-0.0.8 → tinyagent_py-0.0.9}/tinyagent_py.egg-info/top_level.txt +0 -0
@@ -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.9
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.
@@ -19,7 +19,11 @@ Inspired by:
19
19
  - [Build your own Tiny Agent](https://askdev.ai/github/askbudi/tinyagent)
20
20
 
21
21
  ## Overview
22
- 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.
22
+ 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.
23
+
24
+ **Two Main Components:**
25
+ - **TinyAgent**: Core agent with MCP tool integration and extensible hooks
26
+ - **TinyCodeAgent**: Specialized agent for secure Python code execution with pluggable providers
23
27
 
24
28
  ## Installation
25
29
 
@@ -31,6 +35,10 @@ pip install tinyagent-py
31
35
  # Install with all optional dependencies
32
36
  pip install tinyagent-py[all]
33
37
 
38
+ # Install with Code Agent support
39
+ pip install tinyagent-py[code]
40
+
41
+
34
42
  # Install with PostgreSQL support
35
43
  pip install tinyagent-py[postgres]
36
44
 
@@ -40,6 +48,10 @@ pip install tinyagent-py[sqlite]
40
48
  # Install with Gradio UI support
41
49
  pip install tinyagent-py[gradio]
42
50
 
51
+
52
+
53
+
54
+
43
55
  ```
44
56
 
45
57
  ### Using uv
@@ -47,6 +59,10 @@ pip install tinyagent-py[gradio]
47
59
  # Basic installation
48
60
  uv pip install tinyagent-py
49
61
 
62
+ # Install with Code Agent support
63
+ uv pip install tinyagent-py[code]
64
+
65
+
50
66
  # Install with PostgreSQL support
51
67
  uv pip install tinyagent-py[postgres]
52
68
 
@@ -59,11 +75,11 @@ uv pip install tinyagent-py[gradio]
59
75
  # Install with all optional dependencies
60
76
  uv pip install tinyagent-py[all]
61
77
 
62
- # Install with development tools
63
- uv pip install tinyagent-py[dev]
64
78
  ```
65
79
 
66
80
  ## Usage
81
+
82
+ ### TinyAgent (Core Agent)
67
83
  [![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)
68
84
 
69
85
 
@@ -100,6 +116,114 @@ I need accommodation in Toronto between 15th to 20th of May. Give me 5 options f
100
116
  await test_agent(task, model="gpt-4.1-mini")
101
117
  ```
102
118
 
119
+ ## TinyCodeAgent - Code Execution Made Easy
120
+
121
+ TinyCodeAgent is a specialized agent for executing Python code with enterprise-grade reliability and extensible execution providers.
122
+
123
+ ### Quick Start with TinyCodeAgent
124
+
125
+ ```python
126
+ import asyncio
127
+ from tinyagent import TinyCodeAgent
128
+
129
+ async def main():
130
+ # Initialize with minimal configuration
131
+ agent = TinyCodeAgent(
132
+ model="gpt-4.1-mini",
133
+ api_key="your-openai-api-key"
134
+ )
135
+
136
+ try:
137
+ # Ask the agent to solve a coding problem
138
+ result = await agent.run("Calculate the factorial of 10 and explain the algorithm")
139
+ print(result)
140
+ finally:
141
+ await agent.close()
142
+
143
+ asyncio.run(main())
144
+ ```
145
+
146
+ ### TinyCodeAgent with Gradio UI
147
+
148
+ Launch a complete web interface for interactive code execution:
149
+
150
+ ```python
151
+ from tinyagent.code_agent.example import run_example
152
+ import asyncio
153
+
154
+ # Run the full example with Gradio interface
155
+ asyncio.run(run_example())
156
+ ```
157
+
158
+ ### Key Features
159
+
160
+ - **🔒 Secure Execution**: Sandboxed Python code execution using Modal.com or other providers
161
+ - **🔧 Extensible Providers**: Switch between Modal, Docker, local execution, or cloud functions
162
+ - **🎯 Built for Enterprise**: Production-ready with proper logging, error handling, and resource cleanup
163
+ - **📁 File Support**: Upload and process files through the Gradio interface
164
+ - **🛠️ Custom Tools**: Add your own tools and functions easily
165
+ - **📊 Session Persistence**: Code state persists across executions
166
+
167
+ ### Provider System
168
+
169
+ TinyCodeAgent uses a pluggable provider system - change execution backends with minimal code changes:
170
+
171
+ ```python
172
+ # Use Modal (default) - great for production
173
+ agent = TinyCodeAgent(provider="modal")
174
+
175
+ # Future providers (coming soon)
176
+ # agent = TinyCodeAgent(provider="docker")
177
+ # agent = TinyCodeAgent(provider="local")
178
+ # agent = TinyCodeAgent(provider="lambda")
179
+ ```
180
+
181
+ ### Example Use Cases
182
+
183
+ **Web Scraping:**
184
+ ```python
185
+ result = await agent.run("""
186
+ What are trending spaces on huggingface today?
187
+ """)
188
+ # Agent will create a python tool to request HuggingFace API and find trending spaces
189
+ ```
190
+
191
+ **Use code to solve a task:**
192
+ ```python
193
+ response = await agent.run(dedent("""
194
+ 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.
195
+ - You should use your coding abilities to check your answer pass the criteria and continue your job until you get to the answer.
196
+
197
+ My Product is **Wedding Invitation Set of 3, in sage green color, with a gold foil border.**
198
+ """),max_turns=20)
199
+
200
+ print(response)
201
+ # 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.
202
+ ```
203
+
204
+
205
+ ### Configuration Options
206
+
207
+ ```python
208
+ from tinyagent import TinyCodeAgent
209
+ from tinyagent.code_agent.tools import get_weather, get_traffic
210
+
211
+ # Full configuration example
212
+ agent = TinyCodeAgent(
213
+ model="gpt-4.1-mini",
214
+ api_key="your-api-key",
215
+ provider="modal",
216
+ tools=[get_weather, get_traffic],
217
+ authorized_imports=["requests", "pandas", "numpy"],
218
+ provider_config={
219
+ "pip_packages": ["requests", "pandas"],
220
+ "sandbox_name": "my-code-sandbox"
221
+ }
222
+ )
223
+ ```
224
+
225
+ For detailed documentation, see the [TinyCodeAgent README](tinyagent/code_agent/README.md).
226
+
103
227
  ## How the TinyAgent Hook System Works
104
228
 
105
229
  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.
@@ -9,8 +9,8 @@ exclude = ["public", "public.*"]
9
9
 
10
10
  [project]
11
11
  name = "tinyagent-py"
12
- version = "0.0.8"
13
- description = "Tiny Agent with MCP Client and Extendable Hooks, Tiny but powerful"
12
+ version = "0.0.9"
13
+ description = "TinyAgent with MCP Client, Code Agent (Thinking, Planning, and Executing in Python), and Extendable Hooks, Tiny but powerful"
14
14
  readme = "README.md"
15
15
  authors = [
16
16
  {name="Mahdi Golchin", email="golchin@askdev.ai"}
@@ -41,10 +41,21 @@ sqlite = [
41
41
  gradio = [
42
42
  "gradio>=3.50.0"
43
43
  ]
44
+ code = [
45
+ "jinja2",
46
+ "pyyaml",
47
+ "cloudpickle",
48
+ "modal"
49
+ ]
44
50
  all = [
45
51
  "asyncpg>=0.27.0",
46
52
  "aiosqlite>=0.18.0",
47
- "gradio>=3.50.0"
53
+ "gradio>=3.50.0",
54
+ "jinja2",
55
+ "pyyaml",
56
+ "cloudpickle",
57
+ "modal"
58
+
48
59
  ]
49
60
  [project.urls]
50
61
  "Homepage" = "https://github.com/askbudi/tinyagent"
@@ -0,0 +1,5 @@
1
+ from .tiny_agent import TinyAgent,tool
2
+ from .mcp_client import MCPClient
3
+ from .code_agent import TinyCodeAgent
4
+
5
+ __all__ = ["TinyAgent", "MCPClient","tool", "TinyCodeAgent"]
@@ -0,0 +1,12 @@
1
+ from .tiny_code_agent import TinyCodeAgent
2
+ from .providers.base import CodeExecutionProvider
3
+ from .providers.modal_provider import ModalProvider
4
+ from .tools.example_tools import get_weather, get_traffic
5
+
6
+ __all__ = [
7
+ "TinyCodeAgent",
8
+ "CodeExecutionProvider",
9
+ "ModalProvider",
10
+ "get_weather",
11
+ "get_traffic"
12
+ ]
@@ -0,0 +1,176 @@
1
+ """
2
+ Example usage of TinyCodeAgent with Gradio UI.
3
+
4
+ This example demonstrates how to initialize and use TinyCodeAgent
5
+ following the guidelines from gradio_agent.md and README.md.
6
+ """
7
+
8
+ import asyncio
9
+ import os
10
+ import sys
11
+ import tempfile
12
+ import shutil
13
+ import logging
14
+ from typing import Dict, Any, Union
15
+
16
+ from tinyagent.hooks.logging_manager import LoggingManager
17
+ from tinyagent.hooks.gradio_callback import GradioCallback
18
+ from .tiny_code_agent import TinyCodeAgent
19
+ from .tools.example_tools import get_weather, get_traffic
20
+
21
+
22
+ async def run_example():
23
+ """Example usage of TinyCodeAgent with GradioCallback."""
24
+
25
+ # --- Logging Setup ---
26
+ log_manager = LoggingManager(default_level=logging.INFO)
27
+ log_manager.set_levels({
28
+ 'tinyagent.hooks.gradio_callback': logging.DEBUG,
29
+ 'tinyagent.tiny_agent': logging.DEBUG,
30
+ 'tinyagent.mcp_client': logging.DEBUG,
31
+ 'tinyagent.code_agent': logging.DEBUG,
32
+ })
33
+
34
+ console_handler = logging.StreamHandler(sys.stdout)
35
+ log_manager.configure_handler(
36
+ console_handler,
37
+ format_string='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
38
+ level=logging.DEBUG
39
+ )
40
+
41
+ ui_logger = log_manager.get_logger('tinyagent.hooks.gradio_callback')
42
+ agent_logger = log_manager.get_logger('tinyagent.code_agent')
43
+ ui_logger.info("--- Starting TinyCodeAgent Example ---")
44
+
45
+ # --- Configuration ---
46
+ model = "gpt-4.1-mini"
47
+ api_key = os.environ.get("OPENAI_API_KEY")
48
+ if not api_key:
49
+ ui_logger.error("OPENAI_API_KEY environment variable not set.")
50
+ return
51
+
52
+ # Create a temporary folder for file uploads
53
+ upload_folder = tempfile.mkdtemp(prefix="gradio_uploads_")
54
+ ui_logger.info(f"Created temporary upload folder: {upload_folder}")
55
+
56
+ # --- Modal Configuration ---
57
+ modal_secrets: Dict[str, Union[str, None]] = {
58
+ "OPENAI_API_KEY": api_key,
59
+ # Add other secrets as needed
60
+ }
61
+
62
+ provider_config = {
63
+ "modal_secrets": modal_secrets,
64
+ "pip_packages": ["tinyagent-py[all]", "requests", "cloudpickle"],
65
+ "default_python_codes": [
66
+ "import random",
67
+ "import requests",
68
+ "import cloudpickle",
69
+ "import tempfile",
70
+ "import shutil",
71
+ "import asyncio",
72
+ "import logging",
73
+ "import time"
74
+ ]
75
+ }
76
+
77
+ try:
78
+ # --- Initialize TinyCodeAgent ---
79
+ agent = TinyCodeAgent(
80
+ model=model,
81
+ api_key=api_key,
82
+ log_manager=log_manager,
83
+ provider="modal",
84
+ tools=[get_weather, get_traffic],
85
+ provider_config=provider_config
86
+ )
87
+
88
+ # --- Create Gradio UI ---
89
+ gradio_ui = GradioCallback(
90
+ file_upload_folder=upload_folder,
91
+ show_thinking=True,
92
+ show_tool_calls=True,
93
+ logger=ui_logger
94
+ )
95
+ agent.add_callback(gradio_ui)
96
+
97
+ # --- Connect to MCP servers (as per contribution guide) ---
98
+ try:
99
+ ui_logger.info("Connecting to MCP servers...")
100
+ await agent.connect_to_server("npx", ["-y", "@modelcontextprotocol/server-sequential-thinking"])
101
+ ui_logger.info("Connected to MCP servers.")
102
+ except Exception as e:
103
+ ui_logger.warning(f"Failed to connect to MCP servers: {e}")
104
+ # Continue without servers - we still have the local tools
105
+
106
+ # --- Launch Gradio Interface ---
107
+ ui_logger.info("Launching Gradio interface...")
108
+ try:
109
+ gradio_ui.launch(
110
+ agent.agent, # Pass the underlying TinyAgent
111
+ title="TinyCodeAgent Chat Interface",
112
+ description="Chat with TinyCodeAgent. Try asking: 'I need to know the weather and traffic in Toronto, Montreal, New York, Paris and San Francisco.'",
113
+ share=False,
114
+ prevent_thread_lock=True,
115
+ show_error=True,
116
+ mcp_server=True,
117
+ )
118
+ ui_logger.info("Gradio interface launched (non-blocking).")
119
+
120
+ # Keep the event loop running
121
+ while True:
122
+ await asyncio.sleep(1)
123
+
124
+ except KeyboardInterrupt:
125
+ ui_logger.info("Received keyboard interrupt, shutting down...")
126
+ except Exception as e:
127
+ ui_logger.error(f"Failed to launch or run Gradio app: {e}", exc_info=True)
128
+
129
+ finally:
130
+ # Clean up
131
+ ui_logger.info("Cleaning up resources...")
132
+ if os.path.exists(upload_folder):
133
+ ui_logger.info(f"Removing temporary upload folder: {upload_folder}")
134
+ shutil.rmtree(upload_folder)
135
+
136
+ if 'agent' in locals():
137
+ await agent.close()
138
+
139
+ ui_logger.info("--- TinyCodeAgent Example Finished ---")
140
+
141
+
142
+ def simple_example():
143
+ """Simple example without Gradio UI."""
144
+ async def _simple_example():
145
+ # Basic setup
146
+ api_key = os.environ.get("OPENAI_API_KEY")
147
+ if not api_key:
148
+ print("OPENAI_API_KEY environment variable not set.")
149
+ return
150
+
151
+ # Initialize TinyCodeAgent
152
+ agent = TinyCodeAgent(
153
+ model="gpt-4.1-mini",
154
+ api_key=api_key,
155
+ tools=[get_weather, get_traffic]
156
+ )
157
+
158
+ try:
159
+ # Run a simple query
160
+ result = await agent.run(
161
+ "I need to check the weather and traffic in Toronto. Can you help me?"
162
+ )
163
+ print(f"\nResult: {result}")
164
+
165
+ finally:
166
+ await agent.close()
167
+
168
+ asyncio.run(_simple_example())
169
+
170
+
171
+ if __name__ == "__main__":
172
+ # Run the full example with Gradio
173
+ asyncio.run(run_example())
174
+
175
+ # Uncomment to run the simple example instead
176
+ # simple_example()