本文介绍如何使用无影 AgentBay 软件开发工具包 (SDK) 的核心概念,并完成环境准备、认证配置以及创建和操作第一个云会话的完整流程。
环境设置
系统要求
Python
Python
3.10及以上版本。pip or poetry
TypeScript/JavaScript
Node.js 14及以上版本。
npm or yarn
Golang
Go
1.24.4及以上版本。
快速安装
Python
推荐:使用虚拟环境
# Create and activate virtual environment
python3 -m venv agentbay-env
source agentbay-env/bin/activate # Linux/macOS
# agentbay-env\Scripts\activate # Windows
# Install the package
pip install wuying-agentbay-sdk
# Verify installation
python -c "import agentbay; print('Installation successful')"替代方案:使用系统 Python(如果允许)
# Install with user flag (if system allows)
pip install --user wuying-agentbay-sdk
# Verify installation
python -c "import agentbay; print('Installation successful')"TypeScript/JavaScript
# Initialize project (if new project)
mkdir my-agentbay-project && cd my-agentbay-project
npm init -y
# Install the package
npm install wuying-agentbay-sdk
# Verify installation
node -e "const {AgentBay} = require('wuying-agentbay-sdk'); console.log('Installation successful')"Golang
# Initialize module (if new project)
mkdir my-agentbay-project && cd my-agentbay-project
go mod init my-agentbay-project
# Install the package
GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay
# Verify installation
go list -m github.com/aliyun/wuying-agentbay-sdk/golang && echo "Installation successful"API 密钥设置
获取 API 密钥
在左侧导航栏选择服务管理,单击目标API KEY的复制按钮。
说明若无可用API KEY,单击创建API KEY,输入名称并单击确定,创建一个API KEY。
设置环境变量
Linux/macOS:
export AGENTBAY_API_KEY=your_api_key_hereWindows:
setx AGENTBAY_API_KEY your_api_key_here安装验证
Python
import os
from agentbay import AgentBay
# Get API key from environment
api_key = os.getenv("AGENTBAY_API_KEY")
if not api_key:
print("Please set AGENTBAY_API_KEY environment variable")
exit(1)
try:
# Initialize SDK
agent_bay = AgentBay(api_key=api_key)
print("SDK initialized successfully")
# Create a session (requires valid API key and network)
session_result = agent_bay.create()
if session_result.success:
session = session_result.session
print(f"Session created: {session.session_id}")
# Clean up
agent_bay.delete(session)
print("Test completed successfully")
else:
print(f"Session creation failed: {session_result.error_message}")
except Exception as e:
print(f"Error: {e}")TypeScript
import { AgentBay } from 'wuying-agentbay-sdk';
const apiKey = process.env.AGENTBAY_API_KEY;
if (!apiKey) {
console.log("Please set AGENTBAY_API_KEY environment variable");
process.exit(1);
}
async function test() {
try {
// Initialize SDK
const agentBay = new AgentBay({ apiKey });
console.log("SDK initialized successfully");
// Create a session (requires valid API key and network)
const sessionResult = await agentBay.create();
if (sessionResult.success) {
const session = sessionResult.session;
console.log(`Session created: ${session.sessionId}`);
// Clean up
await agentBay.delete(session);
console.log("Test completed successfully");
} else {
console.log(`Session creation failed: ${sessionResult.errorMessage}`);
}
} catch (error) {
console.log(`Error: ${error}`);
}
}
test();Golang
package main
import (
"fmt"
"os"
"github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)
func main() {
// Get API key from environment
apiKey := os.Getenv("AGENTBAY_API_KEY")
if apiKey == "" {
fmt.Println("Please set AGENTBAY_API_KEY environment variable")
return
}
// Initialize SDK
client, err := agentbay.NewAgentBay(apiKey, nil)
if err != nil {
fmt.Printf("Failed to initialize SDK: %v\n", err)
return
}
fmt.Println("SDK initialized successfully")
// Create a session (requires valid API key and network)
sessionResult, err := client.Create(nil)
if err != nil {
fmt.Printf("Session creation failed: %v\n", err)
return
}
if sessionResult.Session != nil {
fmt.Printf("Session created: %s\n", sessionResult.Session.SessionID)
// Clean up
_, err = client.Delete(sessionResult.Session, false)
if err != nil {
fmt.Printf("Session cleanup failed: %v\n", err)
} else {
fmt.Println("Test completed successfully")
}
}
}高级配置(可选)
SDK 默认使用上海 API 网关,如果需要通过其他区域(例如新加坡)进行连接,需要配置不同的网关以获得更好的网络性能。
支持的 API 网关区域
SDK 配置指定要连接到哪个API 网关。建议选择距离用户最近的网关,以获得最佳网络性能。
网关位置 | 端点 |
上海(默认) |
|
新加坡 |
|
切换到新加坡网关
Linux/macOS:
export AGENTBAY_ENDPOINT=wuyingai.ap-southeast-1.aliyuncs.comWindows:
set AGENTBAY_ENDPOINT=wuyingai.ap-southeast-1.aliyuncs.com故障排除
Python 问题
externally-managed-environment错误:
# Solution: Use virtual environment
python3 -m venv agentbay-env
source agentbay-env/bin/activate
pip install wuying-agentbay-sdkModuleNotFoundError: No module named 'agentbay':
# Check if virtual environment is activated
which python # Should show venv path
# Re-install if needed
pip install --force-reinstall wuying-agentbay-sdkTypeScript 问题
Cannot find module 'wuying-agentbay-sdk':
# Ensure you're in the project directory with package.json
pwd
ls package.json # Should exist
# Re-install if needed
npm install wuying-agentbay-sdkrequire() is not defined:
# Check Node.js version (requires 14+)
node --version
# Ensure you're using CommonJS (default) or update to ES modulesGolang 问题
checksum mismatch错误(最常见):
# Always use direct proxy for this package
GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay导入路径错误:
# Check Go version (requires 1.24.4+)
go version
# Ensure module is initialized
go mod init your-project-name构建失败:
# Clean module cache and retry
go clean -modcache
go mod tidy
go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay网络和 API 问题
连接超时:
检查网络连接。
验证 API 网关端点是否适合您的位置。
如果可以的话,尝试不同的网关端点以获得更好的连接。
API 密钥错误:
验证 API 密钥是否正确且有效。
在控制台中检查 API 密钥权限。
确保环境变量设置正确。
会话创建失败:
验证账户是否有足够的配额。
在控制台检查服务状态。
几分钟后再试。
核心概念
AgentBay类
AgentBay类是与云服务交互的主要接口,包括以下核心功能:
会话管理器:创建、删除和管理云会话。
API 客户端:处理与 AgentBay 云服务的所有通信。
身份验证处理程序:自动管理 API 密钥和安全性。
基本使用模式
# 1. Initialize client
agent_bay = AgentBay()
# 2. Create session (uses linux_latest by default)
session = agent_bay.create().session
# 3. Use session for your tasks
# ... your automation tasks ...
# 4. Clean up resources
agent_bay.delete(session)
会话
会话是用户与云环境之间的连接。
主要特点
临时:会话在需要时创建,在完成后销毁。
隔离:每个会话与其他会话完全独立。
计费:需要为会话活跃的时间付费。
基本用法
# Create a session
session = agent_bay.create().session
# Use the session for your tasks
session.command.execute_command("echo 'Hello World'")
# Always clean up when done
agent_bay.delete(session)
会话生命周期
Create Session → Use Session → Delete Session
↓ ↓ ↓
Allocate Execute Release
Resources Operations Resources会话释放
完成后必须释放会话才能释放云资源。释放会话有两种方法:
手动释放(推荐)
# Explicitly delete when done
agent_bay.delete(session)
自动超时解除
如果没有手动删除,会话将在超时后自动释放。
前往无影 AgentBay 控制台,在左侧导航栏选择策略管理。
单击创建策略,将释放不活跃桌面设置为启用。
输入MCP交互终止后释放桌面与用户交互终止后释放桌面的超时时间。
单击创建策略。
在左侧导航栏选择服务管理,找到目标API KEY在操作列中单击 ⋮ 图标,。
选择查看/关联策略,在已关联策略区域单击关联策略,选择创建的策略,单击确定关联。
说明每个API KEY仅可关联一个策略,API KEY创建时将自动关联系统默认策略,需先解除关联。
镜像类型
官方系统镜像
下表为AgentBay官方提供的最新系统镜像。
图像 ID | 环境 | 适合的任务 |
| 云电脑 | 通用计算、服务器任务(未指定则为默认) |
| 云电脑 | 常规 Windows 任务、 |
| 浏览器 | 网页抓取、浏览器自动化、测试网站 |
| 代码沙箱 | 编码、开发工具、编程任务 |
| 云手机 | 移动应用测试、Android 自动化 |
如果未指定
image_id,AgentBay 将自动使用linux_latest作为默认环境。可以通过 AgentBay 控制台创建并使用自定义镜像,以满足特定需求。
选择正确的镜像
Windows环境示例
from agentbay.session_params import CreateSessionParams
# Create Windows environment and automate notepad
params = CreateSessionParams(image_id="windows_latest")
session = agent_bay.create(params).session
# Start Notepad application
session.computer.start_app("notepad.exe")
# Returns: ProcessListResult with started process info
# Input text into notepad
session.computer.input_text("Hello from Windows!")
# Returns: BoolResult with success status
agent_bay.delete(session)
浏览器环境示例
# Create browser environment
params = CreateSessionParams(image_id="browser_latest")
session = agent_bay.create(params).session
# Initialize and navigate
from agentbay.browser import BrowserOption
session.browser.initialize(BrowserOption())
session.browser.agent.navigate("https://www.baidu.com")
print("Web navigation successful")
agent_bay.delete(session)代码沙箱环境示例
# Create development environment and execute code
params = CreateSessionParams(image_id="code_latest")
session = agent_bay.create(params).session
# Execute code
result = session.code.run_code("print('Hello from CodeSpace!')", "python")
# Returns: CodeExecutionResult with output
# Example: result.result = "Hello from CodeSpace!"
agent_bay.delete(session)云手机环境示例
# Create Android environment and send HOME key
params = CreateSessionParams(image_id="mobile_latest")
session = agent_bay.create(params).session
# Press HOME key to return to home screen
from agentbay.mobile import KeyCode
session.mobile.send_key(KeyCode.HOME)
# Returns: BoolResult with success status
# Example: result.success = True (returns to Android home screen)
agent_bay.delete(session)
了解有关每个环境的更多信息
数据持久性
临时数据(默认行为)
默认情况下,会话中的所有数据都是临时的。
会话结束时所有内容都会丢失。
适用于处理任务、临时文件或缓存。
# This data will be LOST when session ends
session.file_system.write_file("/tmp/temp_data.txt", "This will disappear")
持久数据(上下文)
支持跨会话保留数据。
必须明确配置。
适用于项目文件、配置与重要结果。
from agentbay import ContextSync
# Create persistent storage
context = agent_bay.context.get("my-project", create=True).context
context_sync = ContextSync.new(context.id, "/persistent")
# Create session with persistent data
params = CreateSessionParams(context_syncs=[context_sync])
session = agent_bay.create(params).session
# This data will be SAVED across sessions
session.file_system.write_file("/persistent/important.txt", "This will persist")
如果需要保存数据,则必须使用 Context。否则会话结束后数据将永远丢失。
API 结果与请求 ID
API结果
当调用 AgentBay API 时,结果将封装在结果对象中。
# Example API call
screenshot = session.computer.screenshot()
# The result object contains:
print(screenshot.success) # True/False - whether the operation succeeded
print(screenshot.data) # Your actual data (screenshot URL)
print(screenshot.request_id) # Request ID for troubleshooting
请求 ID
对 AgentBay 的每个 API 调用都会获得一个唯一的请求 ID。结构类似"ABC12345-XXXX-YYYY-ZZZZ-123456789ABC"。
请求 ID 的用途
故障排除:如果出现问题,可以提供此 ID 以支持更快地解决问题。
跟踪:帮助跟踪日志中的单个操作。
调试:更容易识别哪个特定的 API 调用有问题。
何时需要使用请求 ID
API 调用意外失败。
特定操作的性能问题。
当联系支持人员咨询问题时。
故障排除示例
result = session.code.run_code("print('hello')", "python")
if not result.success:
print(f"Code execution failed! Request ID: {result.request_id}")
# Share this Request ID with support for faster help
创建会话
快速验证
使用简单示例验证配置是否正确。
import os
from agentbay import AgentBay
api_key = os.getenv("AGENTBAY_API_KEY")
agent_bay = AgentBay(api_key=api_key)
result = agent_bay.create()
if result.success:
session = result.session
cmd_result = session.command.execute_command("echo 'Hello from the cloud!'")
print(f"Cloud says: {cmd_result.output.strip()}")
agent_bay.delete(session)
else:
print(f"Failed: {result.error_message}")
# Expected output:
# Cloud says: Hello from the cloud!
云数据处理
通过以下代码,处理云中的数据文件。
import os
from agentbay import AgentBay
agent_bay = AgentBay(api_key=os.getenv("AGENTBAY_API_KEY"))
result = agent_bay.create()
session = result.session
try:
# 1. Create a Python script for data processing
script_content = '''
import json
import sys
data = {
"students": [
{"name": "Alice", "scores": [85, 92, 88]},
{"name": "Bob", "scores": [78, 85, 80]},
{"name": "Charlie", "scores": [92, 95, 98]}
]
}
results = []
for student in data["students"]:
avg = sum(student["scores"]) / len(student["scores"])
results.append({
"name": student["name"],
"average": round(avg, 2),
"grade": "A" if avg >= 90 else "B" if avg >= 80 else "C"
})
print(json.dumps(results, indent=2))
'''
# 2. Upload script to cloud
session.file_system.write_file("/tmp/process_data.py", script_content)
print("Script uploaded to cloud")
# 3. Execute the script in cloud environment
result = session.command.execute_command("python3 /tmp/process_data.py")
print(f"\n Processing results:\n{result.output}")
# Expected output:
# [
# {"name": "Alice", "average": 88.33, "grade": "B"},
# {"name": "Bob", "average": 81.0, "grade": "B"},
# {"name": "Charlie", "average": 95.0, "grade": "A"}
# ]
print("\n What happened:")
print(" 1. Uploaded Python script to cloud environment")
print(" 2. Executed script with pre-installed Python")
print(" 3. Got results back - all without local setup!")
finally:
agent_bay.delete(session)
print("\n Session cleaned up")
# Expected output includes JSON formatted student grades