Get started with the AgentBay SDK
Install the AgentBay SDK, configure your API key, and verify your setup with code sandbox and browser automation examples.
Preparations
Accounts and Permissions: complete individual identity verification or enterprise identity verification.
New user trial: If this is your first time using AgentBay with your Alibaba Cloud account, you can apply for a new user trial.
Install the SDK and configure the environment
Install the SDK
Python
Environment requirements
Python 3.10 or later.
Recommended: use a virtual environment
# 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')"Alternative: use system Python (if allowed)
# Install with user flag (if system allows)
pip install --user wuying-agentbay-sdk
# Verify installation
python -c "import agentbay; print('Installation successful')"TypeScript/JavaScript
Environment Requirements
Node.js 14 or later.
# 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
Environment Requirements
Go 1.24.4 or later.
# 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 API key
Get API key
Go to the AgentBay console.
In the left navigation pane, choose Service Management, then click the copy button for the target API key.
NoteIf no API key is available, click Create API Key, enter a name, and click OK to create an API key.
Set environment variables
Linux/macOS:
export AGENTBAY_API_KEY=your_api_key_hereWindows:
setx AGENTBAY_API_KEY your_api_key_hereVerify installation
Run the following code to verify your setup. A successful run prints 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")
}
}
}Troubleshooting
Python issues
externally-managed-environmenterror:# Solution: Use a virtual environment python3 -m venv agentbay-env source agentbay-env/bin/activate pip install wuying-agentbay-sdkModuleNotFoundError: 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
TypeScript issues
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-sdkrequire() is not defined:# Verify Node.js version (requires 14+) node --version # Ensure you are using CommonJS (default) or update to ES modules
Golang issues
checksum mismatcherror (most common):# Always use a direct proxy for this package GOPROXY=direct go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbayImport path error:
# Check Go version (requires 1.24.4+) go version # Ensure module is initialized go mod init your-project-nameBuild failed:
# Clear module cache and retry go clean -modcache go mod tidy go get github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay
Network and API Issues
Connection timeout:
Check your network connection.
Verify that the API Gateway endpoint matches your region.
Try a different gateway endpoint for better connectivity.
API key error:
Verify the API key is correct and valid.
Check API key permissions in the console.
Confirm environment variables are set correctly.
Session creation failed:
Verify the account has sufficient quota.
Check service status in the console.
Retry after a few minutes.
Examples
Run Python code in an AgentBay code sandbox
Create a code sandbox and run Python calculations.
Replace your-api-key with your API key.
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)
Automate a cloud browser in AgentBay
Create a cloud browser sandbox and navigate to a website using Playwright.
This example uses the
get_endpoint_urlmethod to retrieve the sandbox environment URL. This method requires an advanced benefit package subscription. For more information, see Plan overview.After the code runs, open the
resource_urlto view the running status of the sandbox environment.
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()Next steps
Understand core concepts
Key AgentBay concepts: Understand each SDK method's purpose and capabilities before you start coding.
Experience core capabilities
Command Execution: Run shell commands and code in the sandbox.
File Operations: Upload, download, and manage files.
Session Management: Configure advanced session parameters.
Explore scenarios
Browser Automation: Scrape web data and automate testing.
Mobile Testing: Automate Android app validation.
Code Development: Use cloud development environments.
Advanced configurations
Configure an endpoint: The SDK defaults to the China (Shanghai) region. Switch to another region, such as Singapore, for better network performance.
Use a custom image: Replace the default image when it lacks required tools or has poor network performance.