全部產品
Search
文件中心

AgentBay:通過SDK接入

更新時間:Mar 17, 2026

本文介紹通過SDK接入無影AgentBay的流程,涵蓋SDK安裝、API密鑰擷取與配置,並提供兩個樣本以示範無影AgentBay的準系統。

準備工作

安裝SDK並配置環境

安裝SDK

Python

環境要求

Python 3.10及以上版本。

推薦:使用虛擬環境
# 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

環境要求

Node.js 14及以上版本。

# 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

環境要求

Go 1.24.4及以上版本。

# 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密鑰

  1. 前往無影 AgentBay 控制台

  2. 在左側導覽列選擇服務管理,單擊目標API KEY的複製按鈕。

    說明

    若無可用API KEY,單擊建立API KEY,輸入名稱並單擊確定,建立一個API KEY。

設定環境變數

Linux/macOS:

export AGENTBAY_API_KEY=your_api_key_here

Windows:

setx AGENTBAY_API_KEY your_api_key_here

安裝驗證

SDK安裝並完成API配置後,執行如下範例程式碼,當控制台返回Test completed successfully時,說明SDK安裝與環境配置成功。

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("Test completed 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")
        }
    }
}

故障排除

Python問題

  1. externally-managed-environment錯誤:

    # 解決方案:使用虛擬環境
    python3 -m venv agentbay-env
    source agentbay-env/bin/activate
    pip install wuying-agentbay-sdk
  2. ModuleNotFoundError: No module named 'agentbay'

    # 檢查虛擬環境是否已啟用
    which python  # Should show venv path
    # 如有需要重新安裝
    pip install --force-reinstall wuying-agentbay-sdk

TypeScript 問題

  1. Cannot find module 'wuying-agentbay-sdk'

    # 確保目前位於包含 package.json 的專案目錄中
    pwd
    ls package.json  # 驗證package.json檔案存在
    # 如有需要重新安裝
    npm install wuying-agentbay-sdk
  2. require() is not defined

    # 驗證 Node.js version (需要 14+)
    node --version
    # 確保正在使用 CommonJS(預設)或更新為 ES 模組

Golang 問題

  1. checksum mismatch錯誤(最常見):

    # 始終為此包使用直接代理
    GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay
  2. 匯入路徑錯誤:

    # 檢查 Go version (需要 1.24.4+)
    go version
    # Ensure module is initialized
    go mod init your-project-name
  3. 構建失敗:

    # 清理模組緩衝並重試
    go clean -modcache
    go mod tidy
    go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay

網路和 API 問題

  1. 連線逾時:

    • 檢查網路連接。

    • 驗證 API Gateway端點是否適合您的位置。

    • 如果可以的話,嘗試不同的網關端點以獲得更好的串連。

  2. API 金鑰錯誤:

    • 驗證 API 金鑰是否正確且有效。

    • 在控制台中檢查 API 金鑰許可權。

    • 確保環境變數設定正確。

  3. 會話建立失敗:

    • 驗證賬戶是否有足夠的配額。

    • 在控制台檢查服務狀態。

    • 過幾分鐘後再嘗試。

體驗AgentBay工作流程

在AgentBay代碼沙箱中運行Python代碼

以下程式碼範例展示了如何通過AgentBay Python SDK建立代碼沙箱環境,並運行包含計算的Python代碼。

說明

your-api-key替換為擷取的API密鑰

from agentbay import AgentBay
from agentbay import CreateSessionParams

agent_bay = AgentBay(api_key="your-api-key")
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)

if result.success:
    session = result.session
    
    code = """
import math

# Calculate factorial
def factorial(n):
    return math.factorial(n)

# Fibonacci sequence
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(f"Factorial of 10: {factorial(10)}")
print(f"Fibonacci of 10: {fibonacci(10)}")

# List comprehension
squares = [x**2 for x in range(1, 11)]
print(f"Squares: {squares}")
"""
    
    result = session.code.run_code(code, "python")
    if result.success:
        print("Output:", result.result)
        # Output: Factorial of 10: 3628800
        #         Fibonacci of 10: 55
        #         Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    agent_bay.delete(session)
 

在AgentBay雲瀏覽器沙箱環境中訪問阿里雲官網

以下程式碼範例展示了如何通過AgentBay Python SDK建立雲瀏覽器沙箱環境,並在雲瀏覽器沙箱中訪問阿里雲。

重要
  • 該範例程式碼需要調用get_endpoint_url方法擷取沙箱環境的可訪問連結,該方法不支援Basic權益包訂閱使用,需先訂閱進階權益後使用,詳情請參見權益包概述

  • 範例程式碼運行後可開啟resource_url查看沙箱環境的運行情況。

import os
import time
from agentbay import AgentBay
from agentbay import CreateSessionParams
from agentbay.browser.browser import BrowserOption
from playwright.sync_api import sync_playwright

def main():
    api_key = os.getenv("AGENTBAY_API_KEY")
    if not api_key:
        raise RuntimeError("AGENTBAY_API_KEY environment variable not set")

    agent_bay = AgentBay(api_key=api_key)

    # Create a session (use an image with browser preinstalled)
    params = CreateSessionParams(image_id="browser_latest")
    session_result = agent_bay.create(params)
    if not session_result.success:
        raise RuntimeError(f"Failed to create session: {session_result.error_message}")

    session = session_result.session

    # Initialize browser (supports stealth, proxy, fingerprint, etc. via BrowserOption)
    ok = session.browser.initialize(BrowserOption())
    if not ok:
        raise RuntimeError("Browser initialization failed")

    endpoint_url = session.browser.get_endpoint_url()

    # Connect Playwright over CDP and automate
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(endpoint_url)
        context = browser.contexts[0]
        page = context.new_page()
        page.goto("https://www.aliyun.com")
        print("Title:", page.title())
        time.sleep(30)
        browser.close()
        
    session.delete()

if __name__ == "__main__":
    main()

後續步驟

瞭解核心概念

  • AgentBay核心概念:在正式開始編程之前,充分理解AgentBay核心概念可以有效協助理解不同的方法的設計目的、能力及基本使用方法。

體驗核心能力

探索使用情境

更多進階配置

  • 配置Endpoint:SDK預設使用上海Endpoint,如果需要通過其他地區(例如新加坡)進行串連,需要配置不同的端點以獲得更好的網路效能。

  • 使用自訂鏡像:在實際使用與開發過程中,如果遇到網路效能不足,預設鏡像缺少所需應用等原因時,可通過使用自訂鏡像解決相關問題。