すべてのプロダクト
Search
ドキュメントセンター

AgentBay:SDK によるアクセス

最終更新日:Mar 17, 2026

このトピックでは、SDK を使用して Wuying AgentBay にアクセスする手順について説明します。SDK のインストール、API キーの取得と設定方法を解説し、2 つのサンプルコードを通して Wuying AgentBay の基本機能を紹介します。

事前準備

SDK のインストールと環境設定

SDK のインストール

Python

環境要件

Python 3.10 以降。

推奨:仮想環境の使用
# 仮想環境の作成とアクティベート
python3 -m venv agentbay-env
source agentbay-env/bin/activate  # Linux/macOS
# agentbay-env\Scripts\activate   # Windows

# パッケージのインストール
pip install wuying-agentbay-sdk

# インストールの確認
python -c "import agentbay; print('Installation successful')"
代替案:システム Python の使用 (許可されている場合)
# user フラグを付けてインストール (システムが許可する場合)
pip install --user wuying-agentbay-sdk

# インストールの確認
python -c "import agentbay; print('Installation successful')"

TypeScript/JavaScript

環境要件

Node.js 14 以降。

# プロジェクトの初期化 (新規プロジェクトの場合)
mkdir my-agentbay-project && cd my-agentbay-project
npm init -y

# パッケージのインストール
npm install wuying-agentbay-sdk

# インストールの確認
node -e "const {AgentBay} = require('wuying-agentbay-sdk'); console.log('Installation successful')"

Golang

環境要件

Go 1.24.4 以降。

# モジュールの初期化 (新規プロジェクトの場合)
mkdir my-agentbay-project && cd my-agentbay-project  
go mod init my-agentbay-project

# パッケージのインストール
GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay

# インストールの確認
go list -m github.com/aliyun/wuying-agentbay-sdk/golang && echo "Installation successful"

API キーの設定

API キーの取得

  1. Wuying AgentBay コンソールに移動します。

  2. 左側のナビゲーションウィンドウで [サービス管理] を選択します。次に、対象の API キーのコピーボタンをクリックします。

    説明

    利用可能な API キーがない場合は、[API キーの作成] をクリックし、名前を入力して [OK] をクリックして API キーを作成します。

環境変数の設定

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

# 環境から API キーを取得
api_key = os.getenv("AGENTBAY_API_KEY")
if not api_key:
    print("Please set AGENTBAY_API_KEY environment variable")
    exit(1)

try:
    # SDK の初期化
    agent_bay = AgentBay(api_key=api_key)
    print("SDK initialized successfully")
    
    # セッションの作成 (有効な API キーとネットワークが必要)
    session_result = agent_bay.create()
    if session_result.success:
        session = session_result.session
        print(f"Session created: {session.session_id}")
        
        # クリーンアップ
        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 {
        // SDK の初期化
        const agentBay = new AgentBay({ apiKey });
        console.log("SDK initialized successfully");
        
        // セッションの作成 (有効な API キーとネットワークが必要)
        const sessionResult = await agentBay.create();
        if (sessionResult.success) {
            const session = sessionResult.session;
            console.log(`Session created: ${session.sessionId}`);
            
            // クリーンアップ
            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() {
    // 環境から API キーを取得
    apiKey := os.Getenv("AGENTBAY_API_KEY")
    if apiKey == "" {
        fmt.Println("Please set AGENTBAY_API_KEY environment variable")
        return
    }

    // 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")

    // セッションの作成 (有効な API キーとネットワークが必要)
    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)
        
        // クリーンアップ
        _, 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  # venv のパスが表示されるはずです
    # 必要に応じて再インストールします
    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 のバージョンを確認します (14 以降が必要です)
    node --version
    # CommonJS (デフォルト) を使用しているか、ES モジュールに更新しているかを確認します

Golang の問題

  1. checksum mismatch エラー (最も一般的):

    # このパッケージには常に直接プロキシを使用します
    GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay
  2. インポートパスエラー:

    # Go のバージョンを確認します (1.24.4 以降が必要です)
    go version
    # モジュールが初期化されていることを確認します
    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-keyAPI キーに置き換えてください。

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

# 階乗を計算する
def factorial(n):
    return math.factorial(n)

# フィボナッチ数列
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)}")

# リスト内包表記
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 クラウドブラウザサンドボックス環境で Alibaba Cloud 公式ウェブサイトにアクセスする

このコード例では、AgentBay Python SDK を使用してクラウドブラウザサンドボックス環境を作成し、そのサンドボックス内で Alibaba Cloud 公式ウェブサイトにアクセスする方法を示します。

重要
  • このサンプルコードは get_endpoint_url メソッドを呼び出して、サンドボックス環境へのアクセス 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)

    # セッションの作成 (ブラウザがプリインストールされたイメージを使用)
    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

    # ブラウザの初期化 (BrowserOption を介してステルス、プロキシ、指紋などをサポート)
    ok = session.browser.initialize(BrowserOption())
    if not ok:
        raise RuntimeError("Browser initialization failed")

    endpoint_url = session.browser.get_endpoint_url()

    # CDP 経由で Playwright に接続して自動化
    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 の基本概念を理解します。これにより、さまざまなメソッドの目的、機能、および基本的な使用方法を学ぶことができます。

コア機能の体験

  • コマンド実行:シェルコマンドとコードを実行します。

  • ファイル操作:ファイルのアップロード、ダウンロード、管理を体験します。

  • セッション管理:高度なセッションパラメーターとベストプラクティスについて学びます。

シナリオの探求

高度な設定

  • エンドポイントの設定:SDK はデフォルトで上海エンドポイントを使用します。シンガポールなど、別のリージョン経由で接続する場合は、ネットワークパフォーマンスを向上させるために別のエンドポイントを設定します。

  • カスタムイメージの使用:ネットワークパフォーマンスが低い場合や、デフォルトのイメージに必要なアプリケーションが含まれていない場合は、カスタムイメージを使用することでこれらの問題を解決できます。