Haystack 与 Datadog 集成指南:用 DatadogConnector 与 DatadogTracer 实现 LLM 流水线全链路追踪
【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack
Haystack 通过datadog-haystack集成包接入 Datadog 的ddtrace追踪库,可在 Pipeline 运行过程中采集 API 调用、上下文数据、提示词等详细信息,并将完整执行链路发送到 Datadog 平台进行可视化分析。本文基于 Datadog 集成 API 参考文档 与 Datadog 使用指南,系统讲解两种接入方式(DatadogConnector组件与DatadogTracer直接启用)、完整配置步骤、核心 API 签名,并结合 核心追踪接口源码 与 标签值序列化工具 深入剖析其底层实现原理,帮助你快速将 RAG、Agent 等流水线的可观测性接入 Datadog。
集成概览:DatadogConnector 能做什么
DatadogConnector将 Haystack 的追踪能力接入 Datadog 平台,底层通过 Datadog 官方追踪库ddtrace完成 span 的创建与上报。它能够捕获流水线运行的详细信息,包括:
- API 调用(如 LLM 生成器的外部请求)
- 上下文数据(检索到的文档、传入的查询)
- 提示词(prompt 与补全结果 completion)
- 组件间流转的元数据
接入后,你可以在 Datadog 仪表盘中查看每次 Pipeline 运行的完整 trace。根据 datadogconnector 组件文档 的说明,其最典型的放置位置是流水线中任意不与其他组件相连的位置,初始化时即建立与 Datadog 后端的连接,无需连接任何组件即可生效。
该集成对应的 Python 包名为datadog-haystack,核心类包括:
| 类 | 所属模块 | 作用 |
|---|---|---|
DatadogConnector | haystack_integrations.components.connectors.datadog.datadog_connector | 以 Pipeline 组件形式启用 Datadog 追踪 |
DatadogTracer | haystack_integrations.tracing.datadog.tracer | 直接注入全局 Tracer 的追踪后端实现 |
DatadogSpan | haystack_integrations.tracing.datadog.tracer | 对ddtrace原生 span 的封装 |
前置条件与安装
安装依赖
在 Python 环境中安装集成包:
pip install datadog-haystack前置条件
- 一个可接收 trace 的 Datadog Agent:
ddtrace默认将 trace 发送到localhost:8126,因此需要先运行 Datadog Agent。 - 配置
ddtrace:通过标准的ddtrace配置机制完成,例如设置DD_SERVICE、DD_ENV、DD_VERSION环境变量,或使用ddtrace-run命令启动应用。具体细节参见 ddtrace 官方文档。 - 启用内容追踪:设置
HAYSTACK_CONTENT_TRACING_ENABLED=true,用于追踪组件输入与输出。
关键环境变量
| 环境变量 | 取值 | 作用 |
|---|---|---|
HAYSTACK_CONTENT_TRACING_ENABLED | "true"/"false"(默认) | 控制是否追踪组件输入输出等敏感内容(查询、文档、答案) |
DD_SERVICE | 字符串 | 标识服务名 |
DD_ENV | 字符串 | 标识部署环境 |
DD_VERSION | 字符串 | 标识服务版本 |
重要提示:
HAYSTACK_CONTENT_TRACING_ENABLED必须在导入任何 Haystack 组件之前设置。这是因为 Haystack 在导入阶段就会初始化内部的追踪组件。更推荐的做法是在 shell 中、运行脚本之前设置这些环境变量,将配置与代码分离,便于管理不同环境。
方式一:使用 DatadogConnector 组件
如果你希望把追踪作为流水线定义的一部分来管理(例如随流水线一起序列化为 YAML),可以将DatadogConnector作为一个普通组件加入 Pipeline。它在初始化时即启用 Datadog 追踪,无需连接、无需运行即可生效。
import os os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true" from haystack import Pipeline from haystack.components.builders import ChatPromptBuilder from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack_integrations.components.connectors.datadog import DatadogConnector pipe = Pipeline() pipe.add_component("tracer", DatadogConnector("Chat example")) pipe.add_component("prompt_builder", ChatPromptBuilder()) pipe.add_component("llm", OpenAIChatGenerator(model="gpt-4o-mini")) pipe.connect("prompt_builder.prompt", "llm.messages") messages = [ ChatMessage.from_system("Always respond in German even if some input data is in other languages."), ChatMessage.from_user("Tell me about {{location}}"), ] response = pipe.run( data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}} ) print(response["llm"]["replies"][0])上述示例中,DatadogConnector("Chat example")传入的名称会作为该追踪组件的标识,由run方法返回,可用于标记该连接器产生的 trace。每次pipe.run(...)都会生成一条包含整个执行上下文的 trace,随后即可在 Datadog 仪表盘查看。
在 Agent 流水线中使用
DatadogConnector同样适用于 Agent 场景。下面示例构建了一个带天气查询与计算工具的 Agent,并将其与追踪器一起加入 Pipeline:
import os os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true" from typing import Annotated from haystack.components.agents import Agent from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack.tools import tool from haystack import Pipeline from haystack_integrations.components.connectors.datadog import DatadogConnector @tool def get_weather(city: Annotated[str, "The city to get weather for"]) -> str: """Get current weather information for a city.""" weather_data = { "Berlin": "18°C, partly cloudy", "New York": "22°C, sunny", "Tokyo": "25°C, clear skies", } return weather_data.get(city, f"Weather information for {city} not available") @tool def calculate( operation: Annotated[ str, "Mathematical operation: add, subtract, multiply, divide", ], a: Annotated[float, "First number"], b: Annotated[float, "Second number"], ) -> str: """Perform basic mathematical calculations.""" if operation == "add": result = a + b elif operation == "subtract": result = a - b elif operation == "multiply": result = a * b elif operation == "divide": if b == 0: return "Error: Division by zero" result = a / b else: return f"Error: Unknown operation '{operation}'" return f"The result of {a} {operation} {b} is {result}" # Create the chat generator chat_generator = OpenAIChatGenerator() # Create the agent with tools agent = Agent( chat_generator=chat_generator, tools=[get_weather, calculate], system_prompt="You are a helpful assistant with access to weather and calculator tools. Use them when needed.", exit_conditions=["text"], ) # Create the DatadogConnector for tracing datadog_connector = DatadogConnector("Agent Example") # Build the pipeline pipe = Pipeline() pipe.add_component("tracer", datadog_connector) pipe.add_component("agent", agent) # Run the pipeline response = pipe.run( data={ "agent": { "messages": [ ChatMessage.from_user( "What's the weather in Berlin and calculate 15 + 27?", ), ], }, "tracer": {}, }, ) # Display results print("Agent Response:") print(response["agent"]["last_message"].text)Agent 的每次工具调用、推理与回复过程都会被纳入 trace,便于观察多轮工具调用的完整链路与耗时分布。
方式二:直接配置 DatadogTracer 后端
如果你更倾向于在代码层面直接控制追踪后端(例如不希望在流水线定义中出现额外的组件),可以直接启用DatadogTracer,它同样能追踪任意 Haystack 流水线:
import ddtrace from haystack import tracing from haystack_integrations.tracing.datadog import DatadogTracer tracing.enable_tracing(DatadogTracer(ddtrace.tracer))调用tracing.enable_tracing(...)后,全局追踪实例即被替换为 Datadog 实现,此后所有 Pipeline 与组件的运行都会自动产生 span。完整用法示例如下(同样要求先设置内容追踪环境变量再导入组件):
import os os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true" import ddtrace from haystack import Pipeline, tracing from haystack.components.builders import ChatPromptBuilder from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack_integrations.tracing.datadog import DatadogTracer # Enable the Datadog tracer tracing.enable_tracing(DatadogTracer(ddtrace.tracer)) pipe = Pipeline() pipe.add_component("prompt_builder", ChatPromptBuilder()) pipe.add_component("llm", OpenAIChatGenerator()) pipe.connect("prompt_builder.prompt", "llm.messages") messages = [ ChatMessage.from_system( "Always respond in German even if some input data is in other languages.", ), ChatMessage.from_user("Tell me about {{location}}"), ] response = pipe.run( data={ "prompt_builder": { "template_variables": {"location": "Berlin"}, "template": messages, }, }, ) print(response["llm"]["replies"][0])核心 API 参考
DatadogConnector
__init__(name: str = 'datadog') -> None
初始化DatadogConnector组件。
参数:
- name(
str):用于标识该追踪组件的名称,由run方法返回,可用于标记此连接器产生的 trace。默认值为"datadog"。
run() -> dict[str, str]
运行DatadogConnector组件。
返回:
dict[str, str]:包含以下键的字典:name:追踪组件的名称。
to_dict() -> dict[str, Any]
将组件序列化为字典,便于 YAML/JSON 形式的流水线持久化。
返回:
dict[str, Any]:序列化后的组件字典。
from_dict(data: dict[str, Any]) -> DatadogConnector
从字典反序列化组件实例。
参数:
- data(
dict[str, Any]):组件的字典表示。
返回:
DatadogConnector:反序列化得到的组件实例。
从源码结构看,
to_dict/from_dict的存在意味着DatadogConnector遵循 Haystack 组件标准的序列化协议,可以将组件定义写入 YAML 流水线并完整还原,这正是文档中"随流水线序列化到 YAML"场景的落点。
DatadogSpan
DatadogSpan是 Haystack 抽象基类Span的 Datadog 实现,对ddtrace的原生 span 对象做了一层封装。Span接口定义位于 haystack/tracing/tracer.py,包含set_tag、set_tags、raw_span、set_content_tag、get_correlation_data_for_logs等能力。
__init__(span: ddSpan) -> None
创建DatadogSpan实例,包装一个ddtrace的原生 span 对象。
set_tag(key: str, value: Any) -> None
在 span 上设置单个标签。
参数:
- key(
str):标签名。 - value(
Any):标签值。
注意:根据 Span.set_tag 的接口约定,标签值会被序列化为字符串,因此建议使用字符串、数字、布尔值等简单类型。
raw_span() -> Any
提供对底层 span 对象的直接访问,便于需要完全操作底层对象时使用。
返回:
Any:底层 span 对象。
get_correlation_data_for_logs() -> dict[str, Any]
返回用于日志与 trace 关联的字典。根据 发布说明 dd-correlation-data,该实现使用了官方ddtrace.tracer.get_log_correlation_context()方法,从而获得标准的 Datadog 日志-追踪关联上下文,方便将应用日志与对应 trace 打通。
DatadogTracer
DatadogTracer是 Haystack 抽象基类Tracer的 Datadog 实现。Tracer接口同样定义在 haystack/tracing/tracer.py,要求实现trace(上下文管理器)与current_span两个方法。
__init__(tracer: ddTracer) -> None
创建DatadogTracer实例,通常传入全局的ddtrace.tracer。
trace(operation_name: str, tags: dict[str, Any] | None = None, parent_span: Span | None = None) -> Iterator[Span]
激活并返回一个新的 span,该 span 会继承当前激活的 span(作为其子 span)。
参数:
- operation_name(
str):被追踪操作的名称。 - tags(
dict[str, Any] | None):应用到新 span 上的标签。 - parent_span(
Span | None):父 span;若为None,新 span 将成为根 span。
current_span() -> Span | None
返回当前激活的 span;若没有激活的 span 则返回None。
底层实现原理:Haystack 追踪架构
要理解 Datadog 集成的工作方式,需要先了解 Haystack 核心的追踪抽象。全局追踪实例定义在 haystack/tracing/tracer.py:
Span(抽象基类):表示一次被插桩的操作,核心方法为set_tag/set_tags,以及默认不生效、由内容追踪开关控制的内容标签方法set_content_tag。Tracer(抽象基类):负责创建与提交 span,核心方法为trace(上下文管理器)与current_span。ProxyTracer:全局追踪实例的代理容器,其构造时通过os.getenv("HAYSTACK_CONTENT_TRACING_ENABLED", "false").lower() == "true"解析内容追踪开关(见 tracer.py),这正是"必须在使用前设置环境变量"这一约束的根源。NullTracer/NullSpan:追踪禁用时的 no-op 实现。enable_tracing(provided_tracer)/disable_tracing()/is_tracing_enabled():全局开关函数,DatadogTracer正是通过enable_tracing注入全局实例。
当传入DatadogTracer(ddtrace.tracer)后,Pipeline 运行时创建的每个 span 都会经ProxyTracer.trace委托到DatadogTracer.trace,最终落到ddtrace的原生 span 上,由ddtrace上报到 Datadog Agent(默认localhost:8126)。
内容追踪的开关机制
Span.set_content_tag(见 tracer.py)默认是"静默"的:只有当全局追踪实例的内容追踪被启用时,内容标签(如查询内容、文档内容、答案内容)才会真正写入 span。启用途径有两个:
- 设置环境变量
HAYSTACK_CONTENT_TRACING_ENABLED=true; - 在自定义 Tracer 实现中覆写
set_content_tag。
这解释了参考文档中反复强调的环境变量要求:不开启该开关,组件输入输出的内容信息不会被追踪。
标签值的类型收敛
追踪后端(包括 Datadog)通常不支持发送复杂类型,因此 Haystack 在 haystack/tracing/utils.py 提供了coerce_tag_value函数:基本类型(bool、str、int、float)原样保留;None转为空字符串;复杂对象先尝试递归序列化(列表、字典、含to_dict或_to_trace_dict的对象),再以 JSON 字符串形式作为标签值;序列化失败时兜底使用str(value)。这一机制保证了文档、消息、流式块等丰富类型也能以可读形式出现在 Datadog 的 span 标签中。
相关演进记录
从 发布说明目录 可以看到该集成持续演进的关键节点:
- datadog-tracer-b084cf64fcc575c6.yaml:引入开箱即用的 Datadog Tracer 支持,可使用
ddtrace-run命令行自动插桩(可通过HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR关闭),也可在代码中手动enable_tracing。 - update-datadog-tracing-for-ddtrace-3-2f3705af917e3260.yaml:更新类型提示的导入路径以兼容
ddtrace3.0.0。 - dd-correlation-data-bb9c9e537c351fa8.yaml:使用官方
get_log_correlation_context()改进日志与 trace 的关联。 - set-component-name-as-datadog-span-resource-name-bdec739077ca20ce.yaml:组件级 span 的 resource name 由操作名改为组件名,使 Datadog 中的 span 聚合与检索更直观。
- fix-auto-tracing-51ed3a590000d6c8.yaml:修复当环境中安装了
ddtrace或opentelemetry时自动启用追踪的行为。
总结与最佳实践
将 Haystack 流水线接入 Datadog 的完整路径可以归纳为三步:
- 启动 Datadog Agent(默认监听
localhost:8126),并通过DD_SERVICE、DD_ENV、DD_VERSION或ddtrace-run配置ddtrace; - 在导入任何 Haystack 组件之前设置
HAYSTACK_CONTENT_TRACING_ENABLED=true; - 二选一接入:在 Pipeline 中加入
DatadogConnector("your_name")(适合随 YAML 序列化的声明式管理),或在代码入口调用tracing.enable_tracing(DatadogTracer(ddtrace.tracer))(适合纯代码控制)。
接入后,每次 Pipeline 运行都会生成包含提示词、补全结果、上下文与元数据的完整 trace。如需继续深入,可进一步阅读 Haystack 追踪使用指南、DatadogConnector 组件文档 以及 Datadog 集成 API 参考,或直接查看核心追踪抽象源码 haystack/tracing/tracer.py 与标签序列化工具 haystack/tracing/utils.py。
【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考