在AI模型的微调或少样本学习中,聊天数据通常扮演着重要的角色。然而,从WeChat导出消息并不那么直截了当。本文将演示如何从WeChat桌面应用复制的消息创建自己的聊天加载器,并将其转换为LangChain兼容的消息格式。
技术背景介绍
WeChat是中国使用最广泛的聊天应用程序之一,但其消息导出功能比较有限。LangChain是一个用于构建强大AI应用程序的框架,支持多种聊天加载器。我们将借鉴LangChain中Discord聊天加载器的设计,通过自定义代码实现WeChat聊天的导入。
核心原理解析
这个方法主要分为以下几个步骤:
- 从WeChat桌面应用中选择并复制所需的消息。
- 将复制的消息粘贴到本地的
.txt
文件中。 - 创建自定义的WeChat聊天加载器,解析文本文件并生成LangChain格式的消息。
代码实现演示
首先,我们需要创建一个消息转储文件。以下是如何生成一个示例WeChat聊天文件:
%%writefile wechat_chats.txt
女朋友 2023/09/16 2:51 PM
天气有点凉
男朋友 2023/09/16 2:51 PM
珍簟凉风著,瑶琴寄恨生。嵇君懒书札,底物慰秋情。
女朋友 2023/09/16 3:06 PM
忙什么呢
男朋友 2023/09/16 3:06 PM
今天只干成了一件像样的事
那就是想你
女朋友 2023/09/16 3:06 PM
[动画表情]
接下来,我们定义一个WeChat聊天加载器:
import logging
import re
from typing import Iterator, List
from langchain_community.chat_loaders import base as chat_loaders
from langchain_core.messages import BaseMessage, HumanMessage
logger = logging.getLogger()
class WeChatChatLoader(chat_loaders.BaseChatLoader):
def __init__(self, path: str):
self.path = path
self._message_line_regex = re.compile(
r"(?P<sender>.+?) (?P<timestamp>\d{4}/\d{2}/\d{2} \d{1,2}:\d{2} (?:AM|PM))"
)
def _append_message_to_results(self, results: List, current_sender: str, current_timestamp: str, current_content: List[str]):
content = "\n".join(current_content).strip()
if not re.match(r"\[.*\]", content):
results.append(
HumanMessage(
content=content,
additional_kwargs={
"sender": current_sender,
"events": [{"message_time": current_timestamp}],
},
)
)
return results
def _load_single_chat_session_from_txt(self, file_path: str) -> chat_loaders.ChatSession:
with open(file_path, "r", encoding="utf-8") as file:
lines = file.readlines()
results: List[BaseMessage] = []
current_sender = None
current_timestamp = None
current_content = []
for line in lines:
if re.match(self._message_line_regex, line):
if current_sender and current_content:
results = self._append_message_to_results(results, current_sender, current_timestamp, current_content)
current_sender, current_timestamp = re.match(self._message_line_regex, line).groups()
current_content = []
else:
current_content.append(line.strip())
if current_sender and current_content:
results = self._append_message_to_results(results, current_sender, current_timestamp, current_content)
return chat_loaders.ChatSession(messages=results)
def lazy_load(self) -> Iterator[chat_loaders.ChatSession]:
yield self._load_single_chat_session_from_txt(self.path)
# 初始化加载器
loader = WeChatChatLoader(path="./wechat_chats.txt")
然后加载消息并进行转换:
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)
# 将 "男朋友" 发送的信息转换成AI消息
messages: List[ChatSession] = list(map_ai_messages(merged_messages, sender="男朋友"))
# 打印转换后的消息
for message in messages[0]["messages"]:
print(message)
应用场景分析
这种转换格式适用于以下场景:
- 微调AI聊天模型:使用真实的聊天数据对模型进行适应性调整。
- 少样本学习:为模型提供上下文例子,提高其应答质量。
- 聊天记录分析:进行数据挖掘与情感分析。
实践建议
- 确保复制的文本格式与正则表达式匹配,避免解析错误。
- 小心处理个人隐私信息,确保文件和API密钥安全。
- 定期更新和维护代码库,以适应LangChain的版本迭代。
如果遇到问题欢迎在评论区交流。
—END—