0
# Code Execution
1
2
Code execution framework supporting built-in, local, container-based, and Vertex AI code execution environments with safety controls.
3
4
## Capabilities
5
6
### Core Code Executor Classes
7
8
Base classes and implementations for executing code in various environments.
9
10
```python { .api }
11
class BaseCodeExecutor:
12
"""Base class for code executors."""
13
14
def __init__(self, **kwargs):
15
"""
16
Initialize base code executor.
17
18
Args:
19
**kwargs: Code executor configuration parameters
20
"""
21
pass
22
23
def execute(
24
self,
25
code: str,
26
language: str,
27
context: 'CodeExecutorContext' = None,
28
**kwargs
29
) -> dict:
30
"""
31
Execute code in the specified language.
32
33
Args:
34
code (str): Code to execute
35
language (str): Programming language
36
context (CodeExecutorContext, optional): Execution context
37
**kwargs: Additional execution parameters
38
39
Returns:
40
dict: Execution result with output, errors, and metadata
41
"""
42
pass
43
44
def is_supported_language(self, language: str) -> bool:
45
"""
46
Check if language is supported.
47
48
Args:
49
language (str): Programming language
50
51
Returns:
52
bool: True if language is supported
53
"""
54
pass
55
56
def get_supported_languages(self) -> list:
57
"""
58
Get list of supported languages.
59
60
Returns:
61
list: List of supported programming languages
62
"""
63
pass
64
65
class BuiltInCodeExecutor(BaseCodeExecutor):
66
"""Built-in code executor with safety controls."""
67
68
def __init__(
69
self,
70
allowed_modules: list = None,
71
timeout: float = 30,
72
max_memory: int = 512, # MB
73
**kwargs
74
):
75
"""
76
Initialize built-in code executor.
77
78
Args:
79
allowed_modules (list, optional): List of allowed Python modules
80
timeout (float): Execution timeout in seconds
81
max_memory (int): Maximum memory usage in MB
82
**kwargs: Additional configuration parameters
83
"""
84
pass
85
86
class UnsafeLocalCodeExecutor(BaseCodeExecutor):
87
"""Local code executor (unsafe - for development only)."""
88
89
def __init__(
90
self,
91
working_directory: str = None,
92
timeout: float = 60,
93
**kwargs
94
):
95
"""
96
Initialize unsafe local code executor.
97
98
Warning: This executor runs code without sandboxing and should only
99
be used in development environments.
100
101
Args:
102
working_directory (str, optional): Code execution directory
103
timeout (float): Execution timeout in seconds
104
**kwargs: Additional configuration parameters
105
"""
106
pass
107
108
class VertexAiCodeExecutor(BaseCodeExecutor):
109
"""Vertex AI code executor (requires extensions)."""
110
111
def __init__(
112
self,
113
project_id: str,
114
location: str = "us-central1",
115
**kwargs
116
):
117
"""
118
Initialize Vertex AI code executor.
119
120
Args:
121
project_id (str): Google Cloud project ID
122
location (str): Vertex AI location
123
**kwargs: Additional configuration parameters
124
"""
125
pass
126
127
class ContainerCodeExecutor(BaseCodeExecutor):
128
"""Container-based code executor (requires extensions)."""
129
130
def __init__(
131
self,
132
container_image: str,
133
docker_config: dict = None,
134
**kwargs
135
):
136
"""
137
Initialize container code executor.
138
139
Args:
140
container_image (str): Docker container image
141
docker_config (dict, optional): Docker configuration
142
**kwargs: Additional configuration parameters
143
"""
144
pass
145
146
class CodeExecutorContext:
147
"""Context for code execution."""
148
149
def __init__(
150
self,
151
session_id: str = None,
152
variables: dict = None,
153
working_directory: str = None,
154
**kwargs
155
):
156
"""
157
Initialize code execution context.
158
159
Args:
160
session_id (str, optional): Session identifier
161
variables (dict, optional): Pre-defined variables
162
working_directory (str, optional): Working directory
163
**kwargs: Additional context parameters
164
"""
165
pass
166
167
def set_variable(self, name: str, value: any):
168
"""
169
Set context variable.
170
171
Args:
172
name (str): Variable name
173
value (any): Variable value
174
"""
175
pass
176
177
def get_variable(self, name: str, default=None):
178
"""
179
Get context variable.
180
181
Args:
182
name (str): Variable name
183
default: Default value if not found
184
185
Returns:
186
Variable value or default
187
"""
188
pass
189
```
190
191
## Usage Examples
192
193
### Basic Code Execution
194
195
```python
196
from google.adk.code_executors import BuiltInCodeExecutor
197
198
# Create safe code executor
199
executor = BuiltInCodeExecutor(
200
allowed_modules=["math", "json", "datetime"],
201
timeout=30,
202
max_memory=256
203
)
204
205
# Execute Python code
206
result = executor.execute(
207
code="""
208
import math
209
result = math.sqrt(16) + 5
210
print(f"Result: {result}")
211
""",
212
language="python"
213
)
214
215
print(f"Output: {result['output']}")
216
print(f"Errors: {result['errors']}")
217
print(f"Exit Code: {result['exit_code']}")
218
```
219
220
### Code Execution with Context
221
222
```python
223
from google.adk.code_executors import BuiltInCodeExecutor, CodeExecutorContext
224
225
executor = BuiltInCodeExecutor()
226
227
# Create execution context with pre-defined variables
228
context = CodeExecutorContext(
229
session_id="analysis-session",
230
variables={
231
"data": [1, 2, 3, 4, 5],
232
"threshold": 3
233
}
234
)
235
236
# Execute code with context
237
result = executor.execute(
238
code="""
239
# Variables from context are available
240
filtered_data = [x for x in data if x > threshold]
241
print(f"Filtered data: {filtered_data}")
242
average = sum(filtered_data) / len(filtered_data)
243
print(f"Average: {average}")
244
""",
245
language="python",
246
context=context
247
)
248
```
249
250
### Agent with Code Execution
251
252
```python
253
from google.adk.agents import Agent
254
from google.adk.code_executors import BuiltInCodeExecutor
255
from google.adk.tools import FunctionTool
256
257
# Create code executor
258
code_executor = BuiltInCodeExecutor(
259
allowed_modules=["pandas", "numpy", "matplotlib"],
260
timeout=60
261
)
262
263
# Create code execution tool
264
def execute_python_code(code: str) -> dict:
265
"""Execute Python code safely."""
266
return code_executor.execute(code, "python")
267
268
code_tool = FunctionTool(
269
func=execute_python_code,
270
name="python_executor",
271
description="Execute Python code for data analysis"
272
)
273
274
# Create agent with code execution capability
275
data_agent = Agent(
276
name="data_scientist",
277
model="gemini-2.0-flash",
278
instruction="Help with data analysis using Python code execution",
279
tools=[code_tool]
280
)
281
282
# Agent can now execute code
283
response = data_agent.run(
284
"Analyze this dataset: [1, 5, 3, 8, 2, 9, 4]. "
285
"Calculate mean, median, and standard deviation."
286
)
287
```
288
289
### Unsafe Local Execution (Development Only)
290
291
```python
292
from google.adk.code_executors import UnsafeLocalCodeExecutor
293
294
# Only use in development environments
295
executor = UnsafeLocalCodeExecutor(
296
working_directory="/tmp/code_execution",
297
timeout=30
298
)
299
300
# Can execute system commands and access filesystem
301
result = executor.execute(
302
code="""
303
import os
304
print(f"Current directory: {os.getcwd()}")
305
print(f"Files: {os.listdir('.')}")
306
307
# Write a file
308
with open("output.txt", "w") as f:
309
f.write("Hello from code execution!")
310
""",
311
language="python"
312
)
313
314
print(result['output'])
315
```
316
317
### Container-Based Execution
318
319
```python
320
from google.adk.code_executors import ContainerCodeExecutor
321
322
# Configure container executor
323
executor = ContainerCodeExecutor(
324
container_image="python:3.9-slim",
325
docker_config={
326
"memory_limit": "512m",
327
"cpu_limit": "1",
328
"network_mode": "none" # No network access
329
}
330
)
331
332
# Execute code in container
333
result = executor.execute(
334
code="""
335
import sys
336
print(f"Python version: {sys.version}")
337
print("Running in container!")
338
339
# Install and use a package
340
import subprocess
341
subprocess.run(["pip", "install", "requests"], check=True)
342
343
import requests
344
print("Requests library installed successfully")
345
""",
346
language="python"
347
)
348
```
349
350
### Vertex AI Code Execution
351
352
```python
353
from google.adk.code_executors import VertexAiCodeExecutor
354
355
# Configure Vertex AI executor
356
executor = VertexAiCodeExecutor(
357
project_id="my-project",
358
location="us-central1"
359
)
360
361
# Execute code on Vertex AI
362
result = executor.execute(
363
code="""
364
import pandas as pd
365
import numpy as np
366
367
# Create sample dataset
368
data = pd.DataFrame({
369
'sales': np.random.randint(100, 1000, 100),
370
'region': np.random.choice(['North', 'South', 'East', 'West'], 100)
371
})
372
373
# Analyze by region
374
analysis = data.groupby('region')['sales'].agg(['mean', 'median', 'std'])
375
print(analysis)
376
""",
377
language="python"
378
)
379
```
380
381
### Multi-Language Support
382
383
```python
384
from google.adk.code_executors import BuiltInCodeExecutor
385
386
executor = BuiltInCodeExecutor()
387
388
# Check supported languages
389
languages = executor.get_supported_languages()
390
print(f"Supported languages: {languages}")
391
392
# Execute different languages
393
languages_to_test = ["python", "javascript", "sql"]
394
395
for lang in languages_to_test:
396
if executor.is_supported_language(lang):
397
print(f"Executing {lang}...")
398
399
if lang == "python":
400
code = "print('Hello from Python!')"
401
elif lang == "javascript":
402
code = "console.log('Hello from JavaScript!');"
403
elif lang == "sql":
404
code = "SELECT 'Hello from SQL!' as message;"
405
406
result = executor.execute(code, lang)
407
print(f"Output: {result['output']}")
408
```
409
410
### Error Handling and Debugging
411
412
```python
413
from google.adk.code_executors import BuiltInCodeExecutor
414
415
executor = BuiltInCodeExecutor()
416
417
# Execute code with potential errors
418
result = executor.execute(
419
code="""
420
try:
421
x = 10 / 0 # This will cause an error
422
except ZeroDivisionError as e:
423
print(f"Caught error: {e}")
424
x = 0
425
426
print(f"Final value: {x}")
427
428
# Also cause a syntax error
429
print("This line is fine")
430
invalid_syntax = 1 + # This is invalid
431
""",
432
language="python"
433
)
434
435
print(f"Exit code: {result['exit_code']}")
436
print(f"Output: {result['output']}")
437
print(f"Errors: {result['errors']}")
438
print(f"Execution time: {result.get('execution_time', 'N/A')}")
439
```
440
441
### Persistent Session Execution
442
443
```python
444
from google.adk.code_executors import BuiltInCodeExecutor, CodeExecutorContext
445
446
executor = BuiltInCodeExecutor()
447
448
# Create persistent context
449
context = CodeExecutorContext(session_id="data-analysis-session")
450
451
# Execute code in steps, maintaining state
452
step1_result = executor.execute(
453
code="""
454
import pandas as pd
455
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
456
print("DataFrame created")
457
print(df)
458
""",
459
language="python",
460
context=context
461
)
462
463
# Continue with same context - df is still available
464
step2_result = executor.execute(
465
code="""
466
# df is still available from previous execution
467
df['C'] = df['A'] + df['B']
468
print("Added column C")
469
print(df)
470
total = df['C'].sum()
471
print(f"Total of column C: {total}")
472
""",
473
language="python",
474
context=context
475
)
476
```