iFlow CLI 自动保存聊天记录配置教程
配置日期:2026-02-17
实现效果
每次退出 iFlow CLI 时,自动将聊天记录追加到当前目录下的 聊天记录-YYYY-MM-DD.md 文件。
支持所有退出方式:
-
/exit
-
quit
-
Ctrl+C
-
直接关闭窗口
(进程被强制终止,来不及执行 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 -
Stophook 在会话结束时触发,比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 不触发
原因:配置格式或位置问题
解决方案:同时配置 SessionEnd 和 Stop 两个 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 原生会话记录
参考资料
- iFlow CLI 官方文档:https://platform.iflow.cn/cli/examples/hooks
