This topic describes the process of accessing Wuying AgentBay through the SDK. It covers SDK installation, API key retrieval, and configuration, and provides two examples to demonstrate Wuying AgentBay's basic features.
Preparations
Accounts and Permissions: Activate an Alibaba Cloud account.
New User Trial: If this is your first time using Wuying 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
Obtain API Key
Go to the Wuying AgentBay console.
In the navigation pane on the left, select 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
After installing the SDK and configuring the API, run the following sample code. When the console returns Test completed successfully, this indicates that the SDK installation and environment configuration are successful.
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:
You can check your network connection.
You can verify that the API Gateway endpoint is suitable for your location.
If possible, you can try a different gateway endpoint for better connectivity.
API key error:
You can verify that the API key is correct and valid.
You can check API key permissions in the console.
You can ensure environment variables are set correctly.
Session creation failed:
You can verify that the account has sufficient quota.
You can check the service status in the console.
You can try again in a few minutes.
Experience AgentBay Workflow
Run Python Code in an AgentBay Code Sandbox
This code example shows how to create a code sandbox environment and run Python code that performs calculations using the AgentBay Python SDK.
Replace your-api-key with the 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)
Access the Alibaba Cloud Official Website in an AgentBay Cloud Browser Sandbox Environment
This code example shows how to create a cloud browser sandbox environment using the AgentBay Python SDK and access the Alibaba Cloud official website in the sandbox.
This example code invokes the
get_endpoint_urlmethod to obtain the access URL for the sandbox environment. This method is not available with a Basic privilege package subscription. To use this method, you must subscribe to an advanced privilege package. For more information, see Privilege Package 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()What to do next
Understand core concepts
AgentBay core concepts: Understand the core concepts of AgentBay before you start coding. This helps you learn the purpose, capabilities, and basic usage of different methods.
Experience core capabilities
Command Execution: Run Shell commands and code.
File Operations: Experience file upload, download, and management.
Session Management: Learn about advanced session parameters and best practices.
Explore scenarios
Browser Automation: Scrape web information and perform automated testing.
Mobile Testing: Automate the validation of Android applications.
Code Development: Explore cloud development environments.
Advanced configurations
Configure an endpoint: The SDK uses the Shanghai endpoint by default. To connect through another region, such as Singapore, configure a different endpoint for better network performance.
Use a custom image: If you experience poor network performance or find that the default image is missing a required application, use a custom image to resolve these issues.