本文介紹如何使用無影 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 Gateway,如果需要通過其他地區(例如新加坡)進行串連,需要配置不同的網關以獲得更好的網路效能。
支援的 API Gateway地區
SDK 配置指定要串連到哪個API Gateway。建議選擇距離使用者最近的網關,以獲得最佳網路效能。
網關位置 | 端點 |
上海(預設) |
|
新加坡 |
|
切換到新加坡網關
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 Gateway端點是否適合您的位置。
如果可以的話,嘗試不同的網關端點以獲得更好的串連。
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 任務、 |
| 瀏覽器 | 網頁抓取、瀏覽器自動化、測試網站 |
| 代碼沙箱 | 編碼、開發工具、編程任務 |
| 雲手機 | 行動裝置 App測試、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, "/tmp/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("/tmp/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