python sdk 使用文件系统前必看

iFlow Python SDK - 文件系统使用指南

概述

iFlow Python SDK 提供了安全的文件系统访问功能,允许 AI 助手在受控环境下读写本地文件。该功能基于白名单机制,确保只能访问明确授权的目录。

核心特性

  • :white_check_mark: 目录白名单 - 只允许访问指定目录
  • :white_check_mark: 路径安全 - 自动防止路径遍历攻击
  • :white_check_mark: 大小限制 - 可配置文件大小上限
  • :white_check_mark: 只读模式 - 可选的只读访问模式
  • :white_check_mark: 权限控制 - 细粒度的文件操作权限

快速开始

最小配置(访问当前目录)

from iflow_sdk import IFlowClient, IFlowOptions

options = IFlowOptions(
    file_access=True,  # 必须:启用文件系统
)

async with IFlowClient(options) as client:
    await client.send_message("读取当前目录下的 README.md")
    # ... 处理响应

说明

  • file_access=True必需的,默认为 False
  • 不指定 file_allowed_dirs 时,默认只能访问 Python 进程的当前工作目录

配置参数

必需参数

参数 类型 默认值 说明
file_access bool False 必须设置为 True 才能启用文件系统功能

重要参数

参数 类型 默认值 说明
file_allowed_dirs List[str] None 允许访问的目录列表。None 表示只允许当前工作目录
cwd str os.getcwd() iFlow CLI 的工作目录。如果与当前目录不同,必须在 file_allowed_dirs 中包含

可选参数

参数 类型 默认值 说明
file_read_only bool False 是否只读模式。True 时禁止写入操作
file_max_size int 10485760 文件大小限制(字节),默认 10MB

使用场景

场景 1:访问指定目录

from pathlib import Path
from iflow_sdk import IFlowClient, IFlowOptions

# 指定允许访问的目录
workspace = Path("/path/to/workspace")

options = IFlowOptions(
    file_access=True,
    file_allowed_dirs=[str(workspace)],  # 明确指定目录
)

async with IFlowClient(options) as client:
    await client.send_message("列出 workspace 目录下的所有 Python 文件")

场景 2:访问多个目录

options = IFlowOptions(
    file_access=True,
    file_allowed_dirs=[
        "/home/user/project",
        "/home/user/data",
        "/tmp/cache"
    ],
)

场景 3:只读模式(安全审查)

options = IFlowOptions(
    file_access=True,
    file_allowed_dirs=["/home/user/codebase"],
    file_read_only=True,  # 禁止写入
)

async with IFlowClient(options) as client:
    await client.send_message("分析这个项目的代码结构")
    # AI 只能读取,无法修改文件

场景 4:自定义工作目录

import os

project_dir = "/home/user/my_project"

options = IFlowOptions(
    cwd=project_dir,  # iFlow 的工作目录
    file_access=True,
    file_allowed_dirs=[project_dir],  # ⚠️ 必须包含 cwd
)

:warning: 重要提示:如果 cwd 与当前 Python 工作目录不同,必须file_allowed_dirs 中明确包含 cwd,否则会导致权限错误。


完整示例

import asyncio
from pathlib import Path
from iflow_sdk import IFlowClient, IFlowOptions, ApprovalMode, AssistantMessage, TaskFinishMessage


async def main():
    # 1. 准备工作目录
    workspace = Path.cwd() / "workspace"
    workspace.mkdir(exist_ok=True)
    
    # 2. 配置文件系统访问
    options = IFlowOptions(
        # 必需配置
        file_access=True,
        file_allowed_dirs=[str(workspace)],
        
        # 可选配置
        file_read_only=False,
        file_max_size=5 * 1024 * 1024,  # 5MB
        cwd=str(workspace),
        
        # 其他配置
        approval_mode=ApprovalMode.YOLO,  # 自动执行工具
    )
    
    # 3. 创建客户端并使用
    async with IFlowClient(options) as client:
        # 发送文件操作请求
        await client.send_message(
            f"在 {workspace} 目录下创建一个 hello.py 文件,"
            "内容为一个简单的 Hello World 程序"
        )
        
        # 接收响应
        async for message in client.receive_messages():
            if isinstance(message, AssistantMessage):
                print(message.chunk.text, end="", flush=True)
            elif isinstance(message, TaskFinishMessage):
                print(f"\n完成: {message.stop_reason}")
                break
        
        # 验证文件
        hello_file = workspace / "hello.py"
        if hello_file.exists():
            print(f"\n✓ 文件已创建: {hello_file}")
            print(f"内容:\n{hello_file.read_text()}")


if __name__ == "__main__":
    asyncio.run(main())

安全最佳实践

:white_check_mark: 推荐做法

  1. 最小权限原则

    # 只授权必需的目录
    file_allowed_dirs=["/specific/project/dir"]
    
  2. 使用绝对路径

    from pathlib import Path
    file_allowed_dirs=[str(Path("/path/to/dir").resolve())]
    
  3. 生产环境使用只读模式

    file_read_only=True  # 审查或分析时
    
  4. 设置合理的文件大小限制

    file_max_size=1 * 1024 * 1024  # 1MB,避免大文件
    

:cross_mark: 避免做法

  1. 不要授权根目录或系统目录

    # ❌ 危险!
    file_allowed_dirs=["/", "/etc", "/usr"]
    
  2. 不要忽略 cwd 和 file_allowed_dirs 的一致性

    # ❌ 错误配置
    options = IFlowOptions(
        cwd="/project/a",
        file_allowed_dirs=["/project/b"]  # cwd 不在允许列表中
    )
    
  3. 不要在未启用 file_access 时期望文件操作

    # ❌ 不会生效
    options = IFlowOptions(
        file_access=False,  # 未启用
        file_allowed_dirs=["/some/dir"]
    )
    

错误处理

常见错误

1. PermissionError: Access denied

原因:尝试访问不在 file_allowed_dirs 中的文件

解决

# 确保目标目录在允许列表中
options = IFlowOptions(
    file_access=True,
    file_allowed_dirs=["/correct/path"]
)

2. ValueError: File too large

原因:文件超过 file_max_size 限制

解决

options = IFlowOptions(
    file_access=True,
    file_max_size=50 * 1024 * 1024  # 增加到 50MB
)

3. PermissionError: File system is in read-only mode

原因:在只读模式下尝试写入

解决

options = IFlowOptions(
    file_access=True,
    file_read_only=False  # 允许写入
)

配置检查清单

在使用文件系统功能前,请确认:

  • file_access=True 已设置
  • file_allowed_dirs 包含所有需要访问的目录
  • 如果设置了 cwd,确保它在 file_allowed_dirs
  • file_max_size 足够大以处理目标文件
  • 根据需求设置 file_read_only 模式
  • 使用绝对路径而非相对路径

2 个赞

顶! :+1: