Skip to content

文件交互

插件运行在主服务进程中,AI 运行在隔离的沙盒容器内,双方看到的文件路径不同。_ctx.fsFileSystem 实例)提供了在插件与沙盒之间传递文件的标准接口。

与插件数据目录的区别

plugin.get_plugin_data_dir() 解决「插件自己把文件存在哪里」。_ctx.fs 解决「文件如何在插件与沙盒之间流转」。两者通常配合使用,但职责不同。

路径概念

概念说明示例
沙盒路径AI 看到的路径(容器内)/app/shared/output.txt
宿主机路径插件实际操作的路径/data/sandbox/.../shared/output.txt

_ctx.fs 的各方法自动完成两种路径之间的转换。

插件向 AI 传递文件

mixed_forward_file

接受 URL、bytesPath 或本地文件路径,将其复制到沙盒共享目录,返回沙盒内可访问的路径字符串。

python
# 从远程 URL 获取图片,返回给 AI
sandbox_path = await _ctx.fs.mixed_forward_file(
    "https://example.com/image.png",
    file_name="image.png",
)
return sandbox_path   # "/app/shared/image.png"

# 从字节数据生成文件
data = json.dumps(result, ensure_ascii=False).encode()
sandbox_path = await _ctx.fs.mixed_forward_file(data, file_name="result.json")
return sandbox_path

forward_file

将已经位于 shared_pathupload_path 下的文件转换为沙盒路径字符串(同步,不复制文件)。

python
output = _ctx.fs.shared_path / "report.md"
output.write_text("# 报告内容")
return _ctx.fs.forward_file(output)   # "/app/shared/report.md"

shared_path

当前频道的共享目录(Path 对象),是插件写入临时文件后交给 AI 的标准位置。

python
target = _ctx.fs.shared_path / "output.csv"
target.write_text(csv_content)

AI 向插件传递文件

get_file

将 AI 传入的沙盒路径转换为宿主机上的 Path 对象,插件通过该路径实际读取文件。

python
@plugin.mount_sandbox_method(SandboxMethodType.TOOL, "分析文件")
async def analyze_file(_ctx: AgentCtx, file_path: str) -> str:
    host_path = _ctx.fs.get_file(file_path)  # 沙盒路径 -> 宿主机路径

    if not host_path.exists():
        return "指定文件不存在"

    content = host_path.read_text(encoding="utf-8")
    # 处理 content...
    return f"文件共 {len(content)} 字符"

合法的沙盒路径前缀为 /app/shared//app/uploads/,传入其他路径会抛出 ValueError

结合消息发送

处理完成后,可直接通过 _ctx 发送文件或图片给用户,无需单独调用消息 API:

python
@plugin.mount_sandbox_method(SandboxMethodType.BEHAVIOR, "生成报告")
async def generate_report(_ctx: AgentCtx, title: str, content: str) -> str:
    report = f"# {title}\n\n{content}"
    sandbox_path = await _ctx.fs.mixed_forward_file(
        report.encode(), file_name="report.md"
    )
    await _ctx.send_file(sandbox_path)
    return "报告已生成并发送"

其他属性

属性类型说明
_ctx.fs.chat_keystr当前聊天频道标识
_ctx.fs.container_keystr当前沙盒容器标识
_ctx.fs.upload_pathPath用户上传文件目录(宿主机路径)

相关文档