跳转到主要内容
AG-Kit 的文件系统工具为您的 Agent 提供了与文件交互的全面可靠方案。通过支持事务处理、多种后端和统一工具包,它专为构建执行基于文件任务的稳健 Agent 而设计。

功能概览

使用此工具包可让您的 Agent 具备以下能力:
  • 原子操作:安全地同时修改多个文件,失败时自动回滚。
  • 管理文件与目录:创建、读取、更新、删除及列出文件和目录。
  • 文件系统搜索:通过名称(glob)或内容(grep)查找文件。
  • 安全环境运行:根据安全需求选择本地、内存或沙盒后端。

核心概念

  1. FilesystemToolkit:主要入口点,集成了可供 Agent 直接使用的文件相关工具集(read_filewrite_file 等)。
  2. FileOperator(后端):执行实际文件操作的引擎,提供三种后端选择:
    • LocalFileOperator:高性能访问本地文件系统。
    • InMemoryFileOperator:在虚拟文件系统中进行快速隔离测试。
    • SandboxFileOperator:在隔离容器中安全执行,适合处理不可信代码。

快速入门

from agkit.tools import FilesystemToolkit, LocalFileOperator
import os

# 1. 选择后端并创建工具包
operator = LocalFileOperator()
fs_toolkit = FilesystemToolkit(
    name="fs",
    context={"working_directory": os.getcwd(), "fs_operator": operator}
)

# 2. 获取工具并使用
write_tool = fs_toolkit.get_tool("write_file")
await write_tool.invoke({
    "file_path": "greeting.txt",
    "content": "Hello"
})

关键特性:原子事务

对于代码生成等复杂任务,常需修改多个文件。若某步失败,可能导致项目处于损坏状态。事务机制通过”全成功或全回滚”确保数据一致性。 withTransaction 内任何操作失败,所有变更将自动回滚。
from agkit.tools.fs.operator.transaction import with_transaction
from agkit.tools import LocalFileOperator

operator = LocalFileOperator()

try:
    await with_transaction(operator, async def tx:
        # 以下操作具有原子性
        await tx.write_file('src/component.py', '# New component code')
        await tx.write_file('src/__init__.py', 'from .component import *')
        # 若此处失败,前述两个文件将被还原
        await tx.write_file('setup.py', 'invalid python')
    )
except Exception as error:
    print(f'事务失败已回滚: {error}')
高级事务控制详见应用程序接口参考

核心操作

以下是工具包支持的主要操作。

写入与创建文件

write_file 工具可创建新文件或覆盖现有文件,若父目录不存在会自动创建。
result = await fs_toolkit.get_tool('write_file').invoke({
    'file_path': 'src/utils/helpers.py',
    'content': 'def new_util():\n    pass'
})
# result.data: { 'file_path': 'src/utils/helpers.py', 'bytes_written': 28 }

读取文件

read_file 工具可读取指定文件的全部内容。
result = await fs_toolkit.get_tool('read_file').invoke({
    'file_path': 'package.json'
})
# result.data: '{\n  "name": "my-app",\n  ...'
print(result.data.content)

编辑文件

edit_file 工具对文件内容执行查找替换,适合进行针对性修改。
result = await fs_toolkit.get_tool('edit_file').invoke({
    'file_path': 'src/config.py',
    'old_str': 'API_ENDPOINT = "http://dev.example.com"',
    'new_str': 'API_ENDPOINT = "http://prod.example.com"'
})
# result.data: { 'file_path': 'src/config.py', 'replacements_made': 1 }

列出目录内容

ls 工具可列出指定路径下的文件和子目录。
result = await fs_toolkit.get_tool('ls').invoke({'path': 'src'})
# result.data: { 
#   'entries': [
#     { 'name': 'components', 'type': 'directory', 'size': 0 },
#     { 'name': 'utils', 'type': 'directory', 'size': 0 },
#     { 'name': 'index.py', 'type': 'file', 'size': 1024 }
#   ]
# }
print([entry.name for entry in result.data.entries])

模式匹配查找(Glob)

glob 工具可查找匹配特定模式的所有文件和目录,便于预处理文件发现。
result = await fs_toolkit.get_tool('glob').invoke({
    'pattern': '**/*.test.py'
})
# result.data: { 
#   'matches': [
#     'src/utils/helpers_test.py',
#     'src/components/button_test.py',
#     'tests/integration_test.py'
#   ]
# }
print('发现测试文件:', result.data.matches)

文件内容搜索(Grep)

grep 工具可在指定目录文件中搜索文本模式(支持正则表达式),适用于定位函数调用或特定注释。
result = await fs_toolkit.get_tool('grep').invoke({
    'pattern': 'TODO|FIXME',
    'path': 'src'
})
# result.data: {
#   'matches': [
#     { 'file': 'src/utils/helpers.py', 'line_number': 42, 'line_content': '  # TODO: Optimize this function' },
#     { 'file': 'src/components/button.py', 'line_number': 15, 'line_content': '  # FIXME: Handle edge case' }
#   ]
# }

if len(result.data.matches) > 0:
    print('Matches found:')
    for match in result.data.matches:
        print(f"- {match.file}:{match.line_number}: {match.line_content.strip()}")
所有工具的详细输入输出模式,请参阅API参考

工作流示例:Agent集成

FilesystemToolkit直接集成到您的Agent中,为其提供强大的文件操作能力。
from agkit.tools import FilesystemToolkit, LocalFileOperator

fs_toolkit = FilesystemToolkit(
    name="fs",
    context={"working_directory": os.getcwd(), "fs_operator": LocalFileOperator()}
)

tools=fs_toolkit.get_tools()

后续步骤