使用 PostHog 和 Langfuse 分析与调试 LlamaIndex 应用¶
本指南将展示如何通过 LlamaIndex 构建 RAG 应用,使用 Langfuse 观测执行步骤,并在 PostHog 中分析数据。
Langfuse 是什么?¶
Langfuse 是一个开源的 LLM 工程平台,旨在帮助工程师理解和优化用户与语言模型应用的交互。它提供实时追踪、调试和提升 LLM 性能的工具,适用于实际应用场景。Langfuse 既提供托管的云服务,也支持本地或自托管部署方案。
PostHog 是什么?¶
PostHog 是流行的产品分析工具。将 Langfuse 的 LLM 分析与 PostHog 的产品分析结合,可轻松实现:
- 分析用户参与度:统计用户使用特定 LLM 功能的频率,理解其整体行为模式。
- 关联反馈与行为:将 Langfuse 捕获的用户反馈与 PostHog 中的用户行为进行关联分析。
- 监控 LLM 性能:追踪模型成本、延迟时间和用户反馈等指标,优化 LLM 表现。
LlamaIndex 是什么?¶
LlamaIndex (GitHub) 是专为连接 LLM 与外部数据源设计的数据框架。它能高效完成数据结构化、索引构建和查询处理,帮助开发者更便捷地构建高级 LLM 应用。
如何使用 LlamaIndex 和 Mistral 构建简易 RAG 应用¶
本教程将演示如何创建一个聊天应用,用于解答关于刺猬养护的问题。我们将使用 Mistral 8x22B 模型通过 LlamaIndex 对刺猬养护指南进行向量化处理,并通过 Langfuse 的LlamaIndex 集成追踪所有模型生成过程。
最后,通过 PostHog 集成功能,您可以直接在 PostHog 中查看刺猬应用的详细分析数据。
第一步:配置 LlamaIndex 和 Mistral¶
首先,我们将 Mistral API 密钥设置为环境变量。若尚未注册,请先创建 Mistral 账户,随后订阅免费试用或付费方案,完成后即可生成 API 密钥(💡 您也可以使用 LlamaIndex 支持的其他任意模型,本示例仅以 Mistral 为例)。
接着,我们通过 LlamaIndex 初始化 Mistral 语言模型和嵌入模型,并将这些模型配置到 LlamaIndex 的 Settings
对象中:
%pip install llama-index llama-index-llms-mistralai llama-index-embeddings-mistralai nest_asyncio --upgrade
# Set the Mistral API key
import os
os.environ["MISTRAL_API_KEY"] = "***"
# Ensures that sync and async code can be used together without issues
import nest_asyncio
nest_asyncio.apply()
# Import and set up llama index
from llama_index.llms.mistralai import MistralAI
from llama_index.embeddings.mistralai import MistralAIEmbedding
from llama_index.core import Settings
# Define your LLM and embedding model
llm = MistralAI(model="open-mixtral-8x22b", temperature=0.1)
embed_model = MistralAIEmbedding(model_name="mistral-embed")
# Set the LLM and embedding model in the Settings object
Settings.llm = llm
Settings.embed_model = embed_model
%pip install langfuse openinference-instrumentation-llama-index wget
import os
# Get keys for your project from the project settings page: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..."
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..."
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region
设置好环境变量后,我们现在可以初始化 Langfuse 客户端。get_client()
函数会使用环境变量中提供的凭证来初始化 Langfuse 客户端。
from langfuse import get_client
langfuse = get_client()
# Verify connection
if langfuse.auth_check():
print("Langfuse client is authenticated and ready!")
else:
print("Authentication failed. Please check your credentials and host.")
Langfuse client is authenticated and ready!
现在,我们初始化 OpenInference LlamaIndex 检测工具。这个第三方检测工具会自动捕获 LlamaIndex 操作,并将 OpenTelemetry (OTel) 追踪数据导出到 Langfuse。
了解更多关于 Langfuse 的 LlamaIndex 集成信息,请参阅此处。
from openinference.instrumentation.llama_index import LlamaIndexInstrumentor
# Initialize LlamaIndex instrumentation
LlamaIndexInstrumentor().instrument()
import wget
url = "https://www.pro-igel.de/downloads/merkblaetter_engl/wildtier_engl.pdf"
wget.download(url, "./hedgehog.pdf") # saves as ./hedgehog.pdf
'./hedgehog (1).pdf'
接下来,我们使用LlamaIndex的SimpleDirectoryReader
加载PDF文件。
from llama_index.core import SimpleDirectoryReader
hedgehog_docs = SimpleDirectoryReader(
input_files=["./hedgehog.pdf"]
).load_data()
步骤4:在刺猬文档上构建RAG系统¶
接下来,我们使用VectorStoreIndex
为刺猬文档创建向量嵌入,然后将其转换为可查询的检索引擎,以便根据查询检索信息。
from llama_index.core import VectorStoreIndex
hedgehog_index = VectorStoreIndex.from_documents(hedgehog_docs)
hedgehog_query_engine = hedgehog_index.as_query_engine(similarity_top_k=5)
最后,将所有内容整合起来,我们查询引擎并打印响应:
response = hedgehog_query_engine.query("Which hedgehogs require help?")
print(response)
Hedgehogs that may require help include young hedgehogs in need of assistance during autumn, those in need of care, orphaned hoglets, and hedgehogs in need of rehabilitation before release. Additionally, hedgehogs facing dangers such as poison, pesticides, and hazards in built-up areas may also need assistance.
LLM 链的所有步骤现已在 Langfuse 中实现追踪。
Langfuse 中的追踪示例:https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/367db23d-5b03-446b-bc73-36e289596c00
步骤 5:(可选)实现用户反馈功能以监控应用表现¶
为了监测刺猬聊天应用的质量,您可以使用 Langfuse Scores 存储用户反馈(例如点赞/点踩或评论)。这些评分数据随后可在 PostHog 中进行分析。
评分功能可用于评估单个观察点或完整追踪记录。您可以通过 Langfuse 界面中的标注工作流创建评分,运行基于模型的评估,或像本示例中演示的那样通过 SDK 进行数据注入。
为获取当前观察点的上下文信息,我们使用 observe()
装饰器 并将其应用于 hedgehog_helper() 函数。
from langfuse import observe, get_client
langfuse = get_client()
# Langfuse observe() decorator to automatically create a trace for the top-level function and spans for any nested functions.
@observe()
def hedgehog_helper(user_message):
response = hedgehog_query_engine.query(user_message)
trace_id = langfuse.get_current_trace_id()
print(response)
return trace_id
trace_id = hedgehog_helper("Can I keep the hedgehog as a pet?")
# Score the trace, e.g. to add user feedback using the trace_id
langfuse.create_score(
trace_id=trace_id,
name="user-explicit-feedback",
value=0.9,
data_type="NUMERIC", # optional, inferred if not provided
comment="Good to know!", # optional
)
Based on the provided context, there is no information regarding keeping hedgehogs as pets. The text primarily discusses the biology, behavior, and protection of wild hedgehogs. It is important to note that laws and regulations regarding the keeping of wild animals as pets can vary greatly, so it is always best to consult with local wildlife authorities or experts.
步骤 6:在 PostHog 中查看数据¶
最后,我们将 PostHog 与 Langfuse 账户连接。以下是操作步骤的概要(完整说明请参阅文档):
- 若尚未注册,请先注册免费 PostHog 账户
- 从项目设置中复制项目 API 密钥和主机地址
- 在 Langfuse 控制台中点击 Settings,滚动至 Integrations 部分找到 PostHog 集成
- 点击 Configure 并粘贴 PostHog 主机地址和项目 API 密钥(可在 PostHog 项目设置中找到)
- 启用 Enabled 后点击 Save
Langfuse 将开始每日向 PostHog 导出数据。
使用 Langfuse 仪表板模板:
完成集成安装后,仪表板模板可帮助快速建立相关分析视图。
针对我们的刺猬聊天应用,我们使用如下所示的模板仪表板。该模板支持在 PostHog 中分析模型成本、用户反馈和延迟指标。
通过模板创建自定义仪表板:
- 进入 PostHog 的仪表板标签页
- 点击右上角 New dashboard 按钮
- 从模板列表中选择 LLM metrics – Langfuse