AgentFS(测试版) SDK 开发套件
TypeScript/JavaScript SDK
AgentFS TypeScript 和 JavaScript SDK 的完整参考文档
使用 AgentFS TypeScript SDK 构建有状态的 AI 智能体,同时支持 Node.js 和浏览器环境。
安装
npm install agentfs-sdk
bun add agentfs-sdk
import { AgentFS } from "npm:agentfs-sdk";
快速入门
import { AgentFS } from 'agentfs-sdk';
// 使用标识符进行持久化存储
const agent = await AgentFS.open({ id: 'my-agent' });
// 创建:.agentfs/my-agent.db
// 或使用临时的内存数据库
const ephemeralAgent = await AgentFS.open();
// 使用三个主要 API
// 键值存储
await agent.kv.set('key', 'value');
// 文件系统
await agent.fs.writeFile('/file.txt', 'data');
// 工具调用跟踪
await agent.tools.record(...);
核心 API
AgentFS 类
所有 AgentFS 操作的主入口。
AgentFS.open(options?: AgentFSOptions)
创建或打开一个 AgentFS 数据库。
interface AgentFSOptions {
/**
* 可选的智能体唯一标识符。
* - 如果提供:在 `.agentfs/{id}.db` 创建持久化存储
* - 如果省略:使用临时的内存数据库
*/
id?: string;
}
// 持久化存储
const agent = await AgentFS.open({ id: 'my-agent' });
// 创建:.agentfs/my-agent.db
// 临时的内存数据库
const ephemeralAgent = await AgentFS.open();
属性
kv:键值存储接口fs:文件系统接口tools:工具调用跟踪接口db:直接访问底层 Turso 数据库
键值存储 API
为智能体状态和配置提供快速、类型化的存储。
kv.set(key: string, value: any)
存储一个值,自动进行 JSON 序列化。
await agent.kv.set('user:123', {
name: 'Alice',
preferences: { theme: 'dark' }
});
await agent.kv.set('session:current', 'abc-123');
await agent.kv.set('counter', 42);
kv.get<T>(key: string): Promise<T | undefined>
读取一个值,自动进行反序列化。
interface UserData {
name: string;
preferences: { theme: string };
}
const user = await agent.kv.get<UserData>('user:123');
if (user) {
console.log(user.name); // 类型安全的访问
}
kv.delete(key: string)
删除一个键值对。
await agent.kv.delete('session:expired');
kv.list(prefix: string): Promise<{ key: string, value: any }[]>
列出匹配指定前缀的键。
// 列出所有用户键
const userEntries = await agent.kv.list('user:');
for (const { key, value } of userEntries) {
console.log(key, value);
}
// 列出所有键(空前缀)
const allEntries = await agent.kv.list('');
文件系统 API
用于管理智能体数据的类 POSIX 文件系统操作。
fs.writeFile(path: string, data: string | Buffer)
将数据写入文件,并按需创建父目录。
// 写入文本
await agent.fs.writeFile('/reports/summary.md', '# Report\nContent...');
// 写入二进制数据
const imageBuffer = await fetch(url).then(r => r.arrayBuffer());
await agent.fs.writeFile('/images/chart.png', Buffer.from(imageBuffer));
fs.readFile(path: string, options?: BufferEncoding): Promise<Buffer | string>
读取文件内容。默认返回 Buffer;如果指定了编码,则返回字符串。
// 以 Buffer 形式读取(默认)
const data = await agent.fs.readFile('/reports/summary.md');
const text = data.toString('utf-8');
// 以指定编码的字符串形式读取
const content = await agent.fs.readFile('/reports/summary.md', 'utf-8');
// 对于 JSON 文件
const jsonData = await agent.fs.readFile('/config.json');
const config = JSON.parse(jsonData.toString());
fs.readdir(path: string): Promise<string[]>
列出目录内容。
const files = await agent.fs.readdir('/reports');
// 返回:['summary.md', '2024/', 'archive/']
// 检查每个条目的类型
for (const entry of files) {
const stats = await agent.fs.stat(`/reports/${entry}`);
if (stats.isDirectory()) {
console.log(`Directory: ${entry}`);
} else {
console.log(`File: ${entry} (${stats.size} bytes)`);
}
}
fs.stat(path: string): Promise<Stats>
获取文件或目录的元数据。
interface Stats {
size: number; // 文件大小(字节)
mode: number; // 文件模式/权限
mtime: number; // 修改时间(Unix 时间戳)
ctime: number; // 创建时间(Unix 时间戳)
isFile(): boolean;
isDirectory(): boolean;
}
const stats = await agent.fs.stat('/reports/summary.md');
console.log(`Size: ${stats.size} bytes`);
console.log(`Modified: ${new Date(stats.mtime * 1000)}`);
fs.exists(path: string): Promise<boolean>
检查文件或目录是否存在。
if (await agent.fs.exists('/reports/draft.md')) {
console.log('Draft exists');
}
fs.deleteFile(path: string)
删除一个文件。
await agent.fs.deleteFile('/reports/old.md');
工具调用跟踪 API
记录并查询智能体的工具调用,用于调试和合规审计。
tools.record(name, started_at, completed_at, parameters?, result?, error?): Promise<number>
记录一次工具调用。
await agent.tools.record(
name: string, // 工具标识符
started_at: number, // Unix 时间戳(秒)
completed_at: number, // Unix 时间戳(秒)
parameters?: any, // 工具参数(可 JSON 序列化)
result?: any, // 工具结果(可 JSON 序列化)
error?: string // 失败时的错误信息
);
// 示例:跟踪一次 API 调用
const start = Date.now() / 1000;
const response = await callOpenAI(prompt);
const id = await agent.tools.record(
'openai_completion',
start,
Date.now() / 1000,
{ prompt, model: 'gpt-4', temperature: 0.7 },
{ response, tokensUsed: 150 }
);
tools.get(id: number): Promise<ToolCall | undefined>
获取特定工具调用的详细信息。
const toolCall = await agent.tools.get(42);
if (toolCall) {
console.log('Duration:', toolCall.duration_ms, 'ms');
}
浏览器支持
AgentFS 通过 WebAssembly 在浏览器环境中运行:
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { AgentFS } from 'https://unpkg.com/agentfs-sdk/dist/browser.js';
const agent = await AgentFS.open({ id: 'browser-agent' });
// 所有 API 在浏览器中的用法完全相同
await agent.kv.set('browser:data', { platform: 'web' });
await agent.fs.writeFile('/notes.txt', 'Hello from browser!');
</script>
</head>
</html>
支持
- GitHub Issues - 缺陷报告和功能请求
- Discord - 社区支持与讨论
- 示例 - 示例应用
同步自官方 Turso 文档仓库 (
tursodatabase/turso-docs
· MIT 开源协议)
查看官方原文 ↗