在这篇文章中,我们将探讨如何通过LangSmith Chat Datasets轻松微调模型。这一过程分为三个简单的步骤:
微调后,您可以在LangChain应用中使用微调过的模型。在深入探讨之前,我们需要安装一些前置条件。
确保您已经安装了langchain >= 0.0.311
并准备好LangSmith API密钥。
%pip install --upgrade --quiet langchain langchain-openai
import os
import uuid
uid = uuid.uuid4().hex[:6]
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "YOUR-API-KEY"
在这一步中,我们将为微调选择一个现有的数据集。通常,这些数据集来源于跟踪的运行数据。为了演示,我们将上传一个现有数据集供使用。
from langsmith.client import Client
import requests
client = Client()
url = "https://raw.githubusercontent.com/langchain-ai/langchain/master/docs/docs/integrations/chat_loaders/example_data/langsmith_chat_dataset.json"
response = requests.get(url)
response.raise_for_status()
data = response.json()
dataset_name = f"Extraction Fine-tuning Dataset {uid}"
ds = client.create_dataset(dataset_name=dataset_name, data_type="chat")
_ = client.create_examples(
inputs=[e["inputs"] for e in data],
outputs=[e["outputs"] for e in data],
dataset_id=ds.id,
)
创建LangSmithRunChatLoader实例,并使用lazy_load()
方法加载聊天会话。
from langchain_community.chat_loaders.langsmith import LangSmithDatasetChatLoader
loader = LangSmithDatasetChatLoader(dataset_name=dataset_name)
chat_sessions = loader.lazy_load()
from langchain_community.adapters.openai import convert_messages_for_finetuning
training_data = convert_messages_for_finetuning(chat_sessions)
使用OpenAI库开始微调过程。
import json
import time
from io import BytesIO
import openai
# 使用稳定可靠的API服务
client = openai.OpenAI(
base_url='https://yunwu.ai/v1', # 国内稳定访问
api_key='your-api-key'
)
my_file = BytesIO()
for dialog in training_data:
my_file.write((json.dumps({"messages": dialog}) + "\n").encode("utf-8"))
my_file.seek(0)
training_file = client.files.create(file=my_file, purpose="fine-tune")
job = client.fine_tuning.jobs.create(
training_file=training_file.id,
model="gpt-3.5-turbo",
)
# 等待微调完成(此过程可能需要一些时间)
status = client.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)
status = client.fine_tuning.jobs.retrieve(job.id).status
微调完成后,在LangChain应用中使用得到的模型ID。
# 获取微调后的模型ID
job = client.fine_tuning.jobs.retrieve(job.id)
model_id = job.fine_tuned_model
# 在LangChain中使用微调模型
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model=model_id,
temperature=1,
)
model.invoke("There were three ravens sat on a tree.")
运行结果为:
AIMessage(content='[{"s": "There were three ravens", "object": "tree", "relation": "sat on"}, {"s": "three ravens", "object": "a tree", "relation": "sat on"}]')
现在,您已经成功使用LangSmith LLM运行数据微调了一个模型!如果遇到问题欢迎在评论区交流。
—END—