Descrição
Representa uma sessão no ambiente de nuvem AgentBay e fornece métodos para gerencie o sistema de arquivos e executar comandos.
|
Método |
Descrição |
Ambiente |
||||
|
Linux Computer Use |
WindowsComputer Use |
Browser Use |
Mobile Use |
Code Space |
||
|
|
Cria uma nova sessão no ambiente de nuvem AgentBay. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Exclui uma sessão pelo ID. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Obtém o link desta sessão. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Lista todas as sessões disponíveis. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Obtém informações sobre esta sessão. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Define rótulos para esta sessão. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
|
|
Obtém os rótulos desta sessão. |
Compatível |
Compatível |
Compatível |
Compatível |
Compatível |
Propriedades
|
Nome da propriedade |
Descrição |
|
agent_bay |
Instância do AgentBay que criou esta sessão. |
|
session_id |
ID desta sessão. |
|
resource_url |
URL do recurso associado a esta sessão. |
|
file_system |
Instância FileSystem desta sessão. |
|
command |
Instância Command desta sessão. |
|
oss |
Instância do Object Storage Service (OSS) desta sessão. |
|
application |
Instância ApplicationManager desta sessão. |
|
window |
Instância WindowManager desta sessão. |
|
ui |
Instância UI desta sessão. |
|
context |
Instância FileSystem desta sessão. |
Métodos
delete - Excluir uma sessão
Golang
Delete() (*DeleteResult, error)
Valores de retorno
*DeleteResult: Objeto de resultado com o status de sucesso e o ID da solicitação.error: Mensagem de erro caso a exclusão falhe.
Exemplo
package main
import (
"fmt"
"os"
"github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)
func main() {
// Initialize the SDK.
client, err := agentbay.NewAgentBay("your_api_key", nil)
if err != nil {
fmt.Printf("Error initializing AgentBay client: %v\n", err)
os.Exit(1)
}
// Create a session.
createResult, err := client.Create(nil)
if err != nil {
fmt.Printf("Error creating session: %v\n", err)
os.Exit(1)
}
session := createResult.Session
fmt.Printf("Session created with ID: %s\n", session.SessionID)
// Use the session...
// Delete the session.
deleteResult, err := session.Delete()
if err != nil {
fmt.Printf("Error deleting session: %v\n", err)
os.Exit(1)
}
fmt.Println("Session deleted successfully")
fmt.Printf("Request ID: %s\n", deleteResult.RequestID)
}
Python
delete() -> DeleteResult
Valor de retorno
DeleteResult: Objeto de resultado com o status de sucesso, o ID da solicitação e a mensagem de erro.
Exemplo
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# Create a session.
result = agent_bay.create()
if result.success:
session = result.session
print(f"Session created successfully. ID: {session.session_id}")
# Use the session...
# Delete the session.
delete_result = session.delete()
if delete_result.success:
print("Session deleted successfully")
else:
print(f"Failed to delete session: {delete_result.error_message}")
TypeScript
delete(): Promise<DeleteResult>=
Valor de retorno
Promise<DeleteResult>: Promise resolvida em um objeto de resultado. O objeto contém o status de sucesso, o ID da solicitação e a mensagem de erro.
Exemplo
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// Create and delete a session.
async function createAndDeleteSession() {
try {
const result = await agentBay.create();
if (result.success) {
const session = result.session;
console.log(`Session created successfully. ID: ${session.sessionId}`);
// Use the session...
// Delete the session.
const deleteResult = await session.delete();
if (deleteResult.success) {
console.log('Session deleted successfully');
} else {
console.log(`Failed to delete session: ${deleteResult.errorMessage}`);
}
}
} catch (error) {
console.error('Error:', error);
}
}
createAndDeleteSession();
set_labels - Defina rótulos da sessão
Golang
SetLabels(labels map[string]string) (*models.Response, error)
Parâmetro
labels(map[string]string): Mapa de pares chave-valor que representa os rótulos a definir.
Valores de retorno
*models.Response: Objeto de resposta com o ID da solicitação e informações de status.error: Mensagem de erro caso a definição dos rótulos falhe.
Exemplo
// Set session labels.
labels := map[string]string{
"project": "demo",
"environment": "testing",
"version": "1.0.0",
}
response, err := session.SetLabels(labels)
if err != nil {
fmt.Printf("Error setting labels: %v\n", err)
os.Exit(1)
}
fmt.Println("Labels set successfully")
fmt.Printf("Request ID: %s\n", response.RequestID)
Python
set_labels(labels: Dict[str, str]) -> OperationResult
Parâmetro
labels(Dict[str, str]): Dicionário de pares chave-valor que representa os rótulos a definir.
Valor de retorno
OperationResult: Objeto de resultado com o status de sucesso, o ID da solicitação e a mensagem de erro.
Exceção
AgentBayError: Lançada se a definição de rótulos falhar devido a um erro de API ou outros problemas.
Exemplo
# Set session labels.
labels = {
"project": "demo",
"environment": "testing",
"version": "1.0.0"
}
result = session.set_labels(labels)
if result.success:
print("Labels set successfully")
else:
print(f"Failed to set labels: {result.error_message}")
TypeScript
setLabels(labels: Record<string, string>): Promise<OperationResult>
Parâmetro
labels(Record<string, string>): Objeto de pares chave-valor que representa os rótulos a definir.
Valor de retorno
Promise<OperationResult>: Promise resolvida em um objeto de resultado. O objeto contém o ID da solicitação e informações de status.
Exemplo
// Set session labels.
async function setSessionLabels(session: Session) {
try {
const labels = {
project: 'demo',
environment: 'testing',
version: '1.0.0'
};
const result = await session.setLabels(labels);
console.log(`Labels set successfully. Request ID: ${result.requestId}`);
return result;
} catch (error) {
console.error(`Failed to set labels: ${error}`);
throw error;
}
}
get_labels - Obter rótulos da sessão
Golang
GetLabels() (map[string]string, error)
Valores de retorno
map[string]string: Mapa com os pares chave-valor dos rótulos da sessão.error: Mensagem de erro caso não seja possível recuperar os rótulos.
Exemplo
// Get session labels.
labels, err := session.GetLabels()
if err != nil {
fmt.Printf("Error getting labels: %v\n", err)
os.Exit(1)
}
fmt.Println("Session labels:")
for key, value := range labels {
fmt.Printf("%s: %s\n", key, value)
}
Python
get_labels() -> Dict[str, str]
Valor de retorno
Dict[str, str]: Dicionário com os pares chave-valor dos rótulos da sessão.
Exceção
AgentBayError: Lançada se não for possível recuperar os rótulos devido a um erro de API ou outros problemas.
Exemplo
# Get session labels.
try:
labels = session.get_labels()
print(f"Session labels: {labels}")
except AgentBayError as e:
print(f"Failed to get labels: {e}")
TypeScript
getLabels(): Promise<LabelResult>
Valor de retorno
Promise<LabelResult>: Promise resolvida em um objeto de resultado. O objeto contém os rótulos da sessão, o ID da solicitação e o status de sucesso.
Exemplo
// Get session labels.
async function getSessionLabels(session: Session) {
try {
const result = await session.getLabels();
console.log(`Session labels: ${JSON.stringify(result.labels)}`);
console.log(`Request ID: ${result.requestId}`);
return result.labels;
} catch (error) {
console.error(`Failed to get labels: ${error}`);
throw error;
}
}
info - Obter informações da sessão
Golang
Info() (*SessionInfo, error)
Valores de retorno
*SessionInfo: Objeto com informações da sessão, comoSessionID,ResourceURLeAppID.error: Mensagem de erro caso não seja possível recuperar as informações da sessão.
Exemplo
// Get session information.
info, err := session.Info()
if err != nil {
fmt.Printf("Error getting session info: %v\n", err)
os.Exit(1)
}
fmt.Printf("Session ID: %s\n", info.SessionID)
fmt.Printf("Resource URL: %s\n", info.ResourceURL)
fmt.Printf("App ID: %s\n", info.AppID)
Python
info() -> SessionInfo
Valor de retorno
SessionInfo: Objeto com informações da sessão, comosession_id,resource_urleapp_id.
Exceção
AgentBayError: Lançada se não for possível recuperar as informações devido a um erro de API ou outros problemas.
Exemplo
# Get session information.
try:
info = session.info()
print(f"Session ID: {info.session_id}")
print(f"Resource URL: {info.resource_url}")
print(f"Application ID: {info.app_id}")
except AgentBayError as e:
print(f"Failed to get session information: {e}")
TypeScript
info(): Promise<InfoResult>
Valor de retorno
Promise<InfoResult>: Promise resolvida em um objeto de resultado. O objeto contém informações da sessão, comosessionIderesourceUrl, além do ID da solicitação e do status de sucesso.
Exemplo
// Get session information.
async function getSessionInfo(session: Session) {
try {
const result = await session.info();
console.log(`Session ID: ${result.data.sessionId}`);
console.log(`Resource URL: ${result.data.resourceUrl}`);
console.log(`Request ID: ${result.requestId}`);
return result.data;
} catch (error) {
console.error(`Failed to get session information: ${error}`);
throw error;
}
}
get_link - Obter um link de sessão
Golang
GetLink(protocolType string, port int) (string, error)
Parâmetros
protocolType(string): Tipo de protocolo do link, comohttpouhttps. Se este parâmetro estiver vazio, o sistema usa o protocolo padrão.port(int): Número da porta do link. Se este parâmetro for0, o sistema usa a porta padrão.
Valores de retorno
string: Link da sessão, comohttps://example.com/session/123:8443.error: Mensagem de erro caso não seja possível recuperar o link.
Exemplo
// Get the session link using the default protocol and port.
link, err := session.GetLink("", 0)
if err != nil {
fmt.Printf("Error getting link: %v\n", err)
os.Exit(1)
}
fmt.Printf("Session link: %s\n", link)
// Get the link with a custom protocol and port.
customLink, err := session.GetLink("https", 8443)
if err != nil {
fmt.Printf("Error getting custom link: %v\n", err)
os.Exit(1)
}
fmt.Printf("Custom link: %s\n", customLink)
Python
get_link(protocol_type: Optional[str] = None, port: Optional[int] = None) -> str
Parâmetros
protocol_type(str, opcional): Tipo de protocolo do link, como"http"ou"https". Se você não especifique este parâmetro, o sistema usa o protocolo padrão.port(int, opcional): Número da porta do link. Se este parâmetro forNone, o sistema usa a porta padrão.
Valor de retorno
str: Link da sessão, comohttps://example.com/session/123:8443.
Exceção
AgentBayError: Lançada se não for possível recuperar o link devido a um erro de API ou outros problemas.
Exemplo
# Get the session link.
try:
link = session.get_link()
print(f"Session link: {link}")
# Get the link with a custom protocol and port.
custom_link = session.get_link("https", 8443)
print(f"Custom link: {custom_link}")
except AgentBayError as e:
print(f"Failed to get the link: {e}")
TypeScript
getLink(protocolType?: string, port?: number): Promise<LinkResult>
Parâmetros
protocolType(string, opcional): Tipo de protocolo do link, como"http"ou"https". Se este parâmetro não for especificado, o sistema usa o protocolo padrão.port(number, opcional): Número da porta do link. Se este parâmetro não for especificado, o sistema usa a porta padrão.
Valor de retorno
Promise<LinkResult>: Promise resolvida em um objeto de resultado. O objeto contém o link da sessão, o ID da solicitação e o status de sucesso.
Exemplo
// Get the session link.
async function getSessionLink(session: Session) {
try {
const result = await session.getLink();
console.log(`Session link: ${result.data}`);
console.log(`Request ID: ${result.requestId}`);
// Get the link with a custom protocol and port.
const customResult = await session.getLink('https', 8443);
console.log(`Custom link: ${customResult.data}`);
return result.data;
} catch (error) {
console.error(`Failed to get the link: ${error}`);
throw error;
}
}