当前位置: 首页 > article >正文

AI应用的可观测性工程:用Tracing和Logging看清LLM黑盒

“我的RAG系统回答了一个错误答案但我不知道为什么。” “Agent跑了2分钟什么都没完成我不知道它在做什么。” “用了新版本Prompt感觉质量变了但我说不清楚哪里变了。”这些是AI工程师最常见的困境根本原因是缺乏可观测性Observability。本文系统介绍如何为LLM应用构建完整的可观测性体系让AI系统的行为从黑盒变白盒。## 可观测性的三大支柱借鉴传统软件可观测性的三大支柱LLM应用的可观测性同样需要-Metrics指标定量衡量系统健康的数值如响应时延、Token消耗、成功率-Logs日志记录系统发生的事件包括每次LLM调用的输入输出-Traces追踪记录一次请求的完整执行链路特别是在Agent场景中追踪多步推理在LLM应用中还需要额外关注-Prompt版本追踪哪个版本的Prompt被用于哪次请求-Token使用分析详细的Token消耗分布找出成本热点-质量评估LLM生成质量的自动化指标## LangSmithLangChain生态的可观测性标配如果你的应用基于LangChain/LangGraphLangSmith是最省力的选择pythonimport osfrom langchain_openai import ChatOpenAIfrom langchain.callbacks.tracers import LangChainTracer# 配置LangSmithos.environ[LANGCHAIN_TRACING_V2] trueos.environ[LANGCHAIN_API_KEY] your_langsmith_api_keyos.environ[LANGCHAIN_PROJECT] my-rag-project# 之后所有LangChain调用自动追踪llm ChatOpenAI(modelgpt-4o)response llm.invoke(你好世界)# 这次调用的输入、输出、Token消耗、延迟都会自动记录到LangSmithLangSmith的关键功能- 自动记录每次LLM调用输入、输出、Token、延迟- 完整的Agent执行追踪每个工具调用都有记录- Prompt版本管理Hub- 数据集管理和自动化评估## 自建可观测性OpenTelemetry方案不想依赖第三方服务用OpenTelemetry构建自主可控的可观测性pythonfrom opentelemetry import tracefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporterfrom opentelemetry.sdk.resources import Resourceimport timeimport jsonfrom functools import wraps# 初始化Tracer连接到Jaeger或Grafana Tempo等resource Resource(attributes{service.name: llm-application})provider TracerProvider(resourceresource)exporter OTLPSpanExporter(endpointhttp://localhost:4317)provider.add_span_processor(BatchSpanProcessor(exporter))trace.set_tracer_provider(provider)tracer trace.get_tracer(llm-app-tracer)def trace_llm_call(func): 装饰器自动追踪LLM调用 wraps(func) def wrapper(*args, **kwargs): with tracer.start_as_current_span(fllm.{func.__name__}) as span: start_time time.time() # 记录输入 if kwargs.get(messages): span.set_attribute(llm.input.messages, json.dumps(kwargs[messages][:1], ensure_asciiFalse)) if kwargs.get(model): span.set_attribute(llm.model, kwargs[model]) try: result func(*args, **kwargs) # 记录输出 duration (time.time() - start_time) * 1000 span.set_attribute(llm.latency_ms, duration) if hasattr(result, usage): span.set_attribute(llm.tokens.prompt, result.usage.prompt_tokens) span.set_attribute(llm.tokens.completion, result.usage.completion_tokens) span.set_attribute(llm.tokens.total, result.usage.total_tokens) span.set_status(trace.StatusCode.OK) return result except Exception as e: span.set_status(trace.StatusCode.ERROR, str(e)) span.record_exception(e) raise return wrapper## 结构化日志LLM调用的标准格式pythonimport loggingimport jsonfrom datetime import datetimefrom openai import OpenAI# 配置结构化日志logging.basicConfig(levellogging.INFO)logger logging.getLogger(llm_app)class StructuredLLMLogger: 结构化LLM调用日志记录器 def __init__(self, client: OpenAI, app_name: str llm-app): self.client client self.app_name app_name def chat(self, messages: list[dict], model: str gpt-4o, trace_id: str None, **kwargs) - dict: 带完整日志记录的LLM调用 call_id trace_id or datetime.now().strftime(%Y%m%d_%H%M%S_%f) start_time time.time() # 记录请求 logger.info(json.dumps({ event: llm_request, call_id: call_id, app: self.app_name, model: model, message_count: len(messages), system_prompt_hash: hash(messages[0][content]) if messages[0][role] system else None, last_user_message: messages[-1][content][:200] if messages else , timestamp: datetime.now().isoformat(), }, ensure_asciiFalse)) try: response self.client.chat.completions.create( modelmodel, messagesmessages, **kwargs ) duration_ms (time.time() - start_time) * 1000 # 记录响应 logger.info(json.dumps({ event: llm_response, call_id: call_id, app: self.app_name, model: model, latency_ms: round(duration_ms, 2), prompt_tokens: response.usage.prompt_tokens, completion_tokens: response.usage.completion_tokens, total_tokens: response.usage.total_tokens, finish_reason: response.choices[0].finish_reason, response_preview: response.choices[0].message.content[:200], estimated_cost_usd: self._estimate_cost(model, response.usage), timestamp: datetime.now().isoformat(), }, ensure_asciiFalse)) return response except Exception as e: duration_ms (time.time() - start_time) * 1000 logger.error(json.dumps({ event: llm_error, call_id: call_id, model: model, latency_ms: round(duration_ms, 2), error_type: type(e).__name__, error_message: str(e), timestamp: datetime.now().isoformat(), }, ensure_asciiFalse)) raise def _estimate_cost(self, model: str, usage) - float: 估算API调用成本 pricing { gpt-4o: {input: 0.000005, output: 0.000015}, gpt-4o-mini: {input: 0.00000015, output: 0.0000006}, } model_price pricing.get(model, {input: 0.000005, output: 0.000015}) return (usage.prompt_tokens * model_price[input] usage.completion_tokens * model_price[output])## Agent执行追踪Agent场景的追踪更复杂需要记录整个推理链路pythonfrom dataclasses import dataclass, fieldfrom typing import Anyimport uuiddataclassclass AgentTraceSpan: span_id: str field(default_factorylambda: str(uuid.uuid4())[:8]) parent_id: str None name: str start_time: float field(default_factorytime.time) end_time: float None inputs: dict field(default_factorydict) outputs: dict field(default_factorydict) metadata: dict field(default_factorydict) error: str None children: list field(default_factorylist) def end(self, outputs: dict None, error: str None): self.end_time time.time() if outputs: self.outputs outputs if error: self.error error property def duration_ms(self) - float: if self.end_time: return (self.end_time - self.start_time) * 1000 return (time.time() - self.start_time) * 1000class AgentTracer: Agent执行追踪器 def __init__(self): self.traces [] self.current_span_stack [] def start_span(self, name: str, inputs: dict None, metadata: dict None) - AgentTraceSpan: parent_id self.current_span_stack[-1].span_id if self.current_span_stack else None span AgentTraceSpan( namename, parent_idparent_id, inputsinputs or {}, metadatametadata or {} ) if self.current_span_stack: self.current_span_stack[-1].children.append(span) else: self.traces.append(span) self.current_span_stack.append(span) return span def end_span(self, outputs: dict None, error: str None): if self.current_span_stack: span self.current_span_stack.pop() span.end(outputsoutputs, errorerror) return span def print_trace(self, span: AgentTraceSpan None, indent: int 0): 打印追踪树 if span is None: for trace in self.traces: self.print_trace(trace) return status ✓ if not span.error else ✗ print(f{ * indent}{status} [{span.duration_ms:.0f}ms] {span.name}) if span.error: print(f{ * (indent1)}ERROR: {span.error}) for child in span.children: self.print_trace(child, indent 1)# 使用示例tracer AgentTracer()async def traced_agent_run(task: str): root_span tracer.start_span(agent_run, inputs{task: task}) try: # 规划阶段 plan_span tracer.start_span(planning, inputs{task: task}) plan await generate_plan(task) tracer.end_span(outputs{plan: plan}) # 执行阶段 for i, step in enumerate(plan): step_span tracer.start_span(fexecute_step_{i}, inputs{step: step}) # 工具调用 tool_span tracer.start_span( ftool_{step[tool]}, inputs{args: step.get(args, {})} ) result await call_tool(step[tool], step.get(args, {})) tracer.end_span(outputs{result: str(result)[:500]}) tracer.end_span(outputs{status: completed}) tracer.end_span(outputs{status: success}) except Exception as e: tracer.end_span(errorstr(e)) raise # 打印追踪树 tracer.print_trace()## Prometheus指标监控将LLM调用指标暴露给Prometheus与现有监控基础设施集成pythonfrom prometheus_client import Counter, Histogram, Gauge, start_http_server# 定义指标llm_requests_total Counter( llm_requests_total, Total LLM API calls, [model, app, status])llm_latency_histogram Histogram( llm_latency_seconds, LLM API call latency, [model, app], buckets[0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0])llm_tokens_counter Counter( llm_tokens_total, Total tokens consumed, [model, app, token_type])llm_cost_counter Counter( llm_cost_usd_total, Estimated USD cost of LLM calls, [model, app])# 指标收集中间件def record_llm_metrics(model: str, app: str, duration: float, usage, cost: float, status: str): llm_requests_total.labels(modelmodel, appapp, statusstatus).inc() llm_latency_histogram.labels(modelmodel, appapp).observe(duration) llm_tokens_counter.labels(modelmodel, appapp, token_typeprompt).inc(usage.prompt_tokens) llm_tokens_counter.labels(modelmodel, appapp, token_typecompletion).inc(usage.completion_tokens) llm_cost_counter.labels(modelmodel, appapp).inc(cost)# 启动Prometheus HTTP服务器暴露metrics端点start_http_server(8080) # curl http://localhost:8080/metrics## 可视化看板设计用Grafana构建LLM监控看板关键面板1.成本看板按模型/应用的每日/月度费用趋势2.性能看板P50/P95/P99延迟不同模型对比3.质量看板自动化质量评分趋势问题率4.Token分布看板Prompt vs Completion比例长尾请求分析## 小结构建LLM可观测性系统的最简路径1.第一步添加结构化日志记录每次LLM调用的关键信息2.第二步接入LangSmith如果用LangChain或OpenTelemetry3.第三步暴露Prometheus指标建立成本和性能告警4.第四步建立自动化质量评估定期跑评测集可观测性不是锦上添花而是生产级AI应用的地基。没有可观测性的AI系统出了问题只能靠猜。

相关文章:

AI应用的可观测性工程:用Tracing和Logging看清LLM黑盒

“我的RAG系统回答了一个错误答案,但我不知道为什么。” “Agent跑了2分钟什么都没完成,我不知道它在做什么。” “用了新版本Prompt,感觉质量变了,但我说不清楚哪里变了。” 这些是AI工程师最常见的困境,根本原因是缺…...

量子计算并行化:编译器与硬件协同设计实践

1. 量子计算中的并行化革命:从理论到实践 量子计算正在经历一场从实验室原型向实用化系统转变的关键时期。作为一名长期跟踪量子计算硬件发展的工程师,我亲眼目睹了量子处理器规模从几个量子比特扩展到数百个量子比特的历程。在这个过程中,一…...

AI 入门 30 天挑战 - Day 18 费曼学习法版 - 图像分割基础

🌟 完整项目和代码 本教程是 AI 入门 30 天挑战 系列的一部分! 💻 GitHub 仓库: https://github.com/Lee985-cmd/AI-30-Day-Challenge📖 CSDN 专栏: https://blog.csdn.net/m0_67081842?typeblog⭐ 欢迎 Star 支持!…...

终极Maple Mono字体安全审计指南:从漏洞排查到防护最佳实践

终极Maple Mono字体安全审计指南:从漏洞排查到防护最佳实践 【免费下载链接】maple-font Maple Mono: Open source monospace font with round corner, ligatures and Nerd-Font icons for IDE and terminal, fine-grained customization options. 带连字和控制台图…...

AI工程师的上下文管理术:让长对话不失忆的工程实践

LLM最大的局限之一,是有限的上下文窗口。GPT-4o有128K token,Gemini 1.5 Pro有100万token——听起来很大,但实际生产中,长对话积累、知识库检索内容、工具调用结果……很快就能填满。更根本的问题是:不是塞满上下文就好…...

【网安项目】基于深度学习的网络入侵检测系统设计与实现

🛡️ 基于 PyTorch CNN-BiLSTM 的可视化网络入侵检测系统1. 项目摘要本项目设计并实现了一款端到端的网络入侵检测系统(IDS)。系统基于 PyTorch 深度学习框架,采用 CNN-BiLSTM 混合神经网络模型,结合 CICIDS2017 数据集…...

UDS诊断(ISO14229-1) 3D服务:WriteMemoryByAddress实战解析与安全考量

1. 初识WriteMemoryByAddress服务:汽车ECU的"手术刀" 当你需要修改汽车ECU中的某个特定参数时,WriteMemoryByAddress服务就像一把精准的手术刀。作为UDS诊断协议(ISO14229-1)中的3D服务,它允许我们直接通过内…...

专栏A-AI原生产品设计-01-AI辅助 vs AI原生——产品形态的代际差异

第1篇:AI辅助 vs AI原生——产品形态的代际差异本文你将获得 工具1:AI原生度评估矩阵——量化你的产品有多"AI原生",找出差距工具2:AI辅助→AI原生迁移路线图——系统性地将产品从辅助模式升级到原生模式工具3&#xff…...

多模态提示工程终极指南:MiniCPM-V对话模板设计与优化策略

多模态提示工程终极指南:MiniCPM-V对话模板设计与优化策略 【免费下载链接】MiniCPM-V A Gemini 2.5 Flash Level MLLM for Vision, Speech, and Full-Duplex Multimodal Live Streaming on Your Phone 项目地址: https://gitcode.com/GitHub_Trending/mi/MiniCPM…...

一句话出图!生物医学科研绘图天花板

作为常年泡实验室、写论文申基金的科研狗,谁没为了一张图掉过头发?做实验结果图要调格式,画机制图找不对素材,做组会PPT要改海报,找外包画图不仅贵还要等一周,自己用PS又半天摸不着门道。相信我&#xff0c…...

深入EB协议栈:我是如何通过抓包和调试,定位一个诡异的车载网络时间同步漂移问题的

深入EB协议栈:我是如何通过抓包和调试,定位一个诡异的车载网络时间同步漂移问题的 1. 问题现象:时间同步中的"幽灵偏移" 那是一个周五的下午,我正在测试车间里盯着示波器上跳动的波形。这是我们新一代智能驾驶平台的关键…...

Front-End-Checklist SEO最佳实践:提升搜索排名的终极指南

Front-End-Checklist SEO最佳实践:提升搜索排名的终极指南 【免费下载链接】Front-End-Checklist 🗂 The perfect Front-End Checklist for modern websites and meticulous developers 项目地址: https://gitcode.com/gh_mirrors/fr/Front-End-Checkl…...

MSGA多尺度门控注意力改进YOLOv26特征融合自适应选择能力

MSGA多尺度门控注意力改进YOLOv26特征融合自适应选择能力 引言 在目标检测任务中,特征融合是连接不同尺度特征的关键环节。传统的YOLOv26采用简单的特征拼接方式,虽然能够整合多尺度信息,但缺乏对特征重要性的自适应判断能力。本文引入MSGA…...

jQuery与现代框架集成:React、Vue、Angular协同开发终极指南

jQuery与现代框架集成:React、Vue、Angular协同开发终极指南 【免费下载链接】jquery jQuery JavaScript Library 项目地址: https://gitcode.com/gh_mirrors/jq/jquery jQuery作为经典的JavaScript库,至今仍在全球数百万网站中发挥着重要作用。当…...

算法训练营第十四天|18. 四数之和

建议: 要比较一下,本题和 454.四数相加II 的区别,为什么 454.四数相加II 会简单很多,这个想明白了,对本题理解就深刻了。 本题 思路整体和 三数之和一样的,都是双指针,但写的时候 有很多小细节&…...

Qianfan-OCR生产环境:日志分级(DEBUG/INFO/WARN)、服务健康检查、自动重启策略

Qianfan-OCR生产环境:日志分级、健康检查与自动重启策略 1. 项目概述 百度千帆文档智能模型(Qianfan-OCR)是一款开源的4B参数端到端文档智能多模态模型,基于InternVLChat架构(InternViT Qwen3-4B)构建。作为传统OCR流水线的替代方案,它能够…...

Hyperbeam:构建下一代端到端加密管道的终极指南

Hyperbeam:构建下一代端到端加密管道的终极指南 在网络通信日益复杂的今天,你是否曾为数据传输的安全性而担忧?Hyperbeam的出现彻底改变了这一局面,它是一款基于Hyperswarm和Noise协议的端到端加密互联网管道工具,为开…...

如何用 dedao-dl 实现得到课程永久保存?告别知识过期的完整指南

如何用 dedao-dl 实现得到课程永久保存?告别知识过期的完整指南 【免费下载链接】dedao-dl 得到 APP 课程下载工具,可在终端查看文章内容,可生成 PDF,音频文件,markdown 文稿,可下载电子书。可结合 opencla…...

浏览器端CNN开发实战:TensorFlow.js入门指南

1. 网页端构建卷积神经网络的必要性十年前我第一次接触深度学习时,光是配置TensorFlow环境就花了整整三天。现在打开浏览器就能跑神经网络,这种技术进步让每个想入门AI的人都该感到庆幸。网页端CNN开发最大的优势在于零环境配置——不需要安装CUDA驱动&a…...

我的WINPE使用历史

不知道为何,家里机器理想小新AIR I3,一个GPDWIN一代(袖珍windows游戏机,可以用hdmi输出到电视上),稍微电量差点,在“完全”版WIN10下,就带不动,直接关机或者重启&#xf…...

为什么92%的C++ MCP插件在K8s中启动失败?——4类ABI不兼容场景及跨平台cmake工具链配置清单

第一章:C 编写高吞吐量 MCP 网关 插件下载与安装插件源码获取方式 MCP(Model Control Protocol)网关 C 插件采用 MIT 许可证开源,官方代码仓库托管于 GitHub。推荐使用 Git 克隆最新稳定分支:git clone --branch v1.4.…...

容器存储不再受限:Docker 27原生支持动态卷扩容的3大前提条件、2个隐藏API及1次误操作导致数据丢失的惨痛复盘

第一章:容器存储不再受限:Docker 27原生支持动态卷扩容的3大前提条件、2个隐藏API及1次误操作导致数据丢失的惨痛复盘 Docker 27 引入了对本地卷(local volume)动态扩容的原生支持,但该能力并非开箱即用。启用前必须满…...

【C++高吞吐MCP网关实战指南】:20年架构师亲授7大性能瓶颈突破法,面试官当场发offer?

第一章:C高吞吐量MCP网关面试概览C高吞吐量MCP(Message Control Protocol)网关是金融、高频交易及实时风控系统中的核心中间件,其设计目标是在微秒级延迟约束下完成协议解析、路由分发、会话管理与流控熔断。面试中,候…...

免费AI图像放大终极指南:Upscayl如何让低分辨率图片秒变高清

免费AI图像放大终极指南:Upscayl如何让低分辨率图片秒变高清 【免费下载链接】upscayl 🆙 Upscayl - #1 Free and Open Source AI Image Upscaler for Linux, MacOS and Windows. 项目地址: https://gitcode.com/GitHub_Trending/up/upscayl Upsc…...

Habitat-Matterport 3D数据集:1000个真实室内场景的终极AI训练宝库 [特殊字符]

Habitat-Matterport 3D数据集:1000个真实室内场景的终极AI训练宝库 🏠 【免费下载链接】habitat-matterport3d-dataset This repository contains code to reproduce experimental results from our HM3D paper in NeurIPS 2021. 项目地址: https://gi…...

从docker logs -f 到全域日志智能归因:27天交付符合ISO 27001审计要求的日志治理体系

第一章&#xff1a;从docker logs -f到全域日志智能归因的演进动因 在容器化初期&#xff0c;开发者依赖 docker logs -f <container-id> 实时追踪单容器输出&#xff0c;这一命令简洁有效&#xff0c;却隐含三重结构性局限&#xff1a;日志无上下文、跨服务无法关联、故…...

WeDLM-7B-Base镜像免配置教程:Gradio队列管理+并发请求稳定性保障

WeDLM-7B-Base镜像免配置教程&#xff1a;Gradio队列管理并发请求稳定性保障 1. 模型简介与核心优势 WeDLM-7B-Base是一款基于扩散机制&#xff08;Diffusion&#xff09;的高性能基座语言模型&#xff0c;拥有70亿参数。相比传统语言模型&#xff0c;它在多个技术维度实现了…...

Docker 27加密容器踩坑实录(含3个未公开CVE规避方案):某三甲医院PACS系统迁移后性能反升18%的真相

第一章&#xff1a;Docker 27加密容器的医疗合规性演进与临床落地背景随着《HIPAA》《GDPR》及中国《个人信息保护法》《医疗卫生机构数据安全管理办法&#xff08;试行&#xff09;》等法规持续强化对患者健康数据的全生命周期管控要求&#xff0c;传统容器运行时在静态数据加…...

GLM-4.1V-9B-Base生产环境:制造业设备图片故障特征问答系统搭建

GLM-4.1V-9B-Base生产环境&#xff1a;制造业设备图片故障特征问答系统搭建 1. 项目背景与价值 在制造业设备维护领域&#xff0c;传统的人工巡检方式存在效率低、成本高、依赖经验等问题。GLM-4.1V-9B-Base作为一款视觉多模态理解模型&#xff0c;为解决这些问题提供了创新方…...

绝缘子位置检测数据集(2000张)|YOLOv8训练数据集 电力巡检 无人机检测 输电线路监测 智能运维

绝缘子位置检测数据集&#xff08;2000张&#xff09;&#xff5c;YOLOv8训练数据集 电力巡检 无人机检测 输电线路监测 智能运维 前言 随着电力系统规模的不断扩大与智能电网建设的持续推进&#xff0c;传统依赖人工巡检的运维方式正面临效率与安全性的双重挑战。尤其是在输电…...