描述
Context API提供在AgentBay雲環境中管理持久化儲存內容相關的功能。上下文允許您在會話間持久化資料並在未來會話中複用。
方法 | 說明 |
| 列出所有可用上下文。 |
| 按名稱擷取上下文(可設定自動建立)。 |
| 建立新上下文。 |
| 按名稱或ID刪除上下文 。 |
| 修改內容屬性。 |
| 修改內容相關的屬性。 |
| 擷取上下文相關資訊。 |
| 同步指定上下文。 |
屬性
屬性名稱(Property) | 說明(Description) |
ID | 內容相關的唯一識別碼。 |
Name | 上下文名稱。 |
State | 上下文目前狀態(如 |
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):用於指定待查詢資訊的內容識別碼。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):待同步的內容識別碼。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):待同步的內容識別碼。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):待同步的內容識別碼。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();