Code

描述

Code API提供在AgentBay云环境中执行代码,并设置超时时间的方法。

方法

说明

RunCode

在指定的编程语言环境中执行代码,并设置超时时间。

属性

属性名(Property)

说明(Description)

code

需要执行的代码字符串。

language

代码的编程语言,仅限 python 或 javascript

timeout_s

代码执行的超时时间(单位:秒),默认值为 300 秒。

方法

Run_code - 同步指定上下文

Golang

RunCode(code string, language string, timeoutS ...int) (*CodeResult, error)

参数:

  • code (str):需要执行的代码字符串。

  • language (str):代码的编程语言,仅限 Python 或 Javascript

  • timeout_s (int, optional):代码执行的超时时间(单位:秒),默认值为 300 秒。

返回值:

  • CodeResult:返回结果对象,包含执行结果及请求 ID。

  • error:若操作失败,返回错误信息。

示例:

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) -> CodeExecutionResult

参数:

  • code (str):需要执行的代码字符串。

  • language (str):代码的编程语言,仅限 Python 或 Javascript

  • timeout_s (int, optional):代码执行的超时时间(单位:秒),默认值为 300 秒。

返回值:

  • CodeExecutionResult:结果对象,包含执行成功状态、执行结果、错误信息及请求 ID。

示例:

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>

参数:

  • code (str):需要执行的代码字符串。

  • language (str):代码的编程语言,仅限 Python 或 Javascript

  • timeout_s (int, optional):代码执行的超时时间(单位:秒),默认值为 300 秒。

返回值:

  • Promise<CodeExecutionResult>:返回结果对象,包含执行成功状态、执行结果、错误信息及请求 ID。

示例:

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);