# Python SDK

> 用于构建 AI 智能体的 AgentFS Python SDK
> Canonical HTML: https://tursodb.cn/zh-cn/docs/agentfs/sdk/python/
> Upstream Source (MIT): https://docs.turso.tech/agentfs/sdk/python
> Language: zh-CN

---
AgentFS Python SDK 提供了一个异步接口，用于构建具备持久化存储的 AI 智能体。

## 安装

```bash
pip install agentfs-sdk
```

## 快速开始

```python
import asyncio
from agentfs_sdk import AgentFS, AgentFSOptions

async def main():
    # Open an agent filesystem
    agent = await AgentFS.open(AgentFSOptions(id='my-agent'))

    # Use key-value store
    await agent.kv.set('config', {'debug': True})
    config = await agent.kv.get('config')

    # Use filesystem
    await agent.fs.write_file('/notes.txt', 'Hello, AgentFS!')
    content = await agent.fs.read_file('/notes.txt')

    # Track tool calls
    call_id = await agent.tools.start('search', {'query': 'Python'})
    await agent.tools.success(call_id, {'results': ['result1']})

    await agent.close()

asyncio.run(main())
```

## 打开文件系统

### 按 Agent ID

在 `.agentfs/{id}.db` 创建数据库：

```python
agent = await AgentFS.open(AgentFSOptions(id='my-agent'))
```

### 按路径

指定自定义数据库路径：

```python
agent = await AgentFS.open(AgentFSOptions(path='./data/mydb.db'))
```

### 上下文管理器

自动关闭数据库：

```python
async with await AgentFS.open(AgentFSOptions(id='my-agent')) as agent:
    await agent.kv.set('key', 'value')
    # Database is closed when exiting
```

## 键值存储

具备 JSON 序列化的简单键值存储。

### 设置值

```python
await agent.kv.set('user:123', {'name': 'Alice', 'age': 30})
await agent.kv.set('counter', 42)
await agent.kv.set('active', True)
```

### 获取值

```python
user = await agent.kv.get('user:123')
# Returns None if key doesn't exist
```

### 列出键

```python
# List all keys with prefix
keys = await agent.kv.list('user:')
# Returns: ['user:123', 'user:456', ...]
```

### 删除键

```python
await agent.kv.delete('user:123')
```

## 文件系统

类 POSIX 的文件系统操作。

### 写入文件

自动创建父目录：

```python
await agent.fs.write_file('/data/config.json', '{"key": "value"}')

# Write bytes
await agent.fs.write_file('/data/image.png', image_bytes)
```

### 读取文件

```python
# Read as string (default)
content = await agent.fs.read_file('/data/config.json')

# Read as bytes
data = await agent.fs.read_file('/data/image.png', encoding=None)
```

### 列出目录

```python
entries = await agent.fs.readdir('/data')
# Returns: ['config.json', 'image.png', ...]
```

### 获取文件信息

```python
stats = await agent.fs.stat('/data/config.json')
print(f"Size: {stats.size} bytes")
print(f"Modified: {stats.mtime}")
print(f"Is file: {stats.is_file()}")
print(f"Is directory: {stats.is_dir()}")
```

### 删除文件

```python
await agent.fs.delete_file('/data/config.json')
```

### 创建目录

```python
await agent.fs.mkdir('/data/subdir')
```

## 工具调用

跟踪并分析工具/函数调用，用于调试和审计。

### 开始并完成

```python
# Start a tool call
call_id = await agent.tools.start('search', {'query': 'Python'})

# ... perform the operation ...

# Mark as successful
await agent.tools.success(call_id, {'results': ['result1', 'result2']})

# Or mark as failed
await agent.tools.error(call_id, 'Connection timeout')
```

### 记录已完成的调用

如果你有开始时间和结束时间：

```python
await agent.tools.record(
    name='search',
    started_at=1234567890.0,
    completed_at=1234567892.0,
    parameters={'query': 'Python'},
    result={'results': ['result1']}
)
```

### 查询工具调用

```python
# Get by name
calls = await agent.tools.get_by_name('search', limit=10)

# Get recent calls
recent = await agent.tools.get_recent(since=1234567890.0)

# Get by ID
call = await agent.tools.get(42)
```

### 获取统计信息

```python
stats = await agent.tools.get_stats()
for stat in stats:
    print(f"{stat.name}:")
    print(f"  Total calls: {stat.total_calls}")
    print(f"  Successful: {stat.successful}")
    print(f"  Failed: {stat.failed}")
    print(f"  Avg duration: {stat.avg_duration_ms:.2f}ms")
```

## 完整示例

```python
import asyncio
import time
from agentfs_sdk import AgentFS, AgentFSOptions

async def main():
    async with await AgentFS.open(AgentFSOptions(id='demo-agent')) as agent:
        # Store configuration
        await agent.kv.set('agent:config', {
            'model': 'gpt-4',
            'temperature': 0.7
        })

        # Create a research document
        research = """
        # Research Notes

        ## Topic: AgentFS

        AgentFS provides persistent storage for AI agents.
        """

        await agent.fs.write_file('/research/agentfs.md', research)

        # Track a simulated tool call
        call_id = await agent.tools.start('web_search', {
            'query': 'AgentFS documentation'
        })

        # Simulate some work
        await asyncio.sleep(0.1)

        await agent.tools.success(call_id, {
            'results_count': 5,
            'top_result': 'https://docs.turso.tech/agentfs'
        })

        # List what we created
        files = await agent.fs.readdir('/research')
        print(f"Files: {files}")

        # Get tool stats
        stats = await agent.tools.get_stats()
        for stat in stats:
            print(f"{stat.name}: {stat.total_calls} calls")

asyncio.run(main())
```

## API 参考

### AgentFS

| 方法 | 描述 |
| - | - |
| `AgentFS.open(options)` | 打开或创建 Agent 文件系统 |
| `agent.close()` | 关闭数据库连接 |
| `agent.kv` | 键值存储接口 |
| `agent.fs` | 文件系统接口 |
| `agent.tools` | 工具调用接口 |

### AgentFSOptions

| 属性 | 类型 | 描述 |
| - | - | - |
| `id` | `str` | Agent 标识符（创建 `.agentfs/{id}.db`） |
| `path` | `str` | 自定义数据库路径 |

### KvStore

| 方法 | 描述 |
| - | - |
| `set(key, value)` | 存储一个值 |
| `get(key)` | 获取一个值 |
| `delete(key)` | 删除一个键 |
| `list(prefix)` | 列出具有指定前缀的键 |

### 文件系统

| 方法 | 描述 |
| - | - |
| `write_file(path, content)` | 写入文件内容 |
| `read_file(path, encoding)` | 读取文件内容 |
| `readdir(path)` | 列出目录条目 |
| `stat(path)` | 获取文件元数据 |
| `delete_file(path)` | 删除文件 |
| `mkdir(path)` | 创建目录 |

### ToolCalls

| 方法 | 描述 |
| - | - |
| `start(name, params)` | 开始跟踪一次调用 |
| `success(id, result)` | 将调用标记为成功 |
| `error(id, message)` | 将调用标记为失败 |
| `record(...)` | 记录一次已完成的调用 |
| `get(id)` | 按 ID 获取调用 |
| `get_by_name(name, limit)` | 按工具名称查询 |
| `get_recent(since)` | 获取最近的调用 |
| `get_stats()` | 获取使用统计信息 |

## 后续步骤

<div class="doc-cards">
<a class="doc-card" href="https://docs.turso.tech/agentfs/integrations/openai-agents" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>OpenAI Agents</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">将 AgentFS 与 OpenAI Agents SDK 配合使用</p></a>
<a class="doc-card" href="https://docs.turso.tech/agentfs/integrations/llamaindex" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>LlamaIndex</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">将 AgentFS 与 LlamaIndex 配合使用</p></a>
</div>
