Todos os produtos
Search
Central de documentação

AgentBay:Get started with the AgentBay SDK

Última atualização: Jun 29, 2026

Instale o AgentBay SDK, configure sua chave de API e valide a configuração com exemplos de sandbox de código e automação de navegador.

Preparativos

Instale o SDK e configure o ambiente

Instale o SDK

Python

Requisitos de ambiente

Python 3.10 ou superior.

Recomendado: usar um ambiente virtual
# 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')"
Alternativa: usar o Python do sistema (se permitido)
# Install with user flag (if system allows)
pip install --user wuying-agentbay-sdk

# Verify installation 
python -c "import agentbay; print('Installation successful')"

TypeScript/JavaScript

Requisitos de ambiente

Node.js 14 ou superior.

# 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

Requisitos de ambiente

Go 1.24.4 ou superior.

# 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"

Configure a chave de API

Obter a chave de API

  1. Acesse o console do AgentBay.

  2. No painel de navegação à esquerda, escolha Service Management e clique em no botão de cópia da chave de API desejada.

    Nota

    Se não houver nenhuma chave de API disponível, clique em Create API Key, insira um nome e clique em OK para criar uma chave de API.

Defina variáveis de ambiente

Linux/macOS:

export AGENTBAY_API_KEY=your_api_key_here

Windows:

setx AGENTBAY_API_KEY your_api_key_here

Verifique a instalação

Execute o código abaixo para validar sua configuração. Uma execução bem-sucedida exibe Test completed successfully.

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

Solução de problemas

Problemas com Python

  1. Erro externally-managed-environment:

    # Solution: Use a virtual environment
    python3 -m venv agentbay-env
    source agentbay-env/bin/activate
    pip install wuying-agentbay-sdk
  2. ModuleNotFoundError: No module named 'agentbay':

    # Check if the virtual environment is activated
    which python  # Should show venv path
    # Reinstall if needed
    pip install --force-reinstall wuying-agentbay-sdk

Problemas com TypeScript

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

    # Ensure you are in the project directory containing package.json
    pwd
    ls package.json  # Verify package.json exists
    # Reinstall if needed
    npm install wuying-agentbay-sdk
  2. require() is not defined:

    # Verify Node.js version (requires 14+)
    node --version
    # Ensure you are using CommonJS (default) or update to ES modules

Problemas com Golang

  1. Erro checksum mismatch (mais comum):

    # Always use a direct proxy for this package
    GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay
  2. Erro de caminho de importação:

    # Check Go version (requires 1.24.4+)
    go version
    # Ensure module is initialized
    go mod init your-project-name
  3. Falha na compilação:

    # Clear module cache and retry
    go clean -modcache
    go mod tidy
    go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay

Problemas de rede e API

  1. Tempo limite de conexão:

    • Verifique sua conexão de rede.

    • Confirme se o endpoint do API Gateway corresponde à sua região.

    • Tente um endpoint de gateway diferente para melhorar a conectividade.

  2. Erro de chave de API:

    • Valide se a chave de API está correta e válida.

    • Revise as permissões da chave de API no console.

    • Assegure-se de que as variáveis de ambiente estejam definidas corretamente.

  3. Falha na criação da sessão:

    • Verifique se a conta possui cota suficiente.

    • Consulte o status do serviço no console.

    • Tente novamente após alguns minutos.

Exemplos

Execute código Python em uma sandbox de código do AgentBay

Crie uma sandbox de código e execute cálculos em Python.

Nota

Substitua your-api-key pela sua chave de 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)
 

Automatizar um navegador em nuvem no AgentBay

Crie uma sandbox de navegador em nuvem e navegue até um site usando Playwright.

Importante
  • Este exemplo usa o método get_endpoint_url para obter a URL do ambiente da sandbox. Esse método requer uma assinatura de pacote de benefícios avançados. Para mais informações, consulte Visão geral dos planos.

  • Após a execução do código, abra a resource_url para visualizar o status de execução do ambiente da sandbox.

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()

Próximas etapas

Compreender conceitos fundamentais

Experimentar recursos principais

Explorar cenários

Configurações avançadas

  • Configure um endpoint: O SDK usa por padrão a região China (Shanghai). Mude para outra região, como Singapura, para obter melhor desempenho de rede.

  • Usar uma imagem personalizada: Substitua a imagem padrão quando ela não tiver as ferramentas necessárias ou apresentar baixo desempenho de rede.