💡 Async Version: This documentation covers the synchronous API. For async/await support, see
AsyncCodewhich provides the same functionality with async methods.
- Code Execution Guide - Execute code in isolated environments
The Code module provides secure code execution capabilities in isolated environments. It supports multiple programming languages including Python, JavaScript, and more.
- Requires
code_latestimage for code execution features
class Code(BaseService)Handles code execution operations in the AgentBay cloud environment.
def run_code(code: str,
language: str,
timeout_s: int = 60) -> EnhancedCodeExecutionResultExecute code in the specified language with a timeout.
Arguments:
code: The code to execute.
language: The programming language of the code. Case-insensitive.
Supported values: 'python', 'javascript', 'r', 'java'. timeout_s: The timeout for the code execution in seconds. Default is 60s. Note: Due to gateway limitations, each request cannot exceed 60 seconds.
Returns:
EnhancedCodeExecutionResult: Result object containing success status, execution
result, and error message if any.
Raises:
CommandError: If the code execution fails or if an unsupported language is
specified.
Important:
The run_code method requires a session created with the code_latest
image to function properly. If you encounter errors indicating that the
tool is not found, make sure to create your session with
image_id="code_latest" in the CreateSessionParams.
Example:
Execute Python code in a code execution environment
from agentbay import AgentBay, CreateSessionParams
agent_bay = AgentBay(api_key="your_api_key")
result = agent_bay.create(CreateSessionParams(image_id="code_latest"))
code_result = result.session.code.run_code("print('Hello')", "python")
print(code_result.result)
result.session.delete()def run(code: str,
language: str,
timeout_s: int = 60) -> EnhancedCodeExecutionResultAlias of run_code() for better ergonomics and LLM friendliness.
def execute(code: str,
language: str,
timeout_s: int = 60) -> EnhancedCodeExecutionResultAlias of run_code() for better ergonomics and LLM friendliness.
- Validate code syntax before execution
- Set appropriate execution timeouts
- Handle execution errors and exceptions
- Use proper resource limits to prevent resource exhaustion
- Clean up temporary files after code execution
Related APIs:
Documentation generated automatically from source code using pydoc-markdown.