描述
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();