OpenLLMetry LlamaIndex 插桩全指南:为 RAG 与 Agent 应用一键接入 OpenTelemetry 可观测性

原创2026-10-14 09:36:491,724 阅读
文章标签:LLMOps可观测性

OpenLLMetry LlamaIndex 插桩全指南:为 RAG 与 Agent 应用一键接入 OpenTelemetry 可观测性

导读

opentelemetry-instrumentation-llamaindex 是 openllmetry 仓库中面向 LlamaIndex 的 OpenTelemetry 插桩库,能够让基于 LlamaIndex 构建的 RAG、Agent 与查询管道应用自动生成完整、结构化的追踪(trace):从 LLM 对话、Embedding、检索(Retriever)、答案合成(Synthesizer)、工具调用,到 Agent 工作流与 LlamaParse 文档解析,全部覆盖。本文以 opentelemetry-instrumentation-llamaindex/README.md 为主体,结合仓库源码与测试用例,讲解安装、接入、追踪能力边界、span 结构与语义属性,以及通过 TRACELOOP_TRACE_CONTENT 环境变量控制隐私敏感内容采集的最佳实践。读完本文,你将掌握 LlamaIndex 应用接入 OpenTelemetry 追踪的完整方案,并能按需开关内容级(prompt/completion)数据采集。

一、这是什么:针对 LlamaIndex 的完整链路追踪

该库的目标是"tracing complete LLM applications built with LlamaIndex"(见 README.md),即不局限于 LLM 调用本身,而是覆盖一条完整的 RAG/Agent 应用链路。它基于 OpenTelemetry 标准实现,遵循 GenAI 语义约定(gen_ai.* 属性),因此产出的 span 可以无缝接入任何兼容 OpenTelemetry 的后端(Traceloop、Jaeger、Tempo 等)。

从 pyproject.toml 可以看到其依赖面:opentelemetry-api>=1.38.0,<2、opentelemetry-instrumentation>=0.59b0、opentelemetry-semantic-conventions-ai>=0.5.1,<0.6.0,要求 Python >=3.10,<4,并注册了 opentelemetry_instrumentor 入口点 llama-index,使库可以被 OpenTelemetry 的自动插桩体系发现。同时,pyproject.toml 还声明了 instruments = ["llama-index"] 与 llamaparse = ["llama-parse"] 两组可选依赖,分别对应 LlamaIndex 本体与 LlamaParse 文档解析插桩。

二、安装

README 给出的安装方式:

pip install opentelemetry-instrumentation-llamaindex

如果使用 LlamaParse 插桩,需要同时安装可选的 llamaparse 依赖组:

pip install "opentelemetry-instrumentation-llamaindex[llamaparse]"

安装完成后,库会暴露 opentelemetry.instrumentation.llamaindex.LlamaIndexInstrumentor,同时通过入口点注册,便于与 traceloop-sdk 或 OpenTelemetry 自动插桩联动。

三、快速接入:三行代码开启追踪

README 的最小示例非常简单:

from opentelemetry.instrumentation.llamaindex import LlamaIndexInstrumentor

LlamaIndexInstrumentor().instrument()

不过要让 span 真正被导出,还需要一个 OpenTelemetry SDK 侧配置(配置 TracerProvider 与 SpanProcessor)。一个可直接运行的完整示例:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.llamaindex import LlamaIndexInstrumentor

# 1. 配置 TracerProvider 与导出器
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")))
trace.set_tracer_provider(provider)

# 2. 插桩 LlamaIndex
LlamaIndexInstrumentor().instrument(tracer_provider=provider)

# 3. 正常编写 LlamaIndex 代码即可,调用会被自动追踪

仓库的测试配置印证了这一接入方式:tests/conftest.py 中,TracerProvider 挂载 SimpleSpanProcessor(InMemorySpanExporter),随后 LlamaIndexInstrumentor().instrument(tracer_provider=tracer_provider) 完成插桩;而 sample-app 的 llama_index_chroma_app.py 展示了在 traceloop-sdk 场景下的用法——Traceloop.init(app_name="llama_index_example") 会自动完成插桩,随后直接构建 VectorStoreIndex、as_query_engine() 并查询即可。

四、工作原理:双轨插桩架构

LlamaIndexInstrumentor 内部并非单一插桩器,而是同时持有"legacy(完整包)"与"core(核心包)"两个子插桩器,这是从 init.py 的源码结构可以明确看到的:

  • LlamaIndexInstrumentorFull:针对 llama-index >= 0.7.0(完整包)的插桩器;
  • LlamaIndexInstrumentorCore:针对 llama-index-core >= 0.7.0(仅核心包,未安装完整框架时)的插桩器。

_instrument() 会先尝试 legacy 插桩,若依赖冲突检测失败(说明用户环境只有 llama-index-core),再回退到 core 插桩。test_instrumentation.py(见 tests/test_instrumentation.py)分别用两条测试路径验证了这一逻辑:完整安装时 legacy.is_instrumented_by_opentelemetry 为 True,monkeypatch 掉 llama-index 后则 core.is_instrumented_by_opentelemetry 为 True。这种"双轨"设计保证了同一份代码同时兼容 LlamaIndex 0.7+ 的各类版本布局。

4.1 两条插桩路径:事件驱动 vs 方法包装

真正执行插桩的核心是 apply_instrumentation(init.py),它会根据 llama-index-core 的版本走两条完全不同的路线:

  • 版本 >= 0.10.20:事件驱动(dispatcher)模式。调用 instrument_with_dispatcher(tracer)(见 dispatcher_wrapper.py),向 LlamaIndex 的全局 get_dispatcher() 注册 OpenLLMetrySpanHandler 与 OpenLLMetryEventHandler,通过 LlamaIndex 自有的插桩事件系统(LLMChatStartEvent、LLMChatEndEvent、EmbeddingStartEvent、ReRankStartEvent、AgentToolCallEvent 等)创建/更新 span。这种方式能感知 LlamaIndex 工作流的真实父子关系,并支持流式响应(StreamingResponse 会等待流结束事件才关闭 span)。
  • 版本 < 0.10.20:方法包装(wrapt)模式。逐个实例化 RetrieverQueryEngineInstrumentor、BaseRetrieverInstrumentor、BaseSynthesizerInstrumentor、BaseEmbeddingInstrumentor、CustomLLMInstrumentor、QueryPipelineInstrumentor、BaseAgentInstrumentor、BaseToolInstrumentor,用 wrapt.wrap_function_wrapper 包装关键类的方法(如 BaseRetriever.retrieve/aretrieve、BaseSynthesizer.synthesize/asynthesize、BaseEmbedding.get_query_embedding/aget_query_embedding、QueryPipeline.run/arun、AgentRunner.chat/achat、FunctionTool.call/acall 等),每个包装器负责开启/关闭 span。

无论哪条路径,LlamaParseInstrumentor 都会被尝试加载;源码注释明确指出"LlamaParse instrumentation doesn't work for all versions",因此用 try/except 静默保护(init.py)。

4.2 与既有 LLM 插桩的协作

事件驱动模式还处理了与 openllmetry 其他插桩包的协作问题:dispatcher_wrapper.py 中定义了 AVAILABLE_OPENLLMETRY_INSTRUMENTATIONS = <a href="https://link.gitcode.com/i/c06f117966aee0693d51be5cf974e70d" target="_blank">"OpenAI"]([dispatcher_wrapper.py)。当 LlamaIndex 内部调用 OpenAI 时,LlamaIndex 侧不再重复创建 span,而是把 SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY 置为 False,交由 opentelemetry-instrumentation-openai 的插桩生成更精确的 openai.chat span。test_agents.py 中 test_agents_and_tools 断言了 openai.chat 与 ReActAgent.workflow、FunctionTool.task 同时存在且层级关系正确(tests/test_agents.py),这正是该协作机制的可验证证据。

五、追踪能力边界:哪些调用会被记录

结合各插桩器的源码,可以系统整理出被追踪的完整对象清单:

组件类型 追踪对象 span 命名 源码位置
Agent AgentRunner、OpenAIAssistantAgent 的 chat/achat {ClassName}.agent base_agent_instrumentor.py
Retriever BaseRetriever.retrieve/aretrieve retrieve.task base_retriever_instrumentor.py
Synthesizer BaseSynthesizer.synthesize/asynthesize synthesize.task base_synthesizer_instrumentor.py
Embedding BaseEmbedding.get_query_embedding/aget_query_embedding get_query_embedding.task base_embedding_instrumentor.py
自定义 LLM 所有继承 CustomLLM 的类的 complete/acomplete/chat/achat {snake_case_class_name}.chat/.completion custom_llm_instrumentor.py
Query Pipeline QueryPipeline.run/arun llama_index_query_pipeline.workflow query_pipeline_instrumentor.py
Query Engine RetrieverQueryEngine.query/aquery llama_index_retriever_query.workflow retriever_query_engine_instrumentor.py
Tool FunctionTool、QueryEngineTool 的 call/acall {ClassName}.tool base_tool_instrumentor.py
LlamaParse load_data/aload_data/get_json_result/aget_json/get_images/aget_images/get_charts/aget_charts llamaparse.task llamaparse_instrumentor.py

值得注意的细节:

  • 自定义 LLM 的 CustomLLMInstrumentor 会扫描 llama_index.llms 包下所有模块,动态找出所有 CustomLLM 子类并逐一包装,无需逐个配置(custom_llm_instrumentor.py);
  • 在事件驱动模式下,Agent 工作流的 span 命名遵循 {ClassName}.workflow(根节点)与 {method_name}.task(子节点)规则,例如测试中出现的 ReActAgent.workflow、call_tool.task、FunctionTool.task、TokenTextSplitter.task 等(见 tests/test_agents.py);
  • 每个 span 都会被打上 traceloop.span.kind 与 traceloop.entity.name 两个属性,kind 取值包括 workflow、task、agent、tool(对应 TraceloopSpanKindValues,定义于 opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/init.py)。

六、Span 属性:GenAI 语义约定落地

插桩产出的 LLM span 严格遵循 OpenTelemetry GenAI 语义约定(gen_ai.*),核心属性可以从 span_utils.py 与 custom_llm_instrumentor.py 中逐项确认:

属性 含义 说明
gen_ai.operation.name 操作类型 取值 chat / text_completion / embeddings / rerank
gen_ai.provider.name 实际 LLM 提供商 通过类名映射,如 OpenAI→openai、AzureOpenAI→azure.ai.openai、Anthropic→anthropic、Bedrock→aws.bedrock、Gemini→gcp.gemini、Cohere→cohere 等(映射表见 _response_utils.py);未命中的类名取小写
gen_ai.request.model 请求模型名 从 model_dict.model(或 StructuredLLM 的嵌套 model_dict.llm.model)读取
gen_ai.request.temperature 采样温度 同上;test_structured_llm.py 专门验证了 StructuredLLM 场景下 model 与 temperature 仍能正确写入(tests/test_structured_llm.py)
gen_ai.request.max_tokens 最大输出 token 来自 instance.metadata.num_output
gen_ai.input.messages 输入消息 JSON 数组,格式 [{"role": ..., "parts": [{"type": "text", "content": ...}]}],含 tool_call 部分
gen_ai.output.messages 输出消息 JSON 数组,含 finish_reason 字段
gen_ai.response.model / gen_ai.response.id 响应模型名 / 响应 ID 从原始响应提取
gen_ai.usage.input_tokens / output_tokens / total_tokens token 用量 兼容 OpenAI(prompt/completion_tokens)、Anthropic(input/output_tokens)、Cohere(meta.tokens/billed_units)三种原始格式( _response_utils.py)
gen_ai.usage.cache_read_input_tokens / cache_creation_input_tokens 缓存 token 用量 支持 prompt caching 场景
gen_ai.response.finish_reasons 结束原因数组 统一映射为 OTel 枚举:stop / tool_call / length / content_filter / error
tool.name / tool.description / tool.arguments 工具调用信息 事件驱动模式下写入 call_tool.task span

输入/输出消息并非简单原样记录,而是经过 _message_utils.py 的规范化:文本内容转为 {"type": "text", "content": ...} parts,图片以 uri/blob part 表示,assistant 消息会附带 tool_call parts,tool 角色消息在携带 tool_call_id 时包装为 tool_call_response。test_message_utils.py 与 test_semconv_migration.py 分别对这些纯函数与 span 写入逻辑做了单元级验证。

结束原因(finish_reason)的映射值得一提:不同厂商的原始取值差异很大(OpenAI 的 tool_calls、Cohere 的 COMPLETE/MAX_TOKENS/ERROR_TOXIC、Anthropic 的 end_turn/stop_sequence/tool_use、Gemini 的 STOP/SAFETY/RECITATION 等),插桩会统一映射到 OTel 规范枚举(_message_utils.py)。并且从源码注释可以确认一个关键设计:finish_reasons 属于元数据而非内容,不受 TRACELOOP_TRACE_CONTENT 开关控制,即使关闭内容采集,它仍然会被写入 span(span_utils.py)。

此外,utils.py 还实现了一个增强版 JSONEncoder,能够序列化 dataclass、Pydantic v2(model_dump)、Pydantic v1(dict)以及暴露 .json() 的对象,且不会二次编码(utils.py),确保 span 上输入/输出属性的 JSON 序列化稳定可靠。

七、隐私控制:TRACELOOP_TRACE_CONTENT 详解

这是 README 中重点强调的章节。插桩默认会将 prompts、completions 与 embeddings 写入 span 属性,带来清晰的运行可见性,便于调试与质量评估;但这些内容可能包含用户的敏感数据,也会显著增大 trace 体积。因此 README 给出的关闭方式为设置环境变量:

TRACELOOP_TRACE_CONTENT=false

从源码看,这个开关的判定逻辑在 utils.py:

def should_send_prompts():
    return (
        os.getenv(TRACELOOP_TRACE_CONTENT) or "true"
    ).lower() == "true" or context_api.get_value("override_enable_content_tracing")

由此可以提炼出几个准确的行为细节:

  1. 默认值为 true:未设置环境变量时按 "true" 处理,即默认采集内容;
  2. 大小写不敏感:"False"、"FALSE" 等都会在 .lower() 后被正确识别为关闭;测试中正是用 TRACELOOP_TRACE_CONTENT: "True" / "False" 两种写法构造开关(tests/conftest.py);
  3. 支持上下文级覆盖:若 OpenTelemetry context 中存在 override_enable_content_tracing 值,则优先级更高(取 or 关系),这为按请求粒度动态开关内容采集提供了钩子;
  4. 开关的生效范围:should_send_prompts() 门控的是 gen_ai.input.messages、gen_ai.output.messages、traceloop.entity.input / traceloop.entity.output 等内容类属性(span_utils.py、utils.py),而模型名、token 用量、finish_reasons 等元数据属性始终写入;
  5. trace 体积控制:即使开启内容采集,dispatcher_wrapper.py 也会在序列化结果时剔除 source_nodes 等可能异常庞大的键(dispatcher_wrapper.py)。

7.1 更精细的两种输出模式

should_emit_events()(utils.py)揭示了第二个配置维度:当 Config.use_legacy_attributes=False 且配置了 event_logger 时,插桩不再把消息写进 span 属性,而是通过 OpenTelemetry Logs API 发出结构化事件(gen_ai.user.message、gen_ai.assistant.message、gen_ai.choice 等,见 event_emitter.py)。LlamaIndexInstrumentor 的构造函数接受 use_legacy_attributes 参数(默认 True),该参数会同步到 Config.use_legacy_attributes(init.py)。事件模式下 TRACELOOP_TRACE_CONTENT=false 同样生效——event_emitter.py 中 _emit_message_event 会删除 body 中的 content 与 tool_calls 参数,仅保留事件骨架(event_emitter.py)。

两种模式的选择建议:

  • 默认(use_legacy_attributes=True):消息内容写入 span 属性,数据结构简单,与绝大多数 OpenTelemetry 后端/UI 兼容性最好,适合大多数场景;
  • 事件模式(use_legacy_attributes=False + LoggerProvider):消息以日志事件形式独立导出,与 span 解耦,便于单独对消息流做检索、审计或后处理。

八、如何验证插桩是否生效

仓库提供了完整的测试体系,可以作为接入自检的参考。基于 tests/conftest.py 的 fixture 设计,验证思路是:

  1. 用 InMemorySpanExporter 挂到 TracerProvider,插桩后执行 LlamaIndex 调用;
  2. 检查 span_exporter.get_finished_spans() 中是否出现预期 span 名称与属性。

关键断言示例(摘自 tests/test_agents.py):

  • Agent 场景应同时出现 ReActAgent.workflow(根,无 parent)、FunctionTool.task、openai.chat;
  • LLM span 应携带 gen_ai.operation.name=chat、gen_ai.request.model、gen_ai.input.messages(含原始提问)、gen_ai.usage.input_tokens/output_tokens/total_tokens 等;
  • call_tool.task span 上应有 tool.name 与 tool.arguments(JSON 字符串);
  • 事件模式关闭时(默认 legacy 属性),log_exporter.get_finished_logs() 应为空。

此外,tests/test_instrumentation.py 验证了双轨插桩的正确回退,tests/test_llamaparse.py 验证了 llamaparse.task span 的产生,tests/test_json_encoder.py 与 tests/test_none_content_fix.py 则覆盖了序列化与空内容等边界情况。这些测试文件同时是了解各功能细节的最佳阅读材料。

九、注意事项与适用前提

  • 版本前提:插桩器要求 llama-index-core >= 0.7.0;事件驱动模式需要 >= 0.10.20,更早版本会退化为方法包装模式。两种模式下 span 命名存在差异(如 Agent 在旧模式下为 ReActAgent.agent,新模式下为 ReActAgent.workflow),升级 LlamaIndex 后 span 名可能变化,查询时需注意;
  • LLM 底层插桩协作:当 LlamaIndex 底层使用 OpenAI 时,建议同时安装 opentelemetry-instrumentation-openai(测试环境中即如此组合),以获得最精确的 openai.chat span;其他提供商(如 Cohere,见 tests/test_agents.py 中的 Cohere.task span)则由本插桩器直接产出;
  • LlamaParse 插桩依赖可选依赖组 llamaparse,且受版本影响,缺失或失败时会被静默跳过,不影响主链路;
  • 隐私开关默认关闭内容采集的写法为 TRACELOOP_TRACE_CONTENT=false(大小写不敏感),它只影响内容类属性,元数据(模型、token 用量、finish reason)始终保留;如需按请求粒度覆盖,可通过 OpenTelemetry context 的 override_enable_content_tracing 实现。

结语

opentelemetry-instrumentation-llamaindex 以极低的接入成本(一次 instrument() 调用),将 LlamaIndex RAG/Agent 应用的全链路(LLM、Embedding、Retriever、Synthesizer、Agent、Tool、Query Pipeline、LlamaParse)映射为符合 OpenTelemetry GenAI 语义约定的结构化 span,同时通过 TRACELOOP_TRACE_CONTENT 与双输出模式提供了从"全量内容可见"到"仅元数据"的隐私弹性。无论是排查一次检索质量下降、量化 token 成本,还是审计用户敏感信息,它都是 LlamaIndex 应用可观测性建设的第一块基石。

登录后查看全文
openllmetry