# Python SDK

> 用於建構 AI 代理的 AgentFS Python SDK
> Canonical HTML: https://tursodb.cn/zh-tw/docs/agentfs/sdk/python/
> Upstream Source (MIT): https://docs.turso.tech/agentfs/sdk/python
> Language: zh-TW

---
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())
```

## 開啟檔案系統

### 依代理 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.close()` | 關閉資料庫連線 |
| `agent.kv` | 鍵值儲存介面 |
| `agent.fs` | 檔案系統介面 |
| `agent.tools` | 工具呼叫介面 |

### AgentFSOptions

| 屬性 | 型別 | 說明 |
| - | - | - |
| `id` | `str` | 代理識別碼（會建立 `.agentfs/{id}.db`） |
| `path` | `str` | 自訂資料庫路徑 |

### KvStore

| 方法 | 說明 |
| - | - |
| `set(key, value)` | 儲存值 |
| `get(key)` | 取得值 |
| `delete(key)` | 刪除鍵 |
| `list(prefix)` | 列出具有指定前綴的鍵 |

### Filesystem

| 方法 | 說明 |
| - | - |
| `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>
