iflow自动保存聊天记录配置

iFlow CLI 自动保存聊天记录配置教程

配置日期:2026-02-17


实现效果

每次退出 iFlow CLI 时,自动将聊天记录追加到当前目录下的 聊天记录-YYYY-MM-DD.md 文件。

支持所有退出方式

  • /exit :white_check_mark:

  • quit :white_check_mark:

  • Ctrl+C :white_check_mark:

  • 直接关闭窗口 :cross_mark:(进程被强制终止,来不及执行 hook)


前置条件

需要安装 Python 3,本教程使用:

  • Python 3.13.7

  • 安装路径:C:\Users\Administrator\AppData\Local\Programs\Python\Python313


配置步骤

1. 创建 hooks 目录和脚本

在项目目录下创建:

D:\ai\.iflow\hooks\save_chat.py

脚本内容

#!/usr/bin/env python3
"""
iFlow CLI Hook: 自动保存聊天记录到本地文件
触发时机: SessionEnd (会话结束时)
"""
import os
import sys
import json
import datetime
​
def save_chat():
    # 从标准输入读取 JSON 数据
    try:
        data = json.load(sys.stdin)
    except:
        data = {}
    
    # 获取会话信息
    session_id = data.get('session_id', os.environ.get('IFLOW_SESSION_ID', 'unknown'))
    cwd = data.get('cwd', os.environ.get('IFLOW_CWD', os.getcwd()))
    transcript_path = data.get('transcript_path', os.environ.get('IFLOW_TRANSCRIPT_PATH', ''))
    
    # 生成保存文件名
    today = datetime.datetime.now().strftime('%Y-%m-%d')
    save_file = os.path.join(cwd, f'聊天记录-{today}.md')
    
    # 追加到文件
    try:
        with open(save_file, 'a', encoding='utf-8') as f:
            f.write(f"\n\n---\n\n# 会话自动保存 {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write(f"**会话ID:** {session_id}\n\n")
            if transcript_path:
                f.write(f"**会话记录路径:** {transcript_path}\n")
        print(f"聊天记录已保存到: {save_file}")
    except Exception as e:
        print(f"保存失败: {e}", file=sys.stderr)
​
if __name__ == '__main__':
    save_chat()

2. 配置 settings.json

编辑用户目录下的配置文件:

C:\Users\Administrator\.iflow\settings.json

添加 hooks 配置

{
  "modelName": "glm-5",
  "bootAnimationShown": true,
  "searchApiKey": "sk-xxx",
  "cna": "xxx",
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "command": "C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python313\\python.exe D:\\ai\\.iflow\\hooks\\save_chat.py",
            "timeout": 30,
            "type": "command"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "command": "C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python313\\python.exe D:\\ai\\.iflow\\hooks\\save_chat.py",
            "timeout": 30,
            "type": "command"
          }
        ]
      }
    ]
  },
  "baseUrl": "https://apis.iflow.cn/v1",
  "language": "zh-CN",
  "apiKey": "sk-xxx",
  "selectedAuthType": "oauth-iflow"
}

注意

  • Python 路径要写完整路径,不要只写 python

  • Stop hook 在会话结束时触发,比 SessionEnd 更可靠

3. 重启 iFlow CLI

配置完成后,重启 iFlow 即可生效。


踩坑记录

问题1:JSON 文件 BOM 错误

错误信息Unexpected token '', "{ "cna""... is not valid JSON

原因:PowerShell 的 Out-File 默认带 BOM 头

解决方案:使用 [System.IO.File]::WriteAllText() 写入,指定 UTF-8 无 BOM

[System.IO.File]::WriteAllText("path/to/file.json", $content, [System.Text.UTF8Encoding]::new($false))

问题2:Python 命令找不到

原因:Python 没加到系统 PATH,hook 执行时找不到

解决方案:在配置里使用 Python 完整路径

问题3:SessionEnd hook 不触发

原因:配置格式或位置问题

解决方案:同时配置 SessionEndStop 两个 hook,Stop 更可靠


文件结构

D:\ai\
├── .iflow\
│   ├── settings.json          # 项目级配置(可选)
│   └── hooks\
│       └── save_chat.py       # 自动保存脚本
├── 聊天记录-2026-02-15.md     # 手动保存的记录
└── 聊天记录-2026-02-17.md     # 自动保存的记录
​
C:\Users\Administrator\.iflow\
├── settings.json              # 用户级配置(主要配置在这里)
└── projects\
    └── -D-ai\
        └── session-xxx.jsonl  # iFlow 原生会话记录

参考资料

4 个赞

本教程全程使用glm5制作,可以把这个喂ai直接帮忙配置(不过这个我还没实际测试过):thinking:

:+1:

1 个赞

其实 /resume 就能恢复聊天记录,只要是 /quit 退出的都行,ctrl + c 退出的就不清楚

1 个赞

很棒!

:+1:

请问:聊天记录是否影响项目呢? 比如 我聊天记录1工作区域是project1 记录2工作区域是project2 ,那我从记录1 resume到 记录2 ,是否会延续project2的之前的一些设定? 另外能修改会话的名字吗? 一长串不太好管理~

会话记录是跟项目的,项目 A 启动 iflow 只能看到项目 A 的会话记录,这个 /resume 自动保存的,类似游戏的自动存档

如果想要自己手动保存并改名字可以使用 /chat save <标签><标签> 替换为你想要的名字,然后在下次启动执行 /chat resume <标签> 就能选择自己手动保存的会话了,如果忘记了标签也可以用 /chat list 列出所有手动保存的会话记录

关于自定义的设定,应该使用 IFLOW.md 而不是直接通过对话实现,具体使用方法可以参考下面这个链接,而且 IFLOW.md 还有个好处就是可以直接复制粘贴到新项目,稍作修改就能直接继承一些自己想之前调了很久的规则

1 个赞