Description
The Code API lets you execute code in the AgentBay cloud environment and set a timeout.
Method | Description |
RunCode | Execute code in a specified programming language environment and set a timeout. |
Properties
Property | Description |
| The code string to execute. |
| The programming language for the code. Valid values are |
| The timeout for code execution in seconds. The default value is 300 seconds. |
Methods
Run_code - Sync specified context
Golang
RunCode(code string, language string, timeoutS ...int) (*CodeResult, error)Parameters
code (string): The code to execute.language (string): The programming language of the code. Valid values arePythonandJavascript.timeout_s (int, optional): The timeout for code execution, in seconds. The default is 300.
Return value
CodeResult: The result object, which contains the execution result and the request ID.error: The error message if the operation failed.
Example
package main
import (
"fmt"
"os"
"github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)
func main() {
// Initialize AgentBay with API key
client, err := agentbay.NewAgentBay("your_api_key")
if err != nil {
fmt.Printf("Error initializing AgentBay client: %v\n", err)
os.Exit(1)
}
// Create a session with code_latest image
params := &agentbay.CreateSessionParams{
ImageId: "code_latest",
}
sessionResult, err := client.Create(params)
if err != nil {
fmt.Printf("Error creating session: %v\n", err)
os.Exit(1)
}
session := sessionResult.Session
// Execute Python code
pythonCode := `
print("Hello from Python!")
result = 2 + 3
print(f"Result: {result}")
`
codeResult, err := session.Code.RunCode(pythonCode, "python")
if err != nil {
fmt.Printf("Error executing Python code: %v\n", err)
} else {
fmt.Printf("Python code output:\n%s\n", codeResult.Output)
fmt.Printf("Request ID: %s\n", codeResult.RequestID)
}
// Execute JavaScript code
jsCode := `
console.log("Hello from JavaScript!");
const result = 2 + 3;
console.log("Result:", result);
`
jsResult, err := session.Code.RunCode(jsCode, "javascript", 30)
if err != nil {
fmt.Printf("Error executing JavaScript code: %v\n", err)
} else {
fmt.Printf("JavaScript code output:\n%s\n", jsResult.Output)
fmt.Printf("Request ID: %s\n", jsResult.RequestID)
}
}Python
run_code(code: str, language: str, timeout_s: int = 300) -> CodeExecutionResultParameters
code (str): The code to execute.language (str): The programming language of the code. Valid values arePythonandJavascript.timeout_s (int, optional): The timeout period for code execution, in seconds. The default value is 300.
Return value
CodeExecutionResult: The result object, which contains the success status, execution result, error message, and request ID.
Example
import os
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
# Initialize AgentBay with API key
api_key = os.getenv("AGENTBAY_API_KEY")
agent_bay = AgentBay(api_key=api_key)
# Create a session with code_latest image
params = CreateSessionParams(image_id="code_latest")
session_result = agent_bay.create(params)
if session_result.success:
session = session_result.session
else:
print(f"Failed to create session: {session_result.error_message}")
exit(1)
# Execute Python code
python_code = """
print("Hello from Python!")
result = 2 + 3
print(f"Result: {result}")
"""
code_result = session.code.run_code(python_code, "python")
if code_result.success:
print(f"Python code output:\n{code_result.result}")
print(f"Request ID: {code_result.request_id}")
else:
print(f"Code execution failed: {code_result.error_message}")
# Execute JavaScript code
js_code = """
console.log("Hello from JavaScript!");
const result = 2 + 3;
console.log("Result:", result);
"""
js_result = session.code.run_code(js_code, "javascript", timeout_s=30)
if js_result.success:
print(f"JavaScript code output:\n{js_result.result}")
print(f"Request ID: {js_result.request_id}")
else:
print(f"Code execution failed: {js_result.error_message}")TypeScript
runCode(code: string, language: string, timeoutS: number = 300): Promise<CodeExecutionResult>Parameters
code (string): The code to execute.language (string): The programming language of the code. Valid values arePythonandJavascript.timeout_s (int, optional): The timeout for code execution in seconds. The default is 300.
Return value
Promise<CodeExecutionResult>: The result object, which contains the success status, execution result, error message, and request ID.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
async function main() {
// Initialize AgentBay with API key
const apiKey = process.env.AGENTBAY_API_KEY!;
const agentBay = new AgentBay({ apiKey });
// Create a session with code_latest image
const sessionResult = await agentBay.create({
imageId: "code_latest"
});
if (!sessionResult.success) {
console.error(`Failed to create session: ${sessionResult.errorMessage}`);
return;
}
const session = sessionResult.session;
// Execute Python code
const pythonCode = `
print("Hello from Python!")
result = 2 + 3
print(f"Result: {result}")
`;
const codeResult = await session.code.runCode(pythonCode, "python");
if (codeResult.success) {
console.log(`Python code output:\n${codeResult.result}`);
console.log(`Request ID: ${codeResult.requestId}`);
} else {
console.error(`Code execution failed: ${codeResult.errorMessage}`);
}
// Execute JavaScript code
const jsCode = `
console.log("Hello from JavaScript!");
const result = 2 + 3;
console.log("Result:", result);
`;
const jsResult = await session.code.runCode(jsCode, "javascript", 30);
if (jsResult.success) {
console.log(`JavaScript code output:\n${jsResult.result}`);
console.log(`Request ID: ${jsResult.requestId}`);
} else {
console.error(`Code execution failed: ${jsResult.errorMessage}`);
}
}
main().catch(console.error);