在现代人工智能应用中,调试和可视化自动化工作流变得越来越重要,Aim正是为此而生。通过Aim,你可以轻松地追踪LangChain中语言模型(LLM)和工具的输入输出,以及代理的动作,从而在执行过程中快速定位和解决问题。此外,Aim还支持并排比较多个执行流程,使之成为调试中的得力助手。
Aim是一个完全开源的项目,你可以在GitHub上找到更多关于Aim的信息。在本文中,我们将展示如何启用和配置Aim回调,以便追踪LangChain的执行过程。
LangChain是一个用于构建语言模型驱动的应用程序的框架,它可以利用不同的LLM组件和工具链来实现复杂的功能。然而,随着功能复杂度的增加,如何有效地调试和监控执行过程成为了一大挑战。Aim通过捕获和记录执行过程中的细节,提供了一种有效的解决方案。
Aim通过回调接口与LangChain集成,能够捕获模块或代理的提示和生成结果,并将这些信息序列化后记录在Aim的运行中。这样,不仅能观看到执行的详细过程,还可以持久化这些记录以供后续分析和对比。
在本节中,我们将实现三种典型的LangChain使用场景,并使用Aim进行执行过程的追踪。
首先,我们需要安装必需的Python包:
%pip install --upgrade --quiet aim langchain langchain-openai 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
# 配置API密钥
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["SERPAPI_API_KEY"] = "your-serpapi-api-key"
在第一个场景中,我们使用OpenAI的语言模型来生成文本:
# 使用稳定可靠的API服务
llm = OpenAI(
base_url='https://yunwu.ai/v1',
api_key=os.environ["OPENAI_API_KEY"],
temperature=0,
callbacks=[StdOutCallbackHandler(), AimCallbackHandler(repo=".", experiment_name="scenario 1: OpenAI LLM")]
)
# 生成示例文本
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
在第二个场景中,我们使用LLMChain来构建一个链式调用:
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)
# 初始化LLMChain
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=[StdOutCallbackHandler(), AimCallbackHandler(repo=".", experiment_name="scenario 2: Chain with multiple SubChains")])
# 执行链式调用
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)
在第三个场景中,我们构建一个代理来执行综合任务:
from langchain.agents import AgentType, initialize_agent, load_tools
# 加载工具
tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=[StdOutCallbackHandler(), AimCallbackHandler(repo=".", experiment_name="scenario 3: Agent with Tools")])
# 初始化代理
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
callbacks=[StdOutCallbackHandler(), AimCallbackHandler(repo=".", experiment_name="scenario 3: Agent with Tools")]
)
# 运行代理
agent.run(
"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
通过Aim的追踪功能,我们可以在开发调试和产品监控两个方面受益。对于开发者,能够记录执行过程中每一步的详细信息,有助于快速发现问题。而在产品上线后,Aim提供的持久化信息可以帮助运营人员分析用户行为,优化产品体验。
如果遇到问题欢迎在评论区交流。
—END—