尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

MLflow Tracing 轻量级 SDK 实战:在生产环境中为 LLM 应用与 AI Agent 构建可观测性

MLflow Tracing 轻量级 SDK 实战:在生产环境中为 LLM 应用与 AI Agent 构建可观测性 MLflow Tracing 轻量级 SDK 实战在生产环境中为 LLM 应用与 AI Agent 构建可观测性【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflowMLflow Tracingmlflow-tracing是 MLflow 官方推出的轻量级 Python 包只保留仪表化代码/模型/Agent 所需的最小依赖与最小功能集专为 Docker 容器、Serverless 函数、云原生应用等对部署体积敏感的生产环境设计。本文以仓库 libs/tracing/README.md 为主线结合仓库内 mlflow/tracing 源码与 examples/tracing 示例系统讲解mlflow-tracing的安装、后端选型、自动/手动仪表化、生产配置与迁移路径帮助你用最少的依赖为 GenAI 应用补齐全链路可观测性。什么是 MLflow Tracing SDKMLflow Tracing 基于OpenTelemetryOTel追踪规范构建见 docs/docs/genai/tracing/lightweight-sdk.mdx是一套用于 LLM 应用与 AI Agent 的开放、厂商中立的观测能力。mlflow-tracing是它的独立可安装发行包其定位并非“MLflow 的裁剪版”而是一个面向生产观测场景的专用 SDK更快的部署包体积与依赖数显著小于完整版mlflow在 Docker、Serverless、云平台等动态环境中启动更快简化的依赖管理依赖集更小意味着维护依赖升级、安全补丁、上游破坏性变更的工作量更少更强的可移植性依赖越少跨环境、跨平台部署时越不容易出现兼容性问题更小的攻击面每个依赖都可能是潜在漏洞来源减少依赖即降低安全风险。从 libs/tracing/pyproject.toml 可以看到该包运行时依赖仅有 8 个cachetools、databricks-sdk、opentelemetry-api/proto/sdk三个、packaging、protobuf、pydantic全部是观测链路与配置解析所需的底层库不含任何机器学习框架依赖。包本身要求 Python3.10许可证为 Apache-2.0。包内包含的功能mlflow-tracing完整继承mlflow.tracing模块libs/tracing/pyproject.toml 的包发现规则中包含mlflow.tracing*等模块并附带实现以下能力自动追踪Automatic Tracing对 OpenAI、LangChain、DSPy、Anthropic、LlamaIndex、Bedrock、CrewAI、Haystack、Mistral、SmolAgents 等主流 AI 库一行开启mlflow.lib.autolog()手动仪表化 APImlflow.trace装饰器、mlflow.start_span上下文管理器等生产级监控异步导出、采样mlflow/tracing/sampling.py、OTLP 导出等其他追踪 APImlflow.set_trace_tag、mlflow.search_traces、mlflow.get_trace等。从 mlflow/tracing/init.py 可以看到该模块对外暴露了configure、enable/disable、set_destination、reset、分布式追踪上下文透传get_tracing_context_headers_for_http_request等一系列高级 API说明 SDK 并不仅限于本地埋点还支持分布式场景。不包含的功能请明确mlflow-tracing不包含以下 MLflow 能力libs/tracing/README.mdMLflow 追踪服务器与 UIRuns、Model Registry、Projects 等追踪以外的 MLflow 能力模型/Agent 评估与评估结果记录。如需完整功能集应安装完整包pip install mlflow。安装与依赖策略通过 pip 安装pip install mlflow-tracing从源码安装pip install githttps://github.com/mlflow/mlflow.git#subdirectorylibs/tracing⚠️ 重要警告不要将mlflow-tracing与完整mlflow包共存安装否则可能引发版本不匹配与命名空间解析问题docs/docs/genai/tracing/lightweight-sdk.mdx 中的安装警告与 README 的 NOTE 一致。从仓库结构看mlflow-tracing是 monorepo 中的一个独立子项目libs/tracing其pyproject.toml由 dev/pyproject.py 自动生成、不可手改libs/tracing/setup.py 仅在构建期校验mlflow源码目录是否存在该目录是仓库根目录mlflow包的符号链接防止在 Windows 上因符号链接未物化而构建出“空 wheel”。这一细节说明追踪 SDK 的代码与完整 MLflow 的 tracing 模块是同源的安装mlflow-tracing得到的就是一份按需精简的 tracing 实现。选择你的追踪后端mlflow-tracing的设计是配合远程托管的 MLflow 服务器作为后端把 trace 集中写入一处便于统一管理与分析。官方提供了四种托管方式后端说明适用场景Databricks平台内置免费的完全托管 MLflow 服务器无需搭建任何基础设施想最快上手、不想运维Amazon SageMakerAWS 提供的完全托管 MLflow含 tracing 与 Model RegistryAWS 生态内使用、结合 Amazon Bedrock 追踪NebiusGenAI 云平台提供的完全托管 MLflow 服务器在 Nebius GPU 基础设施上训练/托管模型自托管Self-hostingMLflow 是开源项目可自行部署服务器、数据完全私有对数据与基础设施有完全控制权诉求其中自托管是最常用的生产方案docs/docs/genai/tracing/lightweight-sdk.mdx 给出了推荐的搭建步骤安装服务器pip install mlflow[extras]配置后端存储推荐 PostgreSQL/MySQL 等 SQL 数据库配置制品存储S3、Azure Blob、GCS 等启动服务mlflow server --backend-store-uri postgresql://... --default-artifact-root s3://...。官方强烈建议在性能良好的数据库之上运行 SQL 跟踪服务器以最小化运维开销并保障高可用。此外由于 MLflow Tracing 基于 OTel 规范你还可以不引入任何新的托管服务直接把 trace 导出到已有的 OTel 可观测平台export OTEL_EXPORTER_OTLP_TRACES_ENDPOINThttp://your-collector:4317/v1/traces export OTEL_SERVICE_NAMEgenai-app快速开始连接服务器并记录第一个 Trace1. 连接 MLflow 服务器通过环境变量MLFLOW_TRACKING_URI或mlflow.set_tracking_uri连接服务器import mlflow mlflow.set_tracking_uri(databricks) # 或 http://your-mlflow-server:5000 mlflow.set_experiment(/Path/To/Experiment) # 指定记录 trace 的实验对自托管场景也可以写作mlflow.set_tracking_uri(http://your-mlflow-server:5000) mlflow.set_experiment(genai-production-monitoring)2. 为 OpenAI 开启自动追踪import openai client openai.OpenAI(api_keyyour-api-key) # 一行开启 OpenAI 自动追踪 mlflow.openai.autolog() # 照常调用 OpenAI API每次调用都会生成 trace response client.chat.completions.create( modelgpt-4.1-mini, messages[{role: user, content: Hello, how are you?}], )自动追踪同样适用于 LangChainmlflow.langchain.autolog()、Anthropicmlflow.anthropic.autolog()、DSPy 等在 examples/tracing/langchain_auto.py 中可以看到完整用法——只需调用一次mlflow.langchain.autolog()之后每次chain.invoke(...)都会生成一条新 trace最后可用mlflow.search_traces(locations[exp_id], max_results3, return_typelist)批量拉回。注意autolog()默认只开启 tracing不会记录模型、数据集等其他制品如需完整 autolog 请参考 examples/langchain/chain_autolog.py。手动仪表化mlflow.trace 与 start_span自动追踪覆盖主流框架但业务自定义逻辑往往需要手动埋点。mlflow-tracing提供了与完整 MLflow 完全一致的仪表化 API可单独使用也可与自动追踪混用。用装饰器追踪函数examples/tracing/fluent.py 演示了最常用的高阶 Fluent APIimport mlflow mlflow.set_experiment(mlflow-tracing-example) # 装饰函数即可自动捕获函数名、入参、出参等 mlflow.trace def f1(x: int) - int: return x 1 # 可指定额外的元数据 mlflow.trace( span_typemath, attributes{operation: addition}, ) def f2(x: int) - int: # MLflow 会维护调用层级f2 内部调用 f1 会形成 f2 下的子 span x f1(x) 2 # 用上下文管理器为任意代码块创建 span with mlflow.start_span(nameleaf, attributes{operation: exponentiation}) as span: # 手动创建的 span 需要显式设置输入与输出 span.set_inputs({x: x}) x x**2 span.set_outputs({x: x}) return x assert f2(1) 16mlflow.trace的参数签名见 mlflow/tracing/fluent.py还支持name、span_type、attributes、output_reducer、trace_destination、sampling_ratio_override、log_level、links、description等参数可对 span 进行细粒度定制sampling_ratio_override允许对单个函数覆盖全局采样率通过 mlflow/tracing/sampling.py 中的_SAMPLING_RATIO_OVERRIDEContextVar 生效。用 Fluent API 读取 Trace# 获取最近一次活动 trace trace_id mlflow.get_last_active_trace_id() trace mlflow.get_trace(trace_id) # 或按条件搜索 traces mlflow.search_traces( filter_stringtimestamp 0, max_results1, ) print(trace.to_json(prettyTrue))search_traces支持类似 SQL 的过滤语法基于执行时间、状态、标签、元数据等属性可用于问题排查与性能分析to_json(prettyTrue)可输出可读的 JSON 结构。用低层 Client API 手工构建 Span 层级对需要精细控制例如手工指定父子关系、在start_trace时附带标签的场景可以使用低层 Client API。examples/tracing/client.py 完整演示了这一过程import mlflow exp mlflow.set_experiment(mlflow-tracing-example) exp_id exp.experiment_id client mlflow.MlflowClient() def run(x: int, y: int) - int: # start_trace 返回 trace 的根 span root_span client.start_trace( namemy_trace, inputs{x: x, y: y}, tags{fruit: apple, vegetable: carrot}, # 之后可用 set_trace_tag 更新 ) z x y trace_id root_span.trace_id # trace 的唯一标识 # 创建根 span 的子 span child_span client.start_span( namechild_span, trace_idtrace_id, parent_idroot_span.span_id, # 指定父 span ID 以构建层级 inputs{z: z}, attributes{model: my_model, temperature: 0.5}, ) z z**2 # 结束子 span务必先结束子 span 再结束根 span client.end_span( trace_idtrace_id, span_idchild_span.span_id, outputsz, statusOK, # 完成状态OK默认、ERROR 等 ) z z 1 client.end_trace(trace_idtrace_id, outputsz) return z assert run(1, 2) 10 # 检索 trace trace_id mlflow.get_last_active_trace_id() trace client.get_trace(trace_id) # 也可以用 search_traces 从服务器拉取 trace client.search_traces(locations[exp_id])[0] # 更新 / 删除标签 client.set_trace_tag(trace.info.trace_id, fruit, orange) client.delete_trace_tag(trace.info.trace_id, vegetable)这段示例覆盖了start_trace/start_span/end_span/end_trace/get_trace/search_traces/set_trace_tag/delete_trace_tag的完整生命周期是理解 MLflow 追踪数据模型Trace → Span 树的最佳入口。多线程场景Fluent API 基于 ContextVar 维护当前 span 上下文不是线程安全的多线程应用需要改用低层 Client API。更精确的做法是使用contextvars.copy_context()配合ctx.run(...)在子线程中运行任务把主线程的追踪上下文显式传递给工作线程——examples/tracing/multithreading.py 给出了可直接套用的ThreadPoolExecutor模式with ThreadPoolExecutor(max_workers2) as executor: futures [] for question in questions: ctx contextvars.copy_context() # 1. 在主线程复制 context futures.append(executor.submit(ctx.run, worker, question)) # 2. 在复制的 context 中运行 results.extend(future.result() for future in as_completed(futures))同时mlflow/tracing/init.py 暴露了get_tracing_context_headers_for_http_request与set_tracing_context_from_http_request_headers说明 SDK 还支持通过 HTTP 请求头把追踪上下文透传到下游服务实现分布式链路追踪。生产环境配置给 Trace 打标签、记录上下文与错误以下是 docs/docs/genai/tracing/lightweight-sdk.mdx 中提供的生产配置完整示例。它展示了如何在真实业务入口处附加生产上下文、记录指标并在异常时记录错误信息import mlflow import os from your_app import process_user_request # 配置 MLflow 生产环境 mlflow.set_tracking_uri(os.getenv(MLFLOW_TRACKING_URI, http://mlflow-server:5000)) mlflow.set_experiment(os.getenv(MLFLOW_EXPERIMENT_NAME, production-genai-app)) # 为 LLM 库开启自动追踪 mlflow.openai.autolog() # 或 mlflow.langchain.autolog() 等 mlflow.trace def handle_user_request(user_id: str, session_id: str, message: str): 带完整追踪的生产入口。 # 向当前 trace 添加生产上下文 mlflow.update_current_trace( tags{ user_id: user_id, session_id: session_id, environment: production, service_version: os.getenv(SERVICE_VERSION, 1.0.0), } ) try: response process_user_request(message) # 记录成功指标 mlflow.update_current_trace( tags{response_length: len(response), processing_successful: True} ) return response except Exception as e: # 记录错误信息 mlflow.update_current_trace( tags{ error: True, error_type: type(e).__name__, error_message: str(e), }, ) raise要点解读标签Tags是 trace 的键值对元数据可以标记用户、会话、环境、服务版本等便于后续用search_traces分组、过滤和检索mlflow.update_current_trace(tags...)可在 trace 生命周期内随时追加/更新标签配合异常处理即可实现错误可视化与告警该示例同时展示了自动追踪autolog与手动仪表化mlflow.trace在同一应用中的混用方式。包体积对比与迁移指南体积与依赖对比包体积依赖数适用场景mlflow~1000MB20 个包开发、实验、完整 AI 开发工作流mlflow-tracing~5MB5–8 个包生产 tracing、监控、可观测性官方说明mlflow-tracing比完整包小约95%非常适合容器部署、Serverless 函数、边缘计算、生产微服务、CI/CD 流水线。从完整 MLflow 迁移第一步更新依赖pip uninstall mlflow # 移除完整 MLflow pip install mlflow-tracing第二步更新导入语句# 以下导入在 mlflow-tracing 中同样可用 import mlflow import mlflow.openai from mlflow.tracing import trace # 以下功能在 mlflow-tracing 中不可用 # import mlflow.sklearn # ❌ 模型记录 # mlflow.start_run() # ❌ Run 管理 # mlflow.log_metric() # ❌ 指标记录第三步更新配置mlflow.set_tracking_uri(http://your-server:5000) mlflow.set_experiment(your-experiment) # 追踪 API 用法不变 mlflow.trace def your_function(): pass迁移时只需关注三点依赖替换、移除模型/Run 管理类导入、把配置收敛到 tracking URI 与实验设置。绝大部分 tracing 代码mlflow.trace、search_traces、标签 API 等可以原样保留。总结mlflow-tracing以最小依赖集8 个运行时依赖、Python 3.10、Apache-2.0完整保留了 MLflow 的追踪能力基于 OpenTelemetry 规范实现、支持主流 AI 框架的一行自动追踪、mlflow.trace与低层 Client API 两种手动仪表化方式、基于标签的检索与生产监控并可自由选择 Databricks / SageMaker / Nebius / 自托管 / OTLP 后端。对于在生产环境中追求轻量部署、快速启动与更低安全风险同时需要 LLM 应用与 Agent 全链路可观测性的团队它是比完整mlflow更贴合场景的选择。进一步的参考资料SDK 说明与安装 libs/tracing/README.md官方生产 SDK 文档 docs/docs/genai/tracing/lightweight-sdk.mdx完整示例Fluent / Client / LangChain 自动追踪 / 多线程 examples/tracing核心实现Fluent API 见 mlflow/tracing/fluent.pyProvider 管理与 OTel 桥接见 mlflow/tracing/provider.py导出/采样/OTLP 见 mlflow/tracing/export 与 mlflow/tracing/sampling.py【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表