Code Execution Tool
Run code in a secure sandbox for calculations and data analysis.
Overview
The code execution tool runs Python and JavaScript code in an isolated, secure environment. It's perfect for calculations, data analysis, and testing code.
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
code | string | Yes | - | Code to execute |
language | string | No | python | Programming language (python, javascript) |
timeout | integer | No | 30 | Execution timeout in seconds |
allowed_libraries | array | No | all | List of allowed libraries |
Usage Examples
Basic Python Execution
import requests
response = requests.post(
"http://localhost/api/v1/agent/tool-calling",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"tool_name": "code_execution",
"parameters": {
"code": "print(2 + 2)",
"language": "python"
}
}
)
result = response.json()
print(f"Output: {result['output']}")
Data Analysis
response = requests.post(
"http://localhost/api/v1/agent/tool-calling",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"tool_name": "code_execution",
"parameters": {
"code": """
import statistics
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mean = statistics.mean(data)
median = statistics.median(data)
std = statistics.stdev(data)
print(f"Mean: {mean}")
print(f"Median: {median}")
print(f"Std Dev: {std}")
""",
"language": "python"
}
}
)
print(response.json()["output"])
JavaScript Execution
response = requests.post(
"http://localhost/api/v1/agent/tool-calling",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"tool_name": "code_execution",
"parameters": {
"code": "console.log(2 * 21);",
"language": "javascript"
}
}
)
print(response.json()["output"])
Plotting with Matplotlib
response = requests.post(
"http://localhost/api/v1/agent/tool-calling",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"tool_name": "code_execution",
"parameters": {
"code": """
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title('Sample Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.savefig('/tmp/plot.png')
print('Plot saved successfully')
""",
"language": "python",
"allowed_libraries": ["matplotlib"]
}
}
)
Use in Agent
# Create agent with code execution
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "analyst_agent",
"system_prompt": "You are a data analyst. Use code execution to perform calculations and data analysis.",
"model": "gpt-4",
"builtin_tools": ["code_execution"],
"tool_config": {
"code_execution": {
"timeout": 60,
"allowed_libraries": ["pandas", "numpy", "matplotlib", "scipy"]
}
},
"tool_choice": "auto",
"max_iterations": 5
}
)
agent_id = response.json()["id"]
# Chat with agent
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "Calculate the average and standard deviation of these numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
}
)
result = chat_response.json()
print(f"Response: {result['response']}")
JavaScript Usage
const response = await fetch('http://localhost/api/v1/agent/tool-calling', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
tool_name: 'code_execution',
parameters: {
code: 'console.log(Math.sqrt(16));',
language: 'javascript'
}
})
});
const result = await response.json();
console.log('Output:', result.output);
cURL Usage
curl -X POST http://localhost/api/v1/agent/tool-calling \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"tool_name": "code_execution",
"parameters": {
"code": "import math\nprint(math.pi * 2)",
"language": "python"
}
}'
Response Format
Success
{
"output": "6.283185307179586",
"executed_code": "import math\nprint(math.pi * 2)",
"execution_time": 0.5,
"error": null
}
Error
{
"output": null,
"executed_code": "...",
"execution_time": 0.3,
"error": "SyntaxError: invalid syntax"
}
Supported Libraries
Python
Common libraries available:
pandas- Data manipulationnumpy- Numerical computingmatplotlib- Plottingscipy- Scientific computingrequests- HTTP requestsjson- JSON handling
JavaScript
Built-in APIs:
console- LoggingMath- Math functionsDate- Date/timeJSON- JSON parsing
Use Cases
Calculations
code = """
# Calculate compound interest
principal = 10000
rate = 0.05
years = 10
amount = principal * (1 + rate) ** years
print(f"Amount: ${amount:.2f}")
"""
Data Processing
code = """
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
print(f"Average age: {df['Age'].mean()}")
print(f"Max age: {df['Age'].max()}")
"""
Testing Code
code = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(f"fib(10) = {fibonacci(10)}")
"""
Security Considerations
Sandbox Environment
- Isolated execution environment
- No file system access
- No network access (unless configured)
- Limited memory and CPU
- Automatic cleanup after execution
Allowed Operations
✅ Allowed:
- Mathematical calculations
- Data processing
- String manipulation
- Logic operations
- Built-in library functions
❌ Not Allowed:
- File system operations
- Network requests
- System commands
- Infinite loops
Best Practices
- Set timeouts - Prevent infinite loops
- Validate code - Check for syntax errors before execution
- Limit libraries - Only allow necessary libraries
- Handle errors - Catch and display execution errors
- Monitor performance - Track execution time and resource usage
Troubleshooting
Timeout
Problem: Code execution times out
Solution:
- Increase
timeoutparameter - Optimize code for performance
- Remove infinite loops
- Simplify complex calculations
Syntax Error
Problem: Code has syntax errors
Solution:
- Validate code before sending
- Check indentation
- Verify function definitions
- Review error messages
Library Not Available
Problem: Library import fails
Solution:
- Add library to
allowed_libraries - Use available alternatives
- Check library spelling
- Verify library compatibility
Memory Error
Problem: Code uses too much memory
Solution:
- Optimize data structures
- Use streaming for large datasets
- Reduce data size
- Implement chunked processing
Next Steps
- RAG Search Tool - Search your documents
- Web Search Tool - Search internet
- Agent Documentation - Use code execution in agents