Description
The Context API lets you manage persistent storage contexts in the AgentBay cloud environment. Contexts allow you to persist data across sessions and reuse it in future sessions.
|
Method |
Description |
|
|
Lists all available contexts. |
|
|
Gets a context by name. Supports automatic creation. |
|
|
Creates a new context. |
|
|
Deletes a context by name or ID. |
|
|
Modifies the properties of a context. |
|
|
Modifies the properties of a context. |
|
|
Gets information about a context. |
|
|
Synchronizes a specified context. |
Properties
|
Property |
Description |
|
ID |
The unique identifier of the context. |
|
Name |
The name of the context. |
|
State |
The current status of the context, such as |
|
CreatedAt |
The time when the context was created. |
|
LastUsedAt |
The time when the context was last used. |
|
OsType |
The operating system type associated with the context. |
Methods
List - List all contexts
Golang
List() (*ContextListResult, error)
Return values
-
*ContextListResult: A result object that contains the list of contexts and the request ID. -
error: An error message if the operation fails.
Example
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)
}
// List all contexts.
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
Return value
-
ContextListResult: A result object that contains the list of contexts and the request ID.
Example
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# List all contexts.
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>
Return value
-
Promise<ContextListResult>: A promise that resolves to a result object containing the list of contexts and the request ID.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// List all contexts.
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 - Get a context
Golang
Get(name string, create bool) (*ContextResult, error)
Parameters
-
name (string): The name of the context to retrieve.
-
create (bool): Whether to create the context if it does not exist.
Return values
-
*ContextResult: A result object that contains the context object and the request ID. -
error: An error message if the operation fails.
Example
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)
}
// Get the context. If the context does not exist, create it.
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
Parameters
-
name (str): The name of the context to retrieve.
-
create (bool, optional): Whether to create the context if it does not exist. Defaults to
False.
Return value
-
ContextResult: A result object that contains the context object and the request ID.
Example
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# Get the context. If the context does not exist, create it.
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>
Parameters
-
name (string): The name of the context to retrieve.
-
create (boolean, optional): Whether to create the context if it does not exist. Defaults to
false.
Return value
-
Promise<ContextResult>: A promise that resolves to a result object containing the context and the request ID.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// Get the context. If the context does not exist, create it.
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 - Create a new context
Golang
Create(name string) (*ContextResult, error)
Parameter
-
name (string): The name of the context to create.
Return values
-
*ContextResult: A result object that contains the created context object and the request ID. -
error: An error message if the operation fails.
Example
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 new context.
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
Parameter
-
name (str): The name of the context to create.
Return value
-
ContextResult: A result object that contains the created context object and the request ID.
Example
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# Create a new context.
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>
Parameter
-
name (string): The name of the context to create.
Return value
-
Promise<ContextResult>: A promise that resolves to a result object containing the created context and the request ID.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// Create a new context.
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 - Update a context
Golang
Update(context *Context) (*OperationResult, error)
Parameter
-
context (*Context): The context object to update.
Return values
-
*OperationResult: A result object that contains the operation status and the request ID. -
error: An error message if the operation fails.
Example
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)
}
// Get an existing context.
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
// Update the context name.
context.Name = "my-updated-context"
// Save the changes.
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>
Parameter
-
context (Context): The context object to update.
Return value
-
Promise<OperationResult>: A promise that resolves to a result object containing the operation status, request ID, and error message.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// Update an existing context.
async function updateContext() {
try {
// Get an existing context.
const result = await agentBay.context.get('my-context');
if (result.success) {
const context = result.context;
// Update the context name.
context.name = 'my-updated-context';
// Save the changes.
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 - Modify context properties
Python
def modify(context_id_or_name: str, **kwargs) -> ContextResult
Parameters
-
context_id_or_name (str): The ID or name of the context to modify.
-
kwargs: The key-value pairs of the properties to modify, such as
name="new-name".
Return value
-
ContextResult: A result object that contains the modified context object and the request ID.
Example
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# Modify the context.
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 - Delete a context
Golang
Delete(context *Context) (*OperationResult, error)
Parameter
-
context (*Context): The context object to delete.
Return values
-
*OperationResult: A result object that contains the operation status and the request ID. -
error: An error message if the operation fails.
Example
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)
}
// Get an existing context.
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
// Delete the 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
Parameter
-
context_id_or_name (str): The ID or name of the context to delete.
Return value
-
DeleteResult: A result object that contains the operation status and the request ID.
Example
from agentbay import AgentBay
# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")
# Delete the context by name.
result = agent_bay.context.delete("my-context")
if result.success:
print("Context deleted successfully")
else:
print(f"Failed to delete context: {result.error_message}")
# Delete the context by 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>
Parameter
-
context (Context): The context object to delete.
Return value
-
Promise<OperationResult>: A promise that resolves to a result object containing the operation status, request ID, and error message.
Example
import { AgentBay } from 'wuying-agentbay-sdk';
// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// Delete an existing context.
async function deleteContext() {
try {
// Get an existing context.
const result = await agentBay.context.get('my-context');
if (result.success) {
const context = result.context;
// Delete the 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 - Get context information
Golang
GetInfo(path string) (*OperationResult, error)
Parameter
-
path (string): The path where the context is mounted.
Return values
-
*OperationResult: A result object that contains the operation status and the request ID. -
error: An error message if the operation fails.
Example
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
Parameters
-
context_id (str, optional): The ID of the context to query. -
path (str, optional): The mount path of the context. -
task_type (str, optional): The type of task to query.
Return value
-
ContextInfoResult: A result object that contains the context status data, success status, and request ID.
Example
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>
Parameter
-
path (string): The path where the context is mounted.
Return value
-
Promise<OperationResult>: A promise that resolves to a result object containing the operation status, request ID, and error message.
Example
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 - Synchronize a specified context
Golang
SyncContext(contextID string, path string, policy *SyncPolicy) (*OperationResult, error)
Parameters
-
contextID (string): The ID of the context to synchronize. -
path (string): The path where the context is mounted. -
policy (*SyncPolicy, optional): The synchronization policy. Defaults to nil, which uses the default policy.
Return values
-
*OperationResult: A result object that contains the operation status and the request ID. -
error: An error message if the operation fails.
Example
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
Parameters
-
context_id (str, optional): The ID of the context to synchronize. -
path (str, optional): The path where the context is mounted. -
mode (str, optional): The synchronization mode.
Return value
-
ContextSyncResult: A result object that contains the success status and the request ID.
Example
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>
Parameters
-
contextId (string): The ID of the context to synchronize. -
path (string): The path where the context is mounted. -
policy (SyncPolicy, optional): The synchronization policy. Defaults to the default policy if not specified.
Return value
-
Promise<OperationResult>: A promise that resolves to a result object containing the operation status, request ID, and error message.
Example
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();