全部產品
Search
文件中心

AgentBay:Sessions

更新時間:Sep 18, 2025

描述

Session類表示AgentBay雲環境中的會話。它提供了管理檔案系統、執行命令等的方法。

方法

說明

環境

ComputerUseLinux

ComputerUseWindows

BrowserUse

MobileUse

CodeSpace

create

在AgentBay雲環境中建立新會話。

支援

支援

支援

支援

支援

delete

按ID刪除會話。

不支援

不支援

不支援

不支援

不支援

get_link

擷取此會話的連結。

支援

支援

支援

支援

支援

list

列出所有可用會話。

不支援

不支援

不支援

不支援

不支援

info

擷取有關此會話的資訊。

不支援

不支援

不支援

不支援

不支援

set_labels

為此會話設定標籤。

不支援

不支援

不支援

不支援

不支援

get_labels

擷取此會話的標籤。

不支援

不支援

不支援

不支援

不支援

屬性

屬性名稱

說明

agent_bay

建立此會話的AgentBay執行個體。

session_id

此會話的ID。

resource_url

與此會話關聯的資源的URL。

file_system

此會話的FileSystem執行個體。

command

此會話的Command執行個體。

oss

此會話的OSS執行個體。

application

此會話的ApplicationManager執行個體。

window

此會話的WindowManager執行個體。

ui

此會話的UI執行個體。

context

此會話的FileSystem執行個體。

方法

delete - 刪除會話

Golang

Delete() (*DeleteResult, error)

傳回值:

  • *DeleteResult:包含成功狀態和請求ID的結果對象。

  • error:若會話刪除失敗,返回錯誤資訊。

樣本:

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)

func main() {
	// 初始化SDK
	client, err := agentbay.NewAgentBay("your_api_key", nil)
	if err != nil {
		fmt.Printf("Error initializing AgentBay client: %v\n", err)
		os.Exit(1)
	}

	// 建立會話
	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)
	
	// 使用會話...
	
	// 刪除會話
	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

傳回值:

  • DeleteResult:包含成功狀態、請求ID和錯誤資訊的結果對象。

樣本:

from agentbay import AgentBay

# 初始化SDK
agent_bay = AgentBay(api_key="your_api_key")

# 建立會話
result = agent_bay.create()
if result.success:
    session = result.session
    print(f"會話建立成功,ID: {session.session_id}")
    
    # 使用會話...
    
    # 刪除會話
    delete_result = session.delete()
    if delete_result.success:
        print("會話刪除成功")
    else:
        print(f"會話刪除失敗: {delete_result.error_message}")

TypeScript

delete(): Promise<DeleteResult>=

傳回值:

  • Promise<DeleteResult>:返回包含成功狀態、請求ID和錯誤資訊的結果對象。

樣本:

import { AgentBay } from 'wuying-agentbay-sdk';

// 初始化SDK
const agentBay = new AgentBay({ apiKey: 'your_api_key' });

// 建立並刪除會話
async function createAndDeleteSession() {
  try {
    const result = await agentBay.create();
    if (result.success) {
      const session = result.session;
      console.log(`會話建立成功,ID: ${session.sessionId}`);
      
      // 使用會話...
      
      // 刪除會話
      const deleteResult = await session.delete();
      if (deleteResult.success) {
        console.log('會話刪除成功');
      } else {
        console.log(`會話刪除失敗: ${deleteResult.errorMessage}`);
      }
    }
  } catch (error) {
    console.error('錯誤:', error);
  }
}

createAndDeleteSession();

set_labels - 設定會話標籤

Golang

SetLabels(labels map[string]string) (*models.Response, error)

參數:

  • labels(map[string]string):表示要設定的標籤的索引值對。

傳回值:

  • *models.Response:包含請求ID和狀態資訊的響應對象。

  • error:若設定標籤失敗,返回錯誤資訊。

樣本:

// 設定會話標籤
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

參數:

  • labels(Dict[str, str])表示要設定的標籤的索引值對。

傳回值:

  • OperationResult:包含成功狀態、請求ID和錯誤資訊的結果對象。

異常:

  • AgentBayError:因API錯誤或其他問題設定標籤失敗。

樣本:

# 設定會話標籤
labels = {
    "project": "demo",
    "environment": "testing",
    "version": "1.0.0"
}
result = session.set_labels(labels)
if result.success:
    print("標籤設定成功")
else:
    print(f"標籤設定失敗: {result.error_message}")

TypeScript

setLabels(labels: Record<string, string>): Promise<OperationResult>

參數:

  • labels(Record<string, string>):表示要設定的標籤的索引值對。

傳回值:

  • Promise<OperationResult>:返回包含請求ID和狀態資訊的結果對象。

樣本:

// 設定會話標籤
async function setSessionLabels(session: Session) {
  try {
    const labels = {
      project: 'demo',
      environment: 'testing',
      version: '1.0.0'
    };
    
    const result = await session.setLabels(labels);
    console.log(`標籤設定成功,請求 ID: ${result.requestId}`);
    return result;
  } catch (error) {
    console.error(`標籤設定失敗: ${error}`);
    throw error;
  }
}

get_labels - 擷取會話標籤

Golang

GetLabels() (map[string]string, error)

傳回值:

  • map[string]string:會話的標籤索引值對。

  • error:若擷取標籤失敗,返回錯誤資訊。

樣本:

// 擷取會話標籤
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]

傳回值:

  • Dict[str, str]:會話的標籤索引值對。

異常:

  • AgentBayError:因API錯誤或其他問題擷取標籤失敗。

樣本:

# 擷取會話標籤
try:
    labels = session.get_labels()
    print(f"會話標籤: {labels}")
except AgentBayError as e:
    print(f"擷取標籤失敗: {e}")

TypeScript

getLabels(): Promise<LabelResult>

傳回值:

  • Promise<LabelResult>:返回包含會話標籤、請求ID和成功狀態的結果對象。

樣本:

// 擷取會話標籤
async function getSessionLabels(session: Session) {
  try {
    const result = await session.getLabels();
    console.log(`會話標籤: ${JSON.stringify(result.labels)}`);
    console.log(`請求 ID: ${result.requestId}`);
    return result.labels;
  } catch (error) {
    console.error(`擷取標籤失敗: ${error}`);
    throw error;
  }
}

info - 擷取會話資訊

Golang

Info() (*SessionInfo, error)

傳回值:

  • *SessionInfo:包含會話資訊的對象(如 SessionIDResourceURLAppID)。

  • error:若擷取會話資訊失敗,返回錯誤資訊。

樣本:

// 擷取會話資訊
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

傳回值:

  • SessionInfo:包含會話資訊的對象(如 session_idresource_urlapp_id)。

異常:

  • AgentBayError:因API錯誤或其他問題擷取資訊失敗。

樣本:

# 擷取會話資訊
try:
    info = session.info()
    print(f"會話 ID: {info.session_id}")
    print(f"資源 URL: {info.resource_url}")
    print(f"應用 ID: {info.app_id}")
except AgentBayError as e:
    print(f"擷取會話資訊失敗: {e}")

TypeScript

info(): Promise<InfoResult>

傳回值:

  • Promise<InfoResult>:返回包含會話資訊(如 sessionIdresourceUrl)、請求ID和成功狀態的結果對象。

樣本:

// 擷取會話資訊
async function getSessionInfo(session: Session) {
  try {
    const result = await session.info();
    console.log(`會話 ID: ${result.data.sessionId}`);
    console.log(`資源 URL: ${result.data.resourceUrl}`);
    console.log(`請求 ID: ${result.requestId}`);
    return result.data;
  } catch (error) {
    console.error(`擷取會話資訊失敗: ${error}`);
    throw error;
  }
}

get_link - 擷取會話連結

Golang

GetLink(protocolType string, port int) (string, error)

參數:

  • protocolType(string):連結的協議類型(如httphttp)。若為空白,使用預設協議。

  • port(int):連結的連接埠號碼。若為0,使用預設連接埠。

傳回值:

  • string:會話連結(如 https://example.com/session/123:8443)。

  • error:若擷取連結失敗,返回錯誤資訊。

樣本:

// 擷取使用預設協議和連接埠的會話連結
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)

// 擷取自訂協議和連接埠的連結
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

參數:

  • protocol_type(str, 可選):連結的協議類型(如"http""https")。若為空白,使用預設協議。

  • port(int, 可選):連結的連接埠號碼。若為None,使用預設連接埠。

傳回值:

  • str:會話連結(如 https://example.com/session/123:8443)。

異常:

  • AgentBayError:因API錯誤或其他問題擷取連結失敗。

樣本:

# 擷取會話連結
try:
    link = session.get_link()
    print(f"會話連結: {link}")
    
    # 擷取自訂協議和連接埠的連結
    custom_link = session.get_link("https", 8443)
    print(f"自訂連結: {custom_link}")
except AgentBayError as e:
    print(f"擷取連結失敗: {e}")

TypeScript

getLink(protocolType?: string, port?: number): Promise<LinkResult>

參數:

  • protocolType(string,可選):連結的協議類型(如"http""https")。若未指定,使用預設協議。

  • port(number,可選):連結的連接埠號碼。若未指定,使用預設連接埠。

傳回值:

  • Promise<LinkResult>:返回包含會話連結、請求ID和成功狀態的結果對象。

樣本:

// 擷取會話連結
async function getSessionLink(session: Session) {
  try {
    const result = await session.getLink();
    console.log(`會話連結: ${result.data}`);
    console.log(`請求 ID: ${result.requestId}`);
    
    // 擷取自訂協議和連接埠的連結
    const customResult = await session.getLink('https', 8443);
    console.log(`自訂連結: ${customResult.data}`);
    
    return result.data;
  } catch (error) {
    console.error(`擷取連結失敗: ${error}`);
    throw error;
  }
}