老铁们,今天咱们来聊聊如何用Aim可视化和调试LangChain的执行过程。Aim这个工具特别适合跟踪LLM和工具的输入输出,还能记录代理的操作。说白了,Aim就是让调试和检查执行过程变得超级简单!
先来点背景,Aim是一个开源项目,能帮我们在执行过程中看到每一个步骤的详细信息,还能对比多个执行结果。想了解更多可以去Aim的GitHub看看。
下面我们就来具体看看怎么操作,先从安装必要的包开始。
%pip install --upgrade --quiet aim
%pip install --upgrade --quiet langchain
%pip install --upgrade --quiet langchain-openai
%pip install --upgrade --quiet 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
首先需要获取OpenAI的API密钥,可以通过这个链接获取。同时我们还需要SerpApi的密钥,获取方法在这里。
os.environ["OPENAI_API_KEY"] = "..."
os.environ["SERPAPI_API_KEY"] = "..."
使用Aim跟踪LangChain执行
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)
flush_tracker
函数用于在Aim上记录LangChain资产。默认情况下,session会被重置,而不是直接终止。
场景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
第二个场景涉及多个SubChains的链式调用。
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)
这波操作可以说是相当丝滑,让我们对整个过程的理解更加透彻。
今天的技术分享就到这里,希望对大家有帮助。开发过程中遇到问题也可以在评论区交流~
—END—