跳到主要内容
📖 本章预览

本章为预览版本,展示部分核心内容。完整内容包含详细源码解析、实战代码和面试要点,加入知识星球即可解锁全部章节。

第24章 可观测性:给 AI 应用装上上帝视角

本章基于 Spring AI 1.1.2,可观测性基于 Micrometer Observation API + OpenTelemetry

24.1 底层原理:Spring AI 的可观测性架构

24.1.1 核心机制

Spring AI 的可观测性不是"自己造轮子",而是复用了 Spring 生态的 Observation API:

Micrometer Observation API(统一抽象)
├── Metrics(指标)→ Micrometer Registry → Prometheus / Grafana
├── Tracing(链路)→ Micrometer Tracing → OpenTelemetry → Jaeger / Zipkin
└── Logging(日志)→ SLF4J → ELK / Loki

Spring AI 在以下组件中埋入了 Observation:
1. ChatClient(包括 Advisor 链)
2. ChatModel(模型调用)
3. EmbeddingModel(向量化)
4. VectorStore(向量检索)
5. Tool Calling(工具调用)

每个 Observation 包含两类 Key:
- Low Cardinality Key:加到 Metrics + Traces(如 model 名称、操作类型)
- High Cardinality Key:只加到 Traces(如完整 prompt、token 数量)

24.1.2 为什么 AI 应用特别需要可观测性

传统 Web 应用:请求 → 业务逻辑 → 数据库 → 响应(确定性的)
AI 应用:请求 → Advisor链 → RAG检索 → LLM调用 → Tool Calling → 再次LLM → 响应(不确定性的)

AI 应用的特殊挑战:
1. 延迟不可预测:同一个 Prompt,LLM 响应时间可能从 500ms 到 30s
2. 成本不透明:每次调用消耗多少 Token?一天花了多少钱?
3. 质量难衡量:RAG 检索到的内容相关吗?Agent 迭代了几次?
4. 故障难定位:一次请求经过 Advisor → RAG → LLM → Tool → LLM,哪一步出了问题?

可观测性的三大支柱在 AI 场景的映射:
- Metrics(指标)→ 调用量、延迟分布、Token消耗、错误率
- Tracing(链路)→ 一次请求经过的完整调用链,每一步的耗时和参数
- Logging(日志)→ Prompt 内容、模型回复、异常堆栈

24.2 开箱即用:Spring AI 内置指标

24.2.1 依赖配置

<!-- pom.xml -->
<!-- Actuator(暴露指标端点) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- Prometheus 格式导出(可选,用于 Grafana) -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!-- OpenTelemetry 链路追踪桥接(可选) -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>

24.2.2 配置

# application.yml
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
metrics:
tags:
application: spring-ai-app

# Spring AI 可观测性配置
spring:
ai:
chat:
observations:
log-prompt: false # 是否在 trace 中记录完整 prompt(注意隐私)
log-completion: false # 是否在 trace 中记录完整回复
client:
observations:
log-prompt: false # ChatClient 级别的 prompt 日志
vectorstore:
observations:


🔒 解锁完整内容

本章剩余内容需要解锁后查看

以上仅为本章部分预览内容,完整内容包含更多深度源码解析、实战代码和面试要点。

加入知识星球你将获得:

  • ✅ 全部 26 章完整内容 + 持续更新
  • ✅ 配套源码 + 实战项目
  • ✅ 一对一答疑 + 面试辅导
  • ✅ 简历优化 + 内推机会

📚 本章完整目录

以下为本章完整目录结构,加入知识星球即可解锁全部内容。

24.2.3 Spring AI 自动采集的指标清单

24.3 实战:自定义业务指标

24.3.1 AI 业务指标收集器

24.3.2 指标采集 Advisor

24.4 链路追踪:看清一次请求的完整旅程

24.4.1 原理

24.4.2 手动增强链路追踪

24.5 结构化日志

24.5.1 原理

24.5.2 AI 调用日志工具

24.6 告警规则

24.6.1 Prometheus 告警规则

24.7 可观测性架构总结