SDK接入指南

更新时间: 2025-08-26 09:48:20

AgentBay SDK提供了一整套全面的工具,以便与AgentBay云环境进行高效交互,使您能够创建和管理云会话、执行命令、操作文件以及与用户界面进行交互。

获取API Key

创建API Key

说明
  • 如您的账号尚未进行实名认证,请在完成个人或企业实名认证后使用该功能。更多操作,请参见个人实名认证企业实名认证

  • 公测期间最多可以创建10个API Key。

您可以为项目创建API Key,以灵活选择可用的虚拟化云服务和 MCP 镜像范围。

  1. 登录AgentBay控制台

  2. 在左侧导航栏中单击服务管理

  3. 服务管理页面上单击创建API KEY

  4. 创建API KEY对话框中输入名称,并单击确定

    重要

    为保障您的数据安全,请不要与他人共享您的API Key。

查看API Key

  • 查看:服务管理页面上,在目标API KEY的API KEY名称/值列中单击查看图标。

  • 复制:服务管理页面上,在目标API KEY的API KEY名称/值列中单击复制图标。

说明

关于管理API Key的更多操作,请参见创建和管理API Key

安装

pip install wuying-agentbay-sdk
go get github.com/aliyun/wuying-agentbay-sdk/golang
npm install wuying-agentbay-sdk

身份验证

要使用 AgentBay SDK,您需要配置API 密钥。您可以通过以下任一方式设置 API 密钥:

说明

有关获取密钥的更多信息,请参见获取API Key

有关身份验证的更多信息,请参见身份验证指南

设置环境变量

export AGENTBAY_API_KEY=your_api_key

直接传递 API 密钥

// Golang
package main

import (
    "github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)

func main() {
    client, _ := agentbay.NewAgentBay("your_api_key", nil)
    // Use client...
}
# Python
from agentbay import AgentBay

agent_bay = AgentBay(api_key="your_api_key")
// TypeScript
import { AgentBay } from 'wuying-agentbay-sdk';

const agentBay = new AgentBay({ apiKey: 'your_api_key' });

基本用法

本文为您提供一些基本用法的案例,可以帮您快速了解AgentBay的主要功能。

创建会话

from agentbay import AgentBay

agent_bay = AgentBay()
result = agent_bay.create()

if result.success:
    session = result.session
    print(f"Session created with ID: {session.session_id}")
package main

import (
    "fmt"
    "github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)

func main() {
    client, err := agentbay.NewAgentBay("", nil)
    if err != nil {
        fmt.Printf("Error initializing client: %v\n", err)
        return
    }

    result, err := client.Create(nil)
    if err != nil {
        fmt.Printf("Error creating session: %v\n", err)
        return
    }

    fmt.Printf("Session created with ID: %s\n", result.Session.SessionID)
}
import { AgentBay } from 'wuying-agentbay-sdk';

const agentBay = new AgentBay();
const result = await agentBay.create();

if (result.success) {
    const session = result.session;
    console.log(`Session created with ID: ${session.sessionId}`);
}

命令执行

command_result = session.command.execute("ls -la")
if command_result.success:
    print(f"Output: {command_result.data.stdout}")
const commandResult = await session.command.execute('ls -la');
if (commandResult.success) {
    console.log(`Output: ${commandResult.data.stdout}`);
}
commandResult, err := session.Command.Execute("ls -la")
if err != nil {
    fmt.Printf("Error executing command: %v\n", err)
    return
}

fmt.Printf("Output: %s\n", commandResult.Data.Stdout)

写入与读取文件

# Write a file
write_result = session.file_system.write_file(
    path="/tmp/test.txt",
    content="Hello, World!"
)

# Read a file
read_result = session.file_system.read_file(path="/tmp/test.txt")
if read_result.success:
    print(f"File content: {read_result.data}")
// Write a file
_, err = session.FileSystem.WriteFile(
    "/tmp/test.txt",
    []byte("Hello, World!"),
)
if err != nil {
    fmt.Printf("Error writing file: %v\n", err)
    return
}

// Read a file
readResult, err := session.FileSystem.ReadFile("/tmp/test.txt")
if err != nil {
    fmt.Printf("Error reading file: %v\n", err)
    return
}

fmt.Printf("File content: %s\n", string(readResult.Data))
// Write a file
const writeResult = await session.fileSystem.writeFile(
    '/tmp/test.txt',
    'Hello, World!'
);

// Read a file
const readResult = await session.fileSystem.readFile('/tmp/test.txt');
if (readResult.success) {
    console.log(`File content: ${readResult.data}`);
}

使用持久化上下文

from agentbay import AgentBay
from agentbay.context_sync import ContextSync, SyncPolicy
from agentbay.session_params import CreateSessionParams

# Initialize the client
agent_bay = AgentBay()

# Get or create a context
context_result = agent_bay.context.get("my-persistent-context", create=True)

if context_result.success:
    context = context_result.context
    
    # Create a session with context synchronization
    context_sync = ContextSync.new(
        context_id=context.id,
        path="/mnt/data",  # Mount path in the session
        policy=SyncPolicy.default()
    )
    
    params = CreateSessionParams(context_syncs=[context_sync])
    session_result = agent_bay.create(params)
package main

import (
    "fmt"
    "github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)

func main() {
    // Initialize the client
    client, _ := agentbay.NewAgentBay("", nil)
    
    // Get or create a context
    contextResult, _ := client.Context.Get("my-persistent-context", true)
    
    // Create a session with context synchronization
    policy := agentbay.NewSyncPolicy()
    contextSync := agentbay.NewContextSync(
        contextResult.Context.ID,
        "/mnt/data",  // Mount path in the session
        policy,
    )
    
    params := agentbay.NewCreateSessionParams().
        AddContextSyncConfig(contextSync)
    
    sessionResult, _ := client.Create(params)
}
import { AgentBay, ContextSync, SyncPolicy } from 'wuying-agentbay-sdk';

// Initialize the client
const agentBay = new AgentBay();

// Get or create a context
const contextResult = await agentBay.context.get('my-persistent-context', true);

if (contextResult.success) {
    const context = contextResult.context;
    
    // Create a session with context synchronization
    const contextSync = new ContextSync({
        contextId: context.id,
        path: '/mnt/data',  // Mount path in the session
        policy: SyncPolicy.default()
    });
    
    const sessionResult = await agentBay.create({
        contextSync: [contextSync]
    });
}

后续步骤

现在您已经了解了使用AgentBay SDK的基础知识,您可以了解更多功能:

工具

描述

环境(镜像)

ComputerUse

ComputerUse

BrowserUse

CodeSpace

MobileUse

Windows

Ubantu

Debian

Debian

Android

Sessions

进行会话生命周期管理。

支持

支持

支持

支持

支持

FileSystem

提供文件系统操作(如上传、下载和管理)。

支持

支持

支持

支持

暂不支持

OSS

提供对象存储服务(OSS)集成。

支持

支持

暂不支持

支持

支持

Context

管理会话中的上下文数据。

支持

支持

支持

支持

支持

Command

提供在会话中执行命令的功能。

支持

支持

支持

支持

支持

UI

在会话中提供界面交互功能。

暂不支持

暂不支持

暂不支持

不涉及

支持

Application

管理应用程序的操作和状态。

支持

暂不支持

暂不支持

不支持

支持

上一篇: 开发参考 下一篇: Sessions