
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/haystackHaystack 通过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核心类包括类所属模块作用DatadogConnectorhaystack_integrations.components.connectors.datadog.datadog_connector以 Pipeline 组件形式启用 Datadog 追踪DatadogTracerhaystack_integrations.tracing.datadog.tracer直接注入全局 Tracer 的追踪后端实现DatadogSpanhaystack_integrations.tracing.datadog.tracer对ddtrace原生 span 的封装前置条件与安装安装依赖在 Python 环境中安装集成包pip install datadog-haystack前置条件一个可接收 trace 的 Datadog Agentddtrace默认将 trace 发送到localhost:8126因此需要先运行 Datadog Agent。配置ddtrace通过标准的ddtrace配置机制完成例如设置DD_SERVICE、DD_ENV、DD_VERSION环境变量或使用ddtrace-run命令启动应用。具体细节参见 ddtrace 官方文档。启用内容追踪设置HAYSTACK_CONTENT_TRACING_ENABLEDtrue用于追踪组件输入与输出。关键环境变量环境变量取值作用HAYSTACK_CONTENT_TRACING_ENABLEDtrue/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(modelgpt-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并将其与追踪器一起加入 Pipelineimport 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, fWeather 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 fError: Unknown operation {operation} return fThe result of {a} {operation} {b} is {result} # Create the chat generator chat_generator OpenAIChatGenerator() # Create the agent with tools agent Agent( chat_generatorchat_generator, tools[get_weather, calculate], system_promptYou 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( Whats 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场景的落点。DatadogSpanDatadogSpan是 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 打通。DatadogTracerDatadogTracer是 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.pySpan抽象基类表示一次被插桩的操作核心方法为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_ENABLEDtrue在自定义 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_ENABLEDtrue二选一接入在 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),仅供参考