Context

更新时间:

描述

Context API提供在AgentBay云环境中管理持久化存储上下文的功能。上下文允许您在会话间持久化数据并在未来会话中复用。

方法

说明

list

列出所有可用上下文。

get

按名称获取上下文(可设置自动创建)。

create

创建新上下文。

delete

按名称或ID删除上下文 。

modify

修改上下文属性。

update

修改上下文的属性。

Info

获取上下文相关信息。

Sync

同步指定上下文。

属性

属性名(Property)

说明(Description)

ID

上下文的唯一标识符。

Name

上下文名称。

State

上下文当前状态(如 availablein-use)。

CreatedAt

上下文创建时间。

LastUsedAt

上下文最近使用时间。

OsType

上下文绑定的操作系统类型。

方法

List - 列出所有上下文

Golang

List() (*ContextListResult, error)

返回值:

  • *ContextListResult:包含上下文列表和请求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)
	}

	// 列出所有上下文
	result, err := client.Context.List()
	if err != nil {
		fmt.Printf("Error listing contexts: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Found %d contexts:\n", len(result.Contexts))
	for _, context := range result.Contexts {
		fmt.Printf("Context ID: %s, Name: %s, State: %s\n", context.ID, context.Name, context.State)
	}
}

Python

def list() -> ContextListResult

返回值:

  • ContextListResult:包含上下文列表和请求ID的结果对象。

示例:

from agentbay import AgentBay

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

# 列出所有上下文
result = agent_bay.context.list()
if result.success:
    print(f"Found {len(result.contexts)} contexts:")
    for context in result.contexts:
        print(f"Context ID: {context.id}, Name: {context.name}, State: {context.state}")
else:
    print("Failed to list contexts")

TypeScript

list(): Promise<ContextListResult>

返回值:

  • Promise<ContextListResult>:返回包含上下文列表和请求ID的结果对象。

示例:

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

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

// 列出所有上下文
async function listContexts() {
  try {
    const result = await agentBay.context.list();
    if (result.success) {
      console.log(`Found ${result.contexts.length} contexts:`);
      result.contexts.forEach(context => {
        console.log(`Context ID: ${context.id}, Name: ${context.name}, State: ${context.state}`);
      });
    } else {
      console.log('Failed to list contexts');
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

listContexts();

Get - 获取上下文

Golang

Get(name string, create bool) (*ContextResult, error)

参数:

  • name(string):要获取的上下文名称。

  • create(bool):如果上下文不存在,是否创建。

返回值:

  • *ContextResult:包含上下文对象和请求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)
	}

	// 获取上下文,如果不存在则创建
	result, err := client.Context.Get("my-persistent-context", true)
	if err != nil {
		fmt.Printf("Error getting context: %v\n", err)
		os.Exit(1)
	}

	context := result.Context
	fmt.Printf("Context ID: %s, Name: %s, State: %s\n", context.ID, context.Name, context.State)
}

Python

def get(name: str, create: bool = False) -> ContextResult

参数:

  • name(str):要获取的上下文名称。

  • create(bool,可选):如果上下文不存在,是否创建。默认为False

返回值:

  • ContextResult:包含上下文对象和请求ID的结果对象。

示例:

from agentbay import AgentBay

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

# 获取上下文,如果不存在则创建
result = agent_bay.context.get("my-persistent-context", create=True)
if result.success:
    context = result.context
    print(f"Context ID: {context.id}, Name: {context.name}, State: {context.state}")
else:
    print(f"Failed to get context: {result.error_message}")

TypeScript

get(name: string, create?: boolean): Promise<ContextResult>

参数:

  • name(string):要获取的上下文名称。

  • create(boolean,可选):如果上下文不存在,是否创建。默认为false

返回值:

  • Promise<ContextResult>:返回包含上下文对象和请求ID的结果对象。

示例:

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

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

// 获取上下文,如果不存在则创建
async function getOrCreateContext() {
  try {
    const result = await agentBay.context.get('my-persistent-context', true);
    if (result.success) {
      const context = result.context;
      console.log(`Context ID: ${context.id}, Name: ${context.name}, State: ${context.state}`);
    } else {
      console.log(`Failed to get context: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

getOrCreateContext();

Create - 创建新上下文

Golang

Create(name string) (*ContextResult, error)

参数:

  • name(string):要创建的上下文名称。

返回值:

  • *ContextResult:包含创建的上下文对象和请求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)
	}

	// 创建新上下文
	result, err := client.Context.Create("my-new-context")
	if err != nil {
		fmt.Printf("Error creating context: %v\n", err)
		os.Exit(1)
	}

	context := result.Context
	fmt.Printf("Created context with ID: %s, Name: %s\n", context.ID, context.Name)
}

Python

def create(name: str) -> ContextResult

参数:

  • name(str):要创建的上下文名称。

返回值:

  • ContextResult:包含创建的上下文对象和请求ID的结果对象。

示例:

from agentbay import AgentBay

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

# 创建新上下文
result = agent_bay.context.create("my-new-context")
if result.success:
    context = result.context
    print(f"Created context with ID: {context.id}, Name: {context.name}")
else:
    print(f"Failed to create context: {result.error_message}")

TypeScript

create(name: string): Promise<ContextResult>

参数:

  • name(string):要创建的上下文名称。

返回值:

  • Promise<ContextResult>:返回包含创建的上下文对象和请求ID的结果对象。

示例:

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

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

// 创建新上下文
async function createContext() {
  try {
    const result = await agentBay.context.create('my-new-context');
    if (result.success) {
      const context = result.context;
      console.log(`Created context with ID: ${context.id}, Name: ${context.name}`);
    } else {
      console.log(`Failed to create context: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

createContext();

Update - 更新上下文

Golang

Update(context *Context) (*OperationResult, error)

参数:

  • context(*Context):要更新的上下文对象。

返回值:

  • *OperationResult:包含操作状态和请求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)
	}

	// 获取现有上下文
	result, err := client.Context.Get("my-context", false)
	if err != nil {
		fmt.Printf("Error getting context: %v\n", err)
		os.Exit(1)
	}

	context := result.Context
	
	// 更新上下文名称
	context.Name = "my-updated-context"
	
	// 保存更改
	updateResult, err := client.Context.Update(context)
	if err != nil {
		fmt.Printf("Error updating context: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("Context updated successfully")
	fmt.Printf("Request ID: %s\n", updateResult.RequestID)
}

TypeScript

update(context: Context): Promise<OperationResult>

参数:

  • context(Context):要更新的上下文对象。

返回值:

  • Promise<OperationResult>:返回包含操作状态、请求ID和错误信息的结果对象。

示例:

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

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

// 更新现有上下文
async function updateContext() {
  try {
    // 获取现有上下文
    const result = await agentBay.context.get('my-context');
    if (result.success) {
      const context = result.context;
      
      // 更新上下文名称
      context.name = 'my-updated-context';
      
      // 保存更改
      const updateResult = await agentBay.context.update(context);
      if (updateResult.success) {
        console.log(`Context updated successfully, request ID: ${updateResult.requestId}`);
      } else {
        console.log(`Failed to update context: ${updateResult.errorMessage}`);
      }
    } else {
      console.log(`Failed to get context: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

updateContext();

modify - 修改上下文属性

Python

def modify(context_id_or_name: str, **kwargs) -> ContextResult

参数:

  • context_id_or_name(str):要修改的上下文ID或名称。

  • kwargs:要修改的属性键值对(如 name="new-name")。

返回值:

  • ContextResult:包含修改后的上下文对象和请求ID的结果对象。

示例:

from agentbay import AgentBay

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

# 修改上下文
result = agent_bay.context.modify("my-context", name="my-renamed-context")
if result.success:
    context = result.context
    print(f"Modified context: {context.name}")
else:
    print(f"Failed to modify context: {result.error_message}")

Delete - 删除上下文

Golang

Delete(context *Context) (*OperationResult, error)

参数:

  • context(*Context)要删除的上下文对象。

返回值:

  • *OperationResult:包含操作状态和请求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)
	}

	// 获取现有上下文
	result, err := client.Context.Get("my-context", false)
	if err != nil {
		fmt.Printf("Error getting context: %v\n", err)
		os.Exit(1)
	}

	context := result.Context
	
	// 删除上下文
	deleteResult, err := client.Context.Delete(context)
	if err != nil {
		fmt.Printf("Error deleting context: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("Context deleted successfully")
	fmt.Printf("Request ID: %s\n", deleteResult.RequestID)
}

Python

def delete(context_id_or_name: str) -> DeleteResult

参数:

  • context_id_or_name(str):要删除的上下文ID或名称。

返回值:

  • DeleteResult:包含操作状态和请求ID的结果对象。

示例:

from agentbay import AgentBay

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

# 按名称删除上下文
result = agent_bay.context.delete("my-context")
if result.success:
    print("Context deleted successfully")
else:
    print(f"Failed to delete context: {result.error_message}")

# 按 ID 删除上下文
result = agent_bay.context.delete("ctx-1234567890abcdef")
if result.success:
    print("Context deleted successfully")
else:
    print(f"Failed to delete context: {result.error_message}")

TypeScript

delete(context: Context): Promise<OperationResult>

参数:

  • context(Context):要删除的上下文对象。

返回值:

  • Promise<OperationResult>:返回包含操作状态、请求ID和错误信息的结果对象。

示例:

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

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

// 删除现有上下文
async function deleteContext() {
  try {
    // 获取现有上下文
    const result = await agentBay.context.get('my-context');
    if (result.success) {
      const context = result.context;
      
      // 删除上下文
      const deleteResult = await agentBay.context.delete(context);
      if (deleteResult.success) {
        console.log(`Context deleted successfully, request ID: ${deleteResult.requestId}`);
      } else {
        console.log(`Failed to delete context: ${deleteResult.errorMessage}`);
      }
    } else {
      console.log(`Failed to get context: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

deleteContext();

Info - 获取上下文相关信息

Golang

GetInfo(path string) (*OperationResult, error)

参数:

  • path (string):上下文应挂载的路径。

返回值:

  • *OperationResult:包含操作状态和请求ID的结果对象。

  • error:若操作失败,返回错误信息。

示例:

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 with a synchronized context
	// ... (assume context is synchronized to '/mnt/persistent')
	
	// Get information about the synchronized context
	infoResult, err := session.Context.GetInfo("/mnt/persistent")
	if err != nil {
		fmt.Printf("Error getting context info: %v\n", err)
		os.Exit(1)
	}
	
	// The data is returned as an interface{}, convert it to ContextInfo
	contextInfo, ok := infoResult.Data.(*agentbay.ContextInfo)
	if !ok {
		fmt.Println("Error: Context info data is not in expected format")
		os.Exit(1)
	}
	
	fmt.Println("Context Information:")
	fmt.Printf("  Context ID: %s\n", contextInfo.ContextID)
	fmt.Printf("  Path: %s\n", contextInfo.Path)
	fmt.Printf("  State: %s\n", contextInfo.State)
	fmt.Printf("Request ID: %s\n", infoResult.RequestID)
}

Python

info(context_id: Optional[str] = None, path: Optional[str] = None, task_type: Optional[str] = None) -> ContextInfoResult

参数:

  • context_id (str, optional):用于指定待查询信息的上下文 ID。

  • path (str, optional):上下文的挂载路径。

  • task_type (str, optional):用于指定待查询信息的任务类型。

返回值:

  • ContextInfoResult:结果对象,包含上下文状态数据、成功状态以及请求 ID。

示例:

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
    
    # Get context synchronization information
    info_result = session.context.info()
    if info_result.context_status_data:
        for item in info_result.context_status_data:
            print(f"Context {item.context_id} status: {item.status}")
    else:
        print("No context synchronization tasks found")

TypeScript

getInfo(path: string): Promise<OperationResult>

参数:

  • path (string):上下文应挂载的路径。

返回值:

  • Promise<OperationResult>:返回包含操作状态、请求ID和错误信息的结果对象。

示例:

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

// Initialize the SDK
const agentBay = new AgentBay({ apiKey: 'your_api_key' });

// Create a session with a synchronized context
// ... (assume context is synchronized to '/mnt/persistent')

// Get information about the synchronized context
async function getContextInfo() {
  try {
    const infoResult = await session.context.getInfo('/mnt/persistent');
    if (infoResult.success) {
      const contextInfo = infoResult.data;
      console.log('Context Information:');
      console.log(`  Context ID: ${contextInfo.contextId}`);
      console.log(`  Path: ${contextInfo.path}`);
      console.log(`  State: ${contextInfo.state}`);
      console.log(`Request ID: ${infoResult.requestId}`);
    } else {
      console.log(`Failed to get context info: ${infoResult.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

getContextInfo();

Sync - 同步指定上下文

Golang

SyncContext(contextID string, path string, policy *SyncPolicy) (*OperationResult, error)

参数:

  • contextID (string):待同步的上下文 ID。

  • path (string):上下文应挂载的路径。

  • policy (*SyncPolicy, optional):同步策略。若为 nil(空值),则使用默认策略。

返回值:

  • *OperationResult:包含操作状态和请求ID的结果对象。

  • error:若操作失败,返回错误信息。

示例:

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
	
	// Get or create a context
	contextResult, err := client.Context.Get("my-context", true)
	if err != nil {
		fmt.Printf("Error getting context: %v\n", err)
		os.Exit(1)
	}
	
	// Create a sync policy
	policy := agentbay.NewSyncPolicy()
	
	// Synchronize the context with the session
	syncResult, err := session.Context.SyncContext(
		contextResult.Context.ID,
		"/mnt/persistent",
		policy,
	)
	if err != nil {
		fmt.Printf("Error synchronizing context: %v\n", err)
		os.Exit(1)
	}
	
	fmt.Println("Context synchronized successfully")
	fmt.Printf("Request ID: %s\n", syncResult.RequestID)
}

Python

sync(context_id: Optional[str] = None, path: Optional[str] = None, mode: Optional[str] = None) -> ContextSyncResult

参数:

  • context_id (str, optional):待同步的上下文 ID。

  • path (str, optional):上下文应挂载的路径。

  • mode (str, optional):同步模式。

返回值:

  • ContextSyncResult:结果对象,包含成功状态与请求 ID。

示例:

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
    
    # Trigger context synchronization
    sync_result = session.context.sync()
    
    if sync_result.success:
        print(f"Context synchronization triggered successfully, request ID: {sync_result.request_id}")
    else:
        print(f"Failed to trigger context synchronization")

TypeScript

syncContext(contextId: string, path: string, policy?: SyncPolicy): Promise<OperationResult>

参数:

  • contextID (string):待同步的上下文 ID。

  • path (string):上下文应挂载的路径。

  • policy (*SyncPolicy, optional):同步策略。若为 nil(空值),则使用默认策略。

返回值:

  • Promise<OperationResult>:返回包含操作状态、请求ID和错误信息的结果对象。

示例:

import { AgentBay } from 'wuying-agentbay-sdk';
import { SyncPolicy } from 'wuying-agentbay-sdk/context-sync';

// Initialize the SDK
const agentBay = new AgentBay({ apiKey: 'your_api_key' });

// Create a session and synchronize a context
async function syncContextInSession() {
  try {
    // Create a session
    const result = await agentBay.create();
    if (result.success) {
      const session = result.session;
      
      // Get or create a context
      const contextResult = await agentBay.context.get('my-context', true);
      if (contextResult.success) {
        // Synchronize the context with the session
        const syncResult = await session.context.syncContext(
          contextResult.context.id,
          '/mnt/persistent',
          SyncPolicy.default()
        );
        
        if (syncResult.success) {
          console.log(`Context synchronized successfully, request ID: ${syncResult.requestId}`);
        } else {
          console.log(`Failed to synchronize context: ${syncResult.errorMessage}`);
        }
      } else {
        console.log(`Failed to get context: ${contextResult.errorMessage}`);
      }
    } else {
      console.log(`Failed to create session: ${result.errorMessage}`);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

syncContextInSession();