🎯 本周要收的东西

六天的零件今天拼成一个可运行的类:一个 AgentObservationInterceptor,把 trace、指标、成本、日志四件事在一次调用里全部做完,业务代码只需加一行注解。

📖 本周回顾

天 主题 落地物
D1全链路追踪TraceIdFilter + TaskDecorator + step span
D2四个核心指标AgentMetrics(outcome/steps/duration/cost)
D3日志与脱敏PiiMasker + 三层日志隔离
D4Token 成本CostCalculator(输入/缓存/输出三段式)
D5三板斧ModelRouter + PromptLayout + 语义缓存
D6告警7 条 Prometheus 规则 + Runbook

优先级排序:成本告警 > 写工具失败率 > 步数膨胀 > 延迟 P95。前两项直接对应资损,后两项主要是体验。

还有一条本周最重要的教训:成本必须按任务分摊而不是按调用统计。一次任务跑 3 轮,第 3 轮的输入携带了前两轮全部上下文,它单独就占这次成本的四成;按调用平均看会严重低估长尾任务,而恰恰是这些长尾任务在烧钱。分摊规则是:同一 traceId 下的所有调用归到该任务的 agent 与 outcome 维度,失败重试也计入——失败的 token 一样收钱。

指标口径错了比没有指标更危险,所以 outcome 枚举必须先于所有面板落地;告警阈值也要从上线的第一天就设,而不是等出事再补,因为基线数据需要积累两周才有意义。

💻 完整实现:拦截器 + 埋点

一个注解 + 一个切面,一次请求内完成:生成 traceId、开 Timer、开 Observation、结算 token 成本、打三层日志、异常分类。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AgentObserved {
    String agent();
}
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class AgentObservationInterceptor {

    private final MeterRegistry registry;
    private final ObservationRegistry observations;
    private final CostCalculator costCalculator;
    private final PiiMasker masker;

    @Around("@annotation(obs)")
    public Object around(ProceedingJoinPoint pjp, AgentObserved obs) throws Throwable {
        String agent = obs.agent();
        String traceId = Optional.ofNullable(MDC.get("traceId"))
                .orElseGet(() -> UUID.randomUUID().toString().replace("-", ""));
        Timer.Sample sample = Timer.start(registry);

        AgentRequest req = null;
        AgentResult result = null;
        String error = null;

        try (MDC.MDCCloseable c = MDC.putCloseable("traceId", traceId)) {
            req = Arrays.stream(pjp.getArgs())
                    .filter(AgentRequest.class::isInstance)
                    .map(AgentRequest.class::cast).findFirst().orElse(null);

            result = Observation.createNotStarted("agent.task", observations)
                    .lowCardinalityKeyValue("agent", agent)
                    .observeChecked(() -> (AgentResult) pjp.proceed());

            return result;
        } catch (Throwable t) {
            error = classify(t);
            throw t;
        } finally {
            String outcome = error != null ? error
                    : (result == null ? "unknown" : result.outcome().name().toLowerCase());
            String model = result != null ? result.model() : (req != null ? req.model() : "unknown");

            // 1) 指标
            registry.counter("agent.task.total", "agent", agent, "outcome", outcome, "model", model)
                    .increment();
            if (result != null) {
                registry.summary("agent.task.steps", "agent", agent).record(result.stepCount());
                long cost = costCalculator.costMicroUsd(model, LocalDate.now(),
                        result.usage().promptTokens(), result.usage().cachedTokens(),
                        result.usage().completionTokens());
                registry.counter("agent.cost.microusd", "agent", agent, "model", model)
                        .increment(cost);
            }
            sample.stop(Timer.builder("agent.task.duration")
                    .tag("agent", agent).tag("model", model).tag("outcome", outcome)
                    .publishPercentileHistogram()
                    .serviceLevelObjectives(Duration.ofMillis(800), Duration.ofSeconds(2),
                            Duration.ofSeconds(5), Duration.ofSeconds(15))
                    .register(registry));

            // 2) L1 结构化日志:只打字段,不打内容
            log.atInfo()
                    .addKeyValue("agent", agent)
                    .addKeyValue("model", model)
                    .addKeyValue("outcome", outcome)
                    .addKeyValue("steps", result == null ? -1 : result.stepCount())
                    .addKeyValue("userKey", masker.hash(
                            req == null ? null : req.userId()))
                    .addKeyValue("costMicroUsd", result == null ? 0L : result.costMicroUsd())
                    .log("agent.task.done");
        }
    }

    private String classify(Throwable t) {
        if (t instanceof TimeoutException) return "timeout";
        if (t instanceof MaxStepsExceededException) return "max_steps";
        if (t instanceof GuardBlockedException) return "guard_blocked";
        if (t instanceof ToolException) return "tool_error";
        return "error";
    }
}

接入方式就是这一行:

@AgentObserved(agent = "after-sales-ticket")
public AgentResult handle(AgentRequest req) {
    return loop.run(AgentTrace.start(req));
}

三个刻意的设计取舍。第一,MDC 用 putCloseable 而不是手动 put/remove,避免异常路径漏清理导致线程复用时串号。第二,指标全部在 finally 里结算,因为失败的调用同样产生 token 成本,早期版本只在成功分支记账,账面对不上就是这么来的。第三,Timer.builder 放在 stop() 时构造而不是提前持有,否则高基数 tag 会在每次请求新建 meter,MeterRegistry 内部缓存会膨胀到几万个条目——这是 Micrometer 最隐蔽的性能坑。

上线顺序建议:先接 L1 结构化日志(无风险),再接指标(只增不减),最后开 10% 采样追踪。每接一层跑一次同样的压测,对比 P99 开销增量是否在 5% 以内。

✏️ 今日动手

把拦截器接进 W3 的工单 Agent,跑 200 次压测,然后按三段验证:① Prometheus 里 agent_task_total 的 outcome 分布加总必须等于 200;② Grafana 上 P95 延迟、平均步数、单次成本三个面板都有数;③ 任取一个 traceId,能在日志里找到对应的一行 L1 记录,并用它去 Zipkin 查出完整 span 树。

🔖 下周预告

W8 进入多 Agent 协作:Supervisor 与 Handoff 的两种拓扑、共享上下文怎么避免互相污染、Agent 之间的成本归属,以及如何把本周的可观测性升级成「按 Agent 维度分摊账单」。