Tools 示例

文件操作工具

使用文件系统工具读写文件

文件操作工具示例

展示如何使用内置的文件系统工具进行文件操作。

完整代码

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/astercloud/aster/pkg/agent"
    "github.com/astercloud/aster/pkg/provider"
    "github.com/astercloud/aster/pkg/sandbox"
    "github.com/astercloud/aster/pkg/store"
    "github.com/astercloud/aster/pkg/tools"
    "github.com/astercloud/aster/pkg/tools/builtin"
    "github.com/astercloud/aster/pkg/types"
)

func main() {
    ctx := context.Background()

    // 创建工具注册表
    toolRegistry := tools.NewRegistry()
    builtin.RegisterAll(toolRegistry)

    // 创建依赖
    deps := &agent.Dependencies{
        ToolRegistry:     toolRegistry,
        SandboxFactory:   sandbox.NewFactory(),
        ProviderFactory:  provider.NewMultiProviderFactory(),
        Store:            store.NewMemoryStore(),
        TemplateRegistry: agent.NewTemplateRegistry(),
    }

    // 创建 Agent
    ag, err := agent.Create(ctx, &types.AgentConfig{
        TemplateID: "assistant",
        ModelConfig: &types.ModelConfig{
            Provider: "anthropic",
            Model:    "claude-sonnet-4-5",
            APIKey:   os.Getenv("ANTHROPIC_API_KEY"),
        },
        Tools: []string{"filesystem"},  // 只启用文件系统工具
    }, deps)
    if err != nil {
        log.Fatal(err)
    }
    defer ag.Close()

    // 测试不同的文件操作
    tasks := []string{
        "创建一个 config.json 文件,内容是 {\"app\": \"demo\", \"version\": \"1.0\"}",
        "读取 config.json 文件的内容",
        "列出当前目录的所有 .json 文件",
        "在 config.json 中搜索包含 'demo' 的内容",
    }

    for i, task := range tasks {
        fmt.Printf("\n========== 任务 %d ==========\n", i+1)
        fmt.Printf("请求: %s\n\n", task)

        result, err := ag.Chat(ctx, task)
        if err != nil {
            log.Printf("错误: %v", err)
            continue
        }

        fmt.Printf("响应: %s\n", result.Message.Content)
    }
}

可用的文件系统工具

1. filesystem_read

读取文件内容。

// Agent 会调用
{
    "path": "config.json"
}

2. filesystem_write

写入文件。

// Agent 会调用
{
    "path": "output.txt",
    "content": "Hello World"
}

3. filesystem_list

列出目录内容。

// Agent 会调用
{
    "path": ".",
    "recursive": false
}

4. filesystem_delete

删除文件。

// Agent 会调用
{
    "path": "temp.txt"
}

搜索文件内容。

// Agent 会调用
{
    "path": ".",
    "pattern": "TODO",
    "file_pattern": "*.go"
}

运行示例

export ANTHROPIC_API_KEY="sk-ant-xxx"
go run main.go

输出示例

========== 任务 1 ==========
请求: 创建一个 config.json 文件,内容是 {"app": "demo", "version": "1.0"}

响应: 我已经创建了 config.json 文件,内容如下:
```json
{
  "app": "demo",
  "version": "1.0"
}

========== 任务 2 ========== 请求: 读取 config.json 文件的内容

响应: config.json 文件的内容是:

{
  "app": "demo",
  "version": "1.0"
}

========== 任务 3 ========== 请求: 列出当前目录的所有 .json 文件

响应: 当前目录中的 .json 文件有:

  • config.json (56 bytes)
  • package.json (342 bytes)

========== 任务 4 ========== 请求: 在 config.json 中搜索包含 'demo' 的内容

响应: 在 config.json 中找到 1 处匹配: 第 2 行: "app": "demo"


## 实用场景

### 配置文件管理

```go
result, _ := ag.Chat(ctx, "读取 config.yaml 并将端口从 8080 改为 9000")
// Agent 会:
// 1. 读取 config.yaml
// 2. 修改端口
// 3. 写回文件

代码重构

result, _ := ag.Chat(ctx, "在所有 .go 文件中将 'oldFunc' 替换为 'newFunc'")
// Agent 会:
// 1. 搜索所有 .go 文件
// 2. 查找 'oldFunc'
// 3. 逐个替换并保存

日志分析

result, _ := ag.Chat(ctx, "分析 app.log 中的错误信息,统计每种错误的数量")
// Agent 会:
// 1. 读取 app.log
// 2. 提取错误信息
// 3. 统计和分类

沙箱隔离

文件系统工具在沙箱中运行,确保安全:

ag, err := agent.Create(ctx, &types.AgentConfig{
    // ...
    Sandbox: &types.SandboxConfig{
        Kind:    types.SandboxKindLocal,
        WorkDir: "./workspace",  // 限制在此目录
    },
}, deps)

// Agent 只能访问 ./workspace 目录下的文件

相关资源