CCAR-P and Databricks GenAI Study Notebook — Day 2, Part 2
The big picture, CCAR-P crosswalk, Databricks platform map, and key-terminology glossary stay living in Day 1 Part 1. Folder 2 is complete in Day 1 Part 2, and Folder 3 in Day 2 Part 1. This page is the last stretch: Folder 4, "Deploying and Monitoring Agents on Databricks," Files 29-36. It is the folder that closes the loop this whole notebook has been building toward — everything in Folders 1-3 was about building and evaluating an agent offline; Folder 4 is about what happens once it is actually live and someone else is depending on it.
大图景、CCAR-P 对照、Databricks 平台结构图,以及术语表,继续留在Day 1 第一部分里。Folder 2 已经在Day 1 第二部分里讲完,Folder 3 在Day 2 第一部分里讲完。这一页是最后一段:Folder 4,"Deploying and Monitoring Agents on Databricks",File 29-36。这正是整本笔记一直在朝着走的那个闭环——Folder 1-3 讲的都是怎么在线下把一个 agent 建好、评测好;Folder 4 讲的是这个 agent 真正上线之后、有别人在依赖它的时候,会发生什么。
· Note on this part
Folder 4 has eight files (global numbering continues: File 29 is Folder 4's first file, not File 1 again), organized around the same four-stage arc its own opening lecture names: deploy (Databricks Apps, DABs), observe (MLflow Tracing), evaluate (the scorers from Folder 3, now running continuously in production), and monitor (backfill, SQL queries over Unity Catalog trace tables). This is deliberately the same vocabulary Folder 3 used, reapplied to traffic that is actually live instead of a curated eval dataset.
Folder 4 一共八个文件(全局编号继续往下走:File 29 是 Folder 4 的第一个文件,不是重新从 File 1 开始),围绕着这个文件夹自己开篇那节课点名的那个四阶段弧线来组织:部署(Databricks Apps、DABs)、观测(MLflow Tracing)、评测(Folder 3 里讲的那些 scorer,现在持续跑在生产环境里)、监控(回填、对 Unity Catalog trace 表跑 SQL 查询)。这是故意沿用 Folder 3 的那套词汇,只是这次套用在真正的线上流量上,而不是一份精心准备好的评测数据集上。
File 29 (lecture) lays out deployment architecture in the abstract. File 30 (demo) builds one agent through three concrete stages — bare chatbot, traced chatbot, tool-calling chatbot — and is the single most load-bearing file in the folder for an actual build. File 31 (lecture) backs up to explain MCP and tracing in more depth. File 32 (demo) goes deep on production-grade tracing techniques File 30 only touched lightly. File 33 (lecture) is Folder 3's scorer material, re-framed for always-on production monitoring rather than one-shot evaluation. Files 34-35 (labs) are the hands-on version of File 33. File 36 (appendix, optional) covers a newer, more automated alternative to the Apps+DABs path.
08 Folder 4 Agenda
| File | Type | Notebook | Covers |
|---|---|---|---|
| 29 | Lecture | Agent Deployment on Databricks | Agent lifecycle, Databricks Apps, DABs, deployment patterns, resource injection, Unity Gateway |
| 30 | Demo | Deploying an Observable Agent | Build an agent through three stages: deploy as an App, add MLflow tracing, integrate an MCP tool |
| 31 | Lecture | Tool Integration and Observability | Model Context Protocol, MCP server types, MCP lifecycle, MLflow Tracing foundations |
| 32 | Demo | Tracing for Production Agents | Manual spans, span types, custom attributes, multi-turn session grouping, programmatic trace search |
| 33 | Lecture | Production Evaluation and Monitoring | Scorer types, custom scorers, multi-turn judges, sampling strategies, scorer lifecycle, backfill |
| 34 | Lab | Online Evaluation with Multi-Turn Conversations | Deploy judges, create custom scorers, tune sampling rates, run the metrics computation job |
| 35 | Lab | Backfilling and Querying Multi-Turn Conversations | Backfill historical traces, query traces and assessments in Unity Catalog with SQL, scorer cleanup |
| 36 | Lecture (Appendix) | Agent Bricks CLI | init / dev / deploy lifecycle, agent.toml, managed tools, memory, and sessions (Beta) |
Requirements stated by the course: a Databricks workspace with serverless compute (Version 6), and the course model services in dbacademy.agent_deployment (agent-model and judge-model), created by the workspace setup script — the same provisioning pattern Day 1 found behind every earlier folder's shared fixtures.
课程写明的前提条件:一个带 serverless compute(Version 6)的 Databricks workspace,以及 dbacademy.agent_deployment 里的课程模型服务(agent-model 和 judge-model),由 workspace 的 setup 脚本创建——跟 Day 1 发现的、前面每个 Folder 共享 fixture 背后的那套配置方式一样。
File 29 Lecture — Agent Deployment on Databricks
A The Agent Lifecycle
A production agent must be deployed to infrastructure that serves requests, observed so you can understand its behavior, evaluated to measure quality, and monitored continuously to catch regressions. These four stages are not strictly sequential — you can add tracing before deployment, attach scorers to an agent that is already live, or backfill evaluation data onto traces logged weeks ago. The lifecycle is designed to be incremental, which is exactly the order File 30's demo actually builds in: deploy first with nothing else, then layer tracing, then layer a tool.
一个生产级 agent 必须被部署到能处理请求的基础设施上,被观测以便理解它的行为,被评测来衡量质量,还要被持续监控以便在用户发现之前就抓到回归。这四个阶段并不是严格按顺序来的——你可以在部署之前就先加上 tracing,可以给一个已经上线的 agent 挂上 scorer,也可以把评测数据回填到几周前记下来的 trace 上。这套生命周期就是设计成可以一步一步加的,这恰好也是 File 30 的 demo 实际构建的顺序:先什么都不加先部署,然后叠加 tracing,再叠加一个工具。
B Deployment Architecture
B1. Databricks Apps provide managed hosting for web applications. The platform provisions compute, assigns the app its own service principal (the identity that determines what the app can access — model services, UC objects, experiments), and gives it a unique workspace-scoped URL. Apps are first-class workspace objects on the Apps page in the sidebar. B2. Declarative Automation Bundles (DABs) are the project structure describing the app and its resources: user-authored files (agent.py, server.py, chat.html, pyproject.toml) plus config files defined by the spec (requirements.txt, databricks.yml, app.yaml). Deployment is two independent steps — databricks bundle deploy creates/updates the resource declarations, then databricks apps deploy <app> pushes the source code.
B1. Databricks Apps 为 web 应用提供托管环境。平台负责配置 compute,给每个 app 分配一个属于它自己的service principal(决定这个 app 能访问什么的身份——模型服务、UC 对象、experiment),还给它一个独一无二、workspace 范围内的 URL。App 是 workspace 里的一级对象,在侧边栏的Apps页面能看到。B2. Declarative Automation Bundle(DAB)是描述这个 app 和它所依赖资源的项目结构:用户自己写的文件(agent.py、server.py、chat.html、pyproject.toml)加上由规范定义的配置文件(requirements.txt、databricks.yml、app.yaml)。部署是两个互相独立的步骤——databricks bundle deploy创建/更新资源声明,然后databricks apps deploy <app>把源代码推上去。
Model Serving treats the agent as a model: package it as an MLflow model, log and register it in Unity Catalog, Databricks hosts it behind a managed REST endpoint — the platform owns the server, you fit its predict-style interface. Databricks Apps treats the agent as an application: ordinary Python code in Git, running as a web service on managed compute, where you own the routes, async behavior, even a UI. Databricks now recommends Apps for new custom agents because agents behave like software (multi-step loops, tool calls, state, long-running, frequently changed), not like static model artifacts.
| Concept | Model Serving | Databricks Apps |
|---|---|---|
| Unit of deployment | A versioned model artifact | A codebase or application |
| Lifecycle | Log, register, deploy an endpoint | Edit code, deploy (Git-driven CI/CD) |
| Who owns the server | Databricks (you fit its interface) | You (custom routes); Databricks hosts it |
| Iteration speed | Slower: repackage + redeploy each change | Fast: change code, redeploy in seconds |
| Shape of an interaction | Request / response | Long-running, async, or streaming |
| Front end | Separate (e.g. the Review App) | Can ship a chat UI alongside the agent |
What stays the same either way: MLflow tracing and evaluation work identically on both. Agents reach governed Databricks resources (UC functions, AI Search, foundation models) under scoped permissions regardless of which deployment pattern hosts them. Model Serving remains the home for the LLMs and classic ML models an agent calls — Apps hosts the agent, serving endpoints still host the models behind it.
两种方式都不变的地方:MLflow tracing 和评测在两边跑起来是一样的。Agent 访问受治理的 Databricks 资源(UC 函数、AI Search、基础模型)走的都是受限权限,跟选哪种部署方式无关。Model Serving 仍然是 agent 调用的那些 LLM 和传统 ML 模型的家——Apps 托管的是 agent 本身,serving endpoint 托管的仍然是 agent 背后那些模型。
B4 Resource Injection
databricks.yml declares every resource the app depends on; app.yaml's top-level env: section injects those resources into the running app as environment variables, so agent code reads configuration from the environment instead of hardcoding workspace-specific values. The same code runs unchanged across dev, staging, and production by changing only the databricks.yml resource declarations.
databricks.yml声明这个 app 依赖的每一个资源;app.yaml顶层的env:部分把这些资源作为环境变量注入到运行中的 app 里,所以 agent 代码从环境里读配置,而不是把 workspace 特定的值写死在代码里。同一份代码在 dev、staging、生产环境之间不用改一个字,只需要改databricks.yml里的资源声明。
B5 Unity Gateway
Every model-service call from a deployed agent routes through Unity Gateway, Databricks' centralized AI governance layer: guardrails, rate limiting, usage tracking, traffic splitting, and inference-table logging, all configured on the service itself with zero agent code changes. Unity Gateway governs more than agent traffic — it is a unified governance layer across LLM endpoints, MCP servers, and coding agents (Cursor, Claude Code, Codex CLI), giving platform teams one place to manage AI access org-wide.
每一次从已部署的 agent 发出的模型服务调用,都会经过Unity Gateway——Databricks 的集中式 AI 治理层:护栏、速率限制、用量追踪、流量分流、推理表日志,这些全都配置在服务本身上,agent 代码一行都不用改。Unity Gateway 治理的不只是 agent 流量——它是一个统一的治理层,覆盖 LLM endpoint、MCP server,以及编码 agent(Cursor、Claude Code、Codex CLI),让平台团队有一个地方就能管住全组织的 AI 访问。
CCAR-P crosswalk
- D1 (architecture) / D7 (dev productivity & ops enablement) — the Model Serving vs. Apps decision is a textbook D1/D7 question: "agent behaves like software, not a static artifact" is the architect-level judgment call the exam rewards, not the CLI syntax underneath it.
- D5 (governance/safety/risk) — Unity Gateway as a single governance point across LLM endpoints, MCP servers, and coding agents is exactly the "one control plane, not N bolted-on controls" pattern D5 questions are built around.
Resource injection answers a real open question from Day 1's Advana reconnaissance: Advana's Databricks environment is on a different, lagging feature set from the public course UI, with Unity Catalog and serverless "in the implementation." A deployment pattern that reads every environment-specific value (catalog name, model service, warehouse ID) from databricks.yml/app.yaml rather than hardcoding it means an FM Insight agent built against the public-course pattern here can, in principle, point at Advana's actual resource names later with no code change — only a resource-declaration change. That is the exact decoupling an environment with a lagging, partially-rolled-out feature set needs.
资源注入这件事,回答了 Day 1 在 Advana 侦察时留下的一个真实的未解问题:Advana 的 Databricks 环境,功能版本比公开课程的 UI 要落后一些,Unity Catalog 和 serverless 都还"在实施中"。一种把每一个环境特定的值(catalog 名字、模型服务、warehouse ID)都从databricks.yml/app.yaml里读出来、而不是写死在代码里的部署方式,意味着这里按公开课程套路搭出来的 FM Insight agent,原则上以后可以直接指向 Advana 里真实的资源名字,不用改一行代码——只需要改资源声明。这恰好是一个功能滞后、还没完全上线的环境最需要的那种解耦。
File 30 Demo — Deploying an Observable Agent
This demo progressively builds one agent in three stages, each redeploying the same Databricks App: a bare chatbot with no observability; the same chatbot with MLflow tracing wired in; the same chatbot with a SQL tool added through a Databricks-provided MCP. Each stage is additive — nothing from an earlier stage is removed, and by the end every agent interaction, including tool calls, produces a structured MLflow trace with no change to how tracing itself works.
这个 demo 分三个阶段,逐步构建同一个 agent,每一阶段都是对同一个 Databricks App 重新部署:先是一个什么观测都没有的裸聊天机器人;然后是接上 MLflow tracing 的同一个聊天机器人;再是通过 Databricks 提供的 MCP 加上一个 SQL 工具的同一个聊天机器人。每一阶段都是叠加的——前一阶段的东西一个都不删,到最后,每一次 agent 交互,包括工具调用,都会产生一条结构化的 MLflow trace,而 tracing 本身的工作方式一点没变。
C Stage 1 — Define and Deploy a Basic Agent
Six files make up the basic agent. agent.py defines the agent using the OpenAI Agents SDK, with set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True)) as the one line that routes every model call through Unity Gateway instead of the public OpenAI service, and set_default_openai_api("responses") so tool calls work with reasoning models. server.py is a small hand-written FastAPI server exposing GET / (a chat page) and POST /invocations (forwards messages to the agent) — the course notes that production agents should instead use MLflow's AgentServer template, which adds the standard Responses API, streaming, and a built-in chat UI. pyproject.toml, app.yaml, databricks.yml, and requirements.txt round out the bundle exactly as File 29 described.
六个文件构成了这个基础 agent。agent.py用 OpenAI Agents SDK 定义 agent,核心的一行是set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True))——这一行把每一次模型调用都路由到 Unity Gateway,而不是公开的 OpenAI 服务;再加上set_default_openai_api("responses"),让工具调用能配合推理模型工作。server.py是一个手写的小 FastAPI 服务,暴露GET /(聊天页面)和POST /invocations(把消息转发给 agent)——课程特意说明,生产级 agent 应该改用 MLflow 的AgentServer模板,它自带标准 Responses API、流式输出,还有内置聊天 UI。pyproject.toml、app.yaml、databricks.yml、requirements.txt按 File 29 讲的那样补齐整个 bundle。
## agent.py — Stage 1 (basic chatbot, no tracing, no tools)
from agents import Agent, Runner, set_default_openai_api, set_default_openai_client
from databricks_openai import AsyncDatabricksOpenAI
import os
MODEL_SERVICE = os.getenv("MODEL_SERVICE")
set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True))
set_default_openai_api("responses")
agent = Agent(
name="Simple Chatbot",
instructions="You are a helpful assistant. Answer the user's questions clearly and concisely.",
model=MODEL_SERVICE,
)
async def run_agent(messages: list[dict]) -> str:
result = await Runner.run(agent, messages)
return result.final_output
Deployment is the same two-step CLI pattern as File 29 (databricks bundle deploy, then databricks apps deploy), or the equivalent through the Apps UI for a workspace without a Git folder — the demo gives parallel instructions for both, since the DABs UI needs a Git folder and not every lab environment (notably Vocareum) has one by default.
部署方式跟 File 29 一样,走同样的两步 CLI 流程(先databricks bundle deploy,再databricks apps deploy),或者在没有 Git 文件夹的 workspace 里,通过 Apps UI 做等效操作——demo 对两种方式都给了并列的操作说明,因为 DABs UI 需要一个 Git 文件夹,而不是每个实验环境(尤其是 Vocareum)默认都有。
D Stage 2 — Add MLflow Tracing
Four files change. agent.py gains set_trace_processors([]) (stops the Agents SDK sending its own traces to OpenAI), mlflow.openai.autolog() (records each Agents SDK step as a child span), mlflow.set_experiment(experiment_id=...) (targets the DAB-created experiment), and an @mlflow.trace decorator on run_agent() that wraps the whole call in a root span plus tags the trace with agent_name and model_service. databricks.yml adds an experiments resource and grants the app CAN_EDIT on it. app.yaml injects the experiment ID as MLFLOW_EXPERIMENT_ID. pyproject.toml adds mlflow==3.16.1 as a dependency — without it, the app crashes on startup trying to import mlflow.
四个文件要改。agent.py里加上set_trace_processors([])(让 Agents SDK 不再把自己的 trace 发到 OpenAI 去)、mlflow.openai.autolog()(把 Agents SDK 每一步都记录成一个子 span)、mlflow.set_experiment(experiment_id=...)(指向 DAB 创建好的那个 experiment),还在run_agent()上加了一个@mlflow.trace装饰器,把整次调用都包进一个根 span 里,再给这条 trace 打上agent_name和model_service标签。databricks.yml加一个experiments资源,给 app 授予对它的CAN_EDIT权限。app.yaml把 experiment ID 当作MLFLOW_EXPERIMENT_ID注入进去。pyproject.toml加上mlflow==3.16.1作为依赖——没有它,app 一启动就会因为 import 不到mlflow而崩掉。
## agent.py — Stage 2 additions (tracing wired in)
from agents.tracing import set_trace_processors
import mlflow
set_trace_processors([]) # stop sending Agents SDK traces to OpenAI
mlflow.set_tracking_uri("databricks")
mlflow.openai.autolog() # records each Agents SDK step as a child span
mlflow.set_experiment(experiment_id=os.getenv("MLFLOW_EXPERIMENT_ID"))
@mlflow.trace(name="mlflow_chatbot_run", span_type="AGENT")
async def run_agent(messages: list[dict]) -> str:
mlflow.update_current_trace(tags={"agent_name": agent.name, "model_service": MODEL_SERVICE})
result = await Runner.run(agent, messages)
return result.final_output
When the experiment stores traces in Unity Catalog, MLflow writes them to four tables in <catalog>.agent_deployment (_otel_spans, _otel_annotations, _otel_logs, _otel_metrics). The app's service principal needs Can select and modify on all four, or it cannot write traces — the Apps-UI path in this demo has you add all four tables as resources by hand, one table-N resource key at a time. This is a real, easy-to-miss step: redeploying with just the experiment resource added is not enough.
E Stage 3 — Add MCP Tools
agent.py's final version adds a WorkspaceClient, builds the URL of the Databricks-provided SQL MCP ({host}/ai-gateway/mcp-services/system.ai.dbsql), and wraps each request in async with McpServer(url=..., workspace_client=ws, name="dbsql") as mcp_server: — opening the connection per request, not once at startup, so concurrent requests never share one connection. The agent is constructed inside that block with mcp_servers=[mcp_server], so the SDK lists the MCP's tools (here, execute_sql) at runtime. databricks.yml adds a variables block for the catalog name and warehouse lookup, plus two new resources: SELECT on the listings table and CAN_USE on the warehouse. No explicit grant is needed for system.ai.dbsql itself — all workspace users can already call Databricks-provided MCPs.
agent.py最终版本加了一个WorkspaceClient,拼出 Databricks 提供的 SQL MCP 的 URL({host}/ai-gateway/mcp-services/system.ai.dbsql),然后把每一次请求都包进async with McpServer(url=..., workspace_client=ws, name="dbsql") as mcp_server:里——这个连接是按每次请求打开的,不是在启动时打开一次,所以并发请求永远不会共用一个连接。Agent 就是在这个代码块里面构建的,带着mcp_servers=[mcp_server],这样 SDK 就会在运行时去列出这个 MCP 的工具(这里是execute_sql)。databricks.yml加了一个variables块来放 catalog 名字和 warehouse 查找,外加两个新资源:对 listing 表的SELECT和对 warehouse 的CAN_USE。system.ai.dbsql本身不需要专门授权——所有 workspace 用户本来就能调用 Databricks 提供的 MCP。
## agent.py — Stage 3 additions (SQL MCP tool, per-request connection)
from databricks.sdk import WorkspaceClient
from databricks_openai.agents import McpServer
LISTINGS_TABLE = os.getenv("LISTINGS_TABLE")
ws = WorkspaceClient()
DBSQL_URL = f"{ws.config.host}/ai-gateway/mcp-services/system.ai.dbsql"
INSTRUCTIONS = (
"You are a helpful assistant. "
f"For questions about San Francisco Airbnb listings, query {LISTINGS_TABLE} with the execute_sql tool."
)
@mlflow.trace(name="tool_calling_chatbot_run", span_type="AGENT")
async def run_agent(messages: list[dict]) -> str:
mlflow.update_current_trace(tags={"agent_name": "Tool-calling Chatbot", "model_service": MODEL_SERVICE})
async with McpServer(url=DBSQL_URL, workspace_client=ws, name="dbsql", timeout=60.0) as mcp_server:
agent = Agent(
name="Simple Chatbot", instructions=INSTRUCTIONS,
model=MODEL_SERVICE, mcp_servers=[mcp_server],
)
result = await Runner.run(agent, messages)
return result.final_output
After redeploying, a query that triggers the tool ("What is the average price for listings in the Mission neighborhood?") produces a trace showing the root tool_calling_chatbot_run span, one or more execute_sql spans (the agent may run a quick exploratory query before the real one — both are visible), and Response spans before and after each tool call. Nothing about the tracing code changed between Stage 2 and Stage 3 — mlflow.openai.autolog() records each MCP tool call as part of the same trace tree automatically.
重新部署之后,一个会触发工具调用的问题(比如说"Mission 社区的 listing 平均价格是多少")会产生一条 trace,里面有根 span tool_calling_chatbot_run、一个或多个execute_sql span(agent 可能会先跑一个探索性的小查询,然后再跑真正要的那个——两次都能看到),还有每次工具调用前后的Response span。从 Stage 2 到 Stage 3,tracing 相关的代码一个字没改——mlflow.openai.autolog()会自动把每一次 MCP 工具调用记录成同一棵 trace 树的一部分。
F-G Filter Traces by Tag, and Clean Up
Mixing tool-using and non-tool queries through the chat UI and then filtering the Traces tab by the agent_name or model_service tag shows the real value of trace metadata: both kinds of trace share the same root span and tags, and only the tool-call spans differ — the demo's explicit point is that the app records each request as a trace, not an MLflow run; a trace is the execution graph of one request, and tags on it are what let you filter and compare many requests over time. Cleanup is simply deleting the app from the Apps page and, optionally, the experiment — or databricks bundle destroy if deployed via CLI, which removes both together.
在聊天 UI 里混着发一些会用到工具的问题和不会用到工具的问题,然后在 Traces 标签页里按agent_name或model_service标签过滤,就能看出 trace 元数据真正的价值:两种 trace 共用同一个根 span 和同一套标签,只有工具调用的 span 不一样——demo 特意强调的一点是,app 记录的是每一次请求的trace,而不是 MLflow 的run;一条 trace 就是一次请求的执行图,而 trace 上的标签正是用来在大量请求里做筛选和对比的东西。清理工作就是去 Apps 页面删掉这个 app,顺便删掉 experiment——或者如果是用 CLI 部署的,用databricks bundle destroy一次性把两者一起删掉。
CCAR-P crosswalk
- D3 (integration) — the three-stage build (bare → traced → tool-calling) is the clean minimal example of adding integration surface incrementally: each stage's new code is additive and nothing earlier breaks, which is the kind of integration-sequencing judgment D3 scenario questions probe.
- D5 (governance/safety/risk) — the UC trace-table permission step (SELECT + MODIFY, explicitly, not ALL_PRIVILEGES) is a concrete, exam-relevant example of the "least-sufficient grant, not a broad one" pattern that recurs across the course's governance material.
This three-stage build is the closest thing in the whole course to a literal template for a first FM Insight production agent: Stage 1 is "does the agent even run as an App," Stage 2 is "can I see what it did" (the audit-relevant question for anything touching an audit-opinion number), Stage 3 is "can it safely query governed data" (the GFEBS/Navy ERP equivalent of the listings table, reached through a scoped MCP with explicit SELECT, not a blanket grant). Building FM Insight's first agent in this same order — deploy, then trace, then tool — gives a demonstrable artifact at every stage instead of one large all-or-nothing delivery, which is the same "fast, visible win" argument Day 2 Part 1's adoption plan made for Phase 0.
这个三阶段构建,大概是整门课里最接近"FM Insight 第一个生产 agent 该怎么搭"的字面模板了:Stage 1 是"这个 agent 能不能先跑起来成为一个 App",Stage 2 是"我能不能看到它刚才做了什么"(这是碰到任何审计意见相关数字时都绕不开的审计问题),Stage 3 是"它能不能安全地查受治理的数据"(对应 GFEBS/Navy ERP 的,就是这里的 listing 表,通过一个限定范围、明确 SELECT 权限而不是一股脑全给的 MCP 来访问)。按这个顺序——先部署、再 trace、再接工具——来搭 FM Insight 的第一个 agent,每一阶段都能拿出一个可以展示的东西,而不是等一个大而全、一次性交付的东西,这跟 Day 2 第一部分那份采用计划给 Phase 0 的"快速、看得见的小胜利"是同一个道理。
File 31 Lecture — Tool Integration and Observability
A Model Context Protocol
A1. MCP is "a USB-C port for AI": a standardized interface so any compliant client and server can connect, instead of every tool integration needing bespoke API wrappers, auth handling, and response parsing. It follows a client-server architecture with three participants: the Host (the AI application managing one or more clients, e.g. a Databricks App), the Client (maintains one dedicated connection per server), and the Server (exposes tools, resources, or prompts — in practice, tools are the dominant primitive agents use).
A1. MCP 就是"AI 世界的 USB-C 接口":一个标准化的接口,让任何符合协议的客户端和服务端都能互相连上,而不是每接一个工具都要专门写一套 API 封装、认证处理、响应解析。它走的是客户端-服务端架构,三个参与者:Host(管理一个或多个客户端的 AI 应用,比如一个 Databricks App)、Client(每个 server 维护一条专属连接)、Server(暴露 tool、resource 或 prompt——实际用起来,tool 是 agent 最常用的那个原语)。
| Type | Description | Example |
|---|---|---|
| Databricks-provided | MCPs in system.ai, hosted by Databricks — nothing to run | system.ai.dbsql, system.ai.genie_one_mcp, system.ai.github |
| External | A self-hosted or third-party MCP server you register | A partner's MCP server |
| Custom | Your own MCP server, built on Databricks Apps and registered | Domain-specific tools, a REST API exposed as MCP tools |
An MCP on Databricks is a Unity Catalog object with a three-level name (e.g. system.ai.github); agents reach it through Unity Gateway, which checks EXECUTE on the MCP plus USE CATALOG/USE SCHEMA on its catalog and schema — the same governance primitive File 29's Unity Gateway section named, applied specifically to tool access. A3. As of protocol version 2026-07-28, MCP is stateless: no open/close handshake, each request stands alone. Databricks' own MCPs still perform the earlier initialize handshake (versions up to 2025-11-25), and McpServer handles it for you. The host — not the protocol — decides when to call a tool; errors with invalid arguments return isError: true so the model can retry, while an unknown tool or malformed request returns a JSON-RPC error. A4. In a deployed app, open the MCP connection per request (never shared across concurrent requests), and grant the service principal EXECUTE on the MCP plus whatever access its tools need underneath (e.g. SELECT on a table a SQL tool reads).
Databricks 上的一个 MCP 是一个带三段式名字的 Unity Catalog 对象(比如system.ai.github);agent 通过 Unity Gateway 访问它,Gateway 会检查对这个 MCP 的EXECUTE权限,还有对它所在 catalog 和 schema 的USE CATALOG/USE SCHEMA权限——这跟 File 29 Unity Gateway 那一节讲的治理原语是同一个,只是专门用在工具访问上。A3. 从协议版本 2026-07-28 开始,MCP 是无状态的:没有打开/关闭的握手,每次请求都是独立的。Databricks 自己的 MCP 仍然会做早期那种initialize握手(2025-11-25 之前的版本都有),McpServer会替你处理好这个。决定什么时候调用工具的是 host(应用),不是协议本身;参数不对导致工具失败,会返回isError: true,让模型有机会自己纠正重试;而未知工具或格式错误的请求,会返回一个 JSON-RPC 错误。A4. 在已部署的 app 里,MCP 连接要按每次请求打开(永远不要在并发请求之间共用),还要给 service principal 授予对 MCP 的EXECUTE权限,加上它的工具底层需要的任何访问权限(比如一个 SQL 工具要读的表上的SELECT)。
B Observability with MLflow Tracing
B1. A trace is a tree of spans, each capturing inputs/outputs, timing, span type, and status. Automatic tracing (mlflow.openai.autolog()) covers the agent's model and tool calls through the OpenAI SDK with zero extra code; custom spans (@mlflow.trace or mlflow.start_span()) trace your own logic — preprocessing, business rules — into the same trace tree. A typical agent trace has a root AGENT span with child CHAT_MODEL, TOOL, and RETRIEVER spans.
B1. 一条 trace 就是一棵 span 组成的树,每个 span 都记录输入/输出、时间、span 类型、状态。自动 tracing(mlflow.openai.autolog())通过 OpenAI SDK 自动覆盖 agent 的模型调用和工具调用,一行额外代码都不用写;自定义 span(@mlflow.trace或mlflow.start_span())把你自己的逻辑——预处理、业务规则——也 trace 进同一棵树里。一条典型的 agent trace,根上是一个AGENT span,下面挂着CHAT_MODEL、TOOL、RETRIEVER这些子 span。
B2. Traces in production log to an MLflow Experiment, the hub where observability and evaluation data meet — scorers evaluate traces, not raw requests; any agent producing MLflow traces can use the same scorer infrastructure. Three settings matter at real traffic: install mlflow-tracing (a smaller package with just what tracing needs) instead of full mlflow; MLFLOW_ENABLE_ASYNC_TRACE_LOGGING logs in the background so requests don't wait (on by default outside notebooks); MLFLOW_TRACE_SAMPLING_RATIO exports only a share of traces (default 1.0, every trace).
B2. 生产环境里的 trace会记录到一个 MLflow Experiment 里,这是观测数据和评测数据汇合的地方——scorer 评测的是 trace,不是原始请求;任何能产出 MLflow trace 的 agent,都能用上同一套 scorer 基础设施。真实流量下,三个设置很关键:安装mlflow-tracing(一个只带 tracing 所需内容的精简包)而不是完整的mlflow;MLFLOW_ENABLE_ASYNC_TRACE_LOGGING在后台记录日志,这样请求不用等(在 notebook 之外默认开启);MLFLOW_TRACE_SAMPLING_RATIO只导出一部分 trace(默认1.0,全部导出)。
Databricks recommends UC Delta-table storage, in OpenTelemetry format, for new and production workloads: unlimited retention (vs. 100,000 traces per experiment in the fallback store), SQL-queryable, governed by UC schema/table permissions rather than experiment ACLs. Bind it only when the experiment is created (via trace_location=UnityCatalog(...)) — it cannot be added later, though multiple experiments can share one UC location. This creates four Delta tables (_otel_spans, _otel_annotations, _otel_logs, _otel_metrics). Access needs explicit MODIFY + SELECT — ALL_PRIVILEGES is not sufficient. Ingestion is capped at 200 traces/second/workspace and 100 MB/second/table.
CCAR-P crosswalk
- D3 (integration) — observability at scale is a named weak spot in Peter's study log, and File 31 B2-B3 (async logging, sampling ratio, UC storage limits, the per-table SELECT+MODIFY grant) is the most direct, exam-relevant material in the whole folder for that exact objective.
- D3 — integration protocol choice (another named weak spot): MCP's stateless-as-of-2026-07-28 design, with Databricks' own MCPs still keeping the older initialize handshake for backward compatibility, is a concrete example of a protocol-versioning tradeoff an exam scenario could probe.
The UC-trace-storage governance model (SELECT + MODIFY explicitly, never ALL_PRIVILEGES, on a per-table basis) is a direct answer to how FM Insight's own agent decisions should be retained for DODIG review: an agent trace touching a GFEBS or Navy ERP balance needs the same explicit, auditable grant structure as the underlying financial table itself, not a broader convenience grant that would show up as an undocumented control gap in an A-123 test. The 200 traces/second/workspace cap is also a real capacity-planning number worth validating against FM Insight's expected production volume before committing to a single shared workspace for the whole FM community.
UC trace 存储这套治理模型(按表明确授予 SELECT + MODIFY,绝不给 ALL_PRIVILEGES)直接回答了 FM Insight 自己的 agent 决策该怎么留存、以供 DODIG 审查这个问题:一条碰到 GFEBS 或 Navy ERP 余额的 agent trace,需要跟底层财务表本身一样明确、可审计的授权结构,而不是一个图方便给的更宽泛的权限——那种权限在 A-123 测试里会直接暴露成一个没有文档记录的控制缺口。每 workspace 每秒 200 条 trace 的上限,也是一个值得拿去对照 FM Insight 预期生产流量的真实容量规划数字,值得在决定把整个 FM 社区都放进同一个共享 workspace 之前先验证清楚。
File 32 Demo — Tracing for Production Agents
Where File 30 showed tracing as a one-line add-on, File 32 is entirely about what production-grade tracing needs beyond that: manual spans with semantic types, custom attributes and trace metadata, multi-turn session grouping, and programmatic trace search in both Python and SQL. The experiment here is bound to Unity Catalog from the start, so every technique in this file is one you can actually query afterward.
File 30 把 tracing 展示成一行代码就能加上去的东西;File 32 则完全是在讲生产级 tracing 在这基础上还需要什么:带语义类型的手动 span、自定义属性和 trace 元数据、多轮会话分组,以及用 Python 和 SQL 两种方式对 trace 做程序化检索。这个文件里的 experiment 从一开始就绑定到 Unity Catalog,所以这个文件里讲的每一种技巧,事后都真的可以拿去查。
B Manual Tracing with Decorators and Span Types
span_type on @mlflow.trace is a semantic label — not cosmetic — that tells MLflow what kind of GenAI step a function represents, enabling structured trace trees, specialized UI rendering, and downstream scorers that key off span type directly (File 32's own example: RetrievalGroundedness and RetrievalRelevance locate RETRIEVER spans specifically to extract retrieved documents — a judge with no RETRIEVER span to find simply cannot run).
@mlflow.trace上的span_type是一个语义标签——不只是装饰性的——它告诉 MLflow 一个函数代表的是哪种 GenAI 步骤,由此支撑起结构化的 trace 树、UI 里的专门渲染方式,还有下游那些直接认 span 类型的 scorer(File 32 自己举的例子:RetrievalGroundedness和RetrievalRelevance专门去找RETRIEVER span 来提取检索到的文档——一个判官如果找不到 RETRIEVER span,根本就跑不起来)。
| span_type | Use for | Example |
|---|---|---|
| AGENT | The top-level orchestrator; usually the root span | def travel_agent(query) -> str: |
| TOOL | UC functions, SQL queries, API calls, utilities the agent invokes | def lookup_weather(city) -> dict: |
| RETRIEVER | A retrieval/AI-search step; required by RetrievalGroundedness and RetrievalRelevance scorers | def search_knowledge_base(query) -> list: |
| CHAT_MODEL | The underlying LLM call; autologging creates this automatically for supported providers | def call_llm(messages) -> str: |
| PARSER | Parsing/formatting/pre-post-processing logic | def extract_json_from_response(raw) -> dict: |
| CHAIN / FUNCTION | A higher-level sequence of steps, or the generic fallback | def rag_pipeline(question) -> str: |
C Production Context — Trace Metadata vs. Span Attributes
Two distinct mechanisms, easy to conflate: trace metadata (mlflow.update_current_trace(session_id=..., user=...)) is for session/user grouping that the Sessions view reads — it must be metadata, not an attribute, for grouping to work. Span attributes (span.set_attributes({...})) are per-request details like app_version or request_source — searchable and filterable via span.attributes.* in mlflow.search_traces(), but not what the Sessions view groups on. Both must be attached while the request runs; neither can be added afterward.
两个很容易被混为一谈、但其实完全不同的机制:trace 元数据(mlflow.update_current_trace(session_id=..., user=...))是给会话/用户分组用的,Sessions 视图读的就是它——分组要起作用,必须是元数据,不能是属性。span 属性(span.set_attributes({...}))是单次请求级别的细节,比如app_version或request_source——可以在mlflow.search_traces()里通过span.attributes.*检索和过滤,但 Sessions 视图不会按它来分组。两者都必须在请求执行期间设置;事后都加不上去。
@mlflow.trace(span_type="CHAIN")
def travel_agent_with_context(user_query: str, user_id: str, session_id: str) -> str:
# Session/user go on the trace for grouping in the Sessions view
mlflow.update_current_trace(session_id=session_id, user=user_id)
# Per-request details stay as span attributes
span = mlflow.get_current_active_span()
span.set_attributes({"app_version": "1.2.0", "request_source": "web_ui"})
weather_info = lookup_weather("london")
response = client.chat.completions.create(model=MODEL_SERVICE, messages=[...], max_tokens=500)
return response.choices[0].message.content
D Multi-Turn Conversation Tracing — Session-Level Grouping
Each turn in a conversation produces its own trace. Sharing the same session_id and user trace metadata across turns, generated once (e.g. str(uuid.uuid4())) and passed into each chat_turn() call, is how MLflow groups them into one conversation in the Sessions view — exactly the mechanism Folder 3's multi-turn judges (ConversationCompleteness, UserFrustration, ConversationalSafety) depend on to see the whole thread rather than one isolated turn.
一次对话里的每一轮都会产生自己的一条 trace。在每一轮里共用同一个session_id和usertrace 元数据——只生成一次(比如str(uuid.uuid4())),然后传进每一次chat_turn()调用里——正是 MLflow 在 Sessions 视图里把它们归并成一次对话的机制,这跟 Folder 3 里那几个多轮判官(ConversationCompleteness、UserFrustration、ConversationalSafety)用来看到整段对话、而不是孤立的一轮的机制,完全是同一个。
E Searching and Filtering Traces — Python and SQL
mlflow.search_traces(locations=[experiment_id], filter_string=..., max_results=...) is the production query API, returning a Pandas DataFrame. Filter on trace.* (status, timing — e.g. trace.status = 'ERROR', trace.execution_time_ms > 5000), span.attributes.* (e.g. app_version), metadata.*, or tag.*, combined with AND. Always add a trace.timestamp_ms bound for UC-backed traces, so each search scans less data. For dashboards and scheduled reports rather than interactive Python analysis, query the same data with SQL: MLflow exposes two views, <prefix>_trace_unified (full span data — needed for anything requiring duration) and <prefix>_trace_metadata (tags and assessments only — faster when span data isn't needed).
mlflow.search_traces(locations=[experiment_id], filter_string=..., max_results=...)是生产环境里的查询 API,返回一个 Pandas DataFrame。可以按trace.*(状态、耗时——比如trace.status = 'ERROR'、trace.execution_time_ms > 5000)、span.attributes.*(比如app_version)、metadata.*或tag.*来过滤,用AND组合。对存在 UC 里的 trace,一定要加上一个trace.timestamp_ms的时间范围限制,这样每次查询扫描的数据才会少一些。如果要做仪表盘和定时报表,而不是交互式的 Python 分析,可以用 SQL 查同一份数据:MLflow 提供两个视图,<prefix>_trace_unified(完整 span 数据——要算耗时之类的就需要它)和<prefix>_trace_metadata(只有标签和评估结果——不需要 span 数据时查得更快)。
-- Count turns per session and their average duration, using the unified view
SELECT trace_metadata:['mlflow.trace.session']::STRING AS session_id,
COUNT(*) AS turns,
ROUND(AVG(execution_duration_ms)) AS avg_duration_ms
FROM {catalog}.{schema}.prod_tracing_trace_unified
WHERE trace_metadata:['mlflow.trace.session'] IS NOT NULL
GROUP BY 1
CCAR-P crosswalk
- D3 — observability at scale (named weak spot): trace metadata vs. span attributes is precisely the kind of "two mechanisms, easy to conflate, only one works for grouping" distinction a D3 scenario question is built to test.
- D4 (evaluation/testing/optimization) — span_type as the contract a downstream scorer depends on (RetrievalGroundedness needing a RETRIEVER span to exist at all) is the clean example of instrumentation choices determining what evaluation is even possible later.
Session-level grouping is the mechanism an FM Insight multi-turn interaction — an analyst going back and forth with the agent while reconciling a Fund Balance with Treasury discrepancy, say — needs in order to be reviewable as one episode rather than a pile of disconnected single-turn traces. And the SQL-queryable trace-metadata view is a direct, no-extra-build answer to the kind of AI/BI dashboard a program office would want over agent activity: which users, which sessions, how long, with what assessments, all queryable the same way any other governed table is.
会话级分组正是 FM Insight 多轮交互所需要的机制——比如一个分析员在核对一笔 Fund Balance with Treasury 差异的时候,跟 agent 来回对话好几轮——这样才能把它当作一个完整的事件来复盘,而不是一堆互相不相关的单轮 trace。而这个可以用 SQL 查的 trace 元数据视图,对于项目办公室想要的那种关于 agent 活动的 AI/BI 仪表盘来说,是一个不需要额外开发的直接答案:哪些用户、哪些会话、用了多久、评估结果是什么,全都能像查任何其他受治理的表一样查出来。
File 33 Lecture — Production Evaluation and Monitoring
In MLflow, a scorer is the evaluation function; a judge is a scorer that uses an LLM to evaluate subjective or nuanced criteria. Judges must be wrapped in scorers to run in the evaluation harness or production monitoring — the same vocabulary Folder 3 used for offline evaluation, now applied continuously to live traffic.
在 MLflow 里,scorer是评测函数;judge是用 LLM 来评测主观或微妙标准的一种 scorer。Judge 必须被包进 scorer 里,才能跑在评测框架或生产监控里——跟 Folder 3 讲离线评测时用的是同一套词汇,现在只是持续套用在真实流量上。
A Scorer Types
| Type | What it is | Ground truth? |
|---|---|---|
| Built-in LLM judges | Ready-to-use: Safety, RelevanceToQuery, Correctness, RetrievalRelevance, RetrievalGroundedness, RetrievalSufficiency, ToolCallEfficiency, ToolCallCorrectness | Varies — Correctness and RetrievalSufficiency need it, most don't |
| Guidelines judges | Pass/fail against plain-English rules you write (Guidelines, or ExpectationsGuidelines for per-row ground-truth rules) | Only the ExpectationsGuidelines variant |
| Custom prompt judges | make_judge(): full control over the prompt template and multi-level quality scales via feedback_value_type | Optional |
| Custom function scorers | @scorer decorator on any self-contained Python function — regex, schema checks, business rules | N/A — arbitrary code |
# The two-step pattern every built-in judge follows
from mlflow.genai.scorers import Safety, ScorerSamplingConfig
safety_judge = Safety(model="databricks:/dbacademy.agent_deployment.judge-model").register(name="my_safety_judge")
safety_judge = safety_judge.start(sampling_config=ScorerSamplingConfig(sample_rate=1.0))
Custom function scorers run remotely and must be fully self-contained: every import inside the function body, defined in a Databricks notebook, no class-based Scorer subclasses, no references to variables or modules outside the function, no type hints requiring imports. @scorer(aggregations=["mean", "min", "max"]) gets experiment-level summary statistics for numeric scorers.
自定义函数 scorer 是远程运行的,所以必须完全自包含:所有import都要写在函数体内部,必须在 Databricks notebook 里定义,不能用基于类的Scorer子类,不能引用函数外部的变量或模块,类型提示也不能需要额外 import。给数值型 scorer 加上@scorer(aggregations=["mean", "min", "max"]),就能拿到 experiment 级别的汇总统计。
B Multi-Turn Judges (Experimental)
Multi-turn judges evaluate entire conversations (sessions grouped via the mlflow.trace.session metadata from File 32 D1), attaching assessments to the first trace in the session. A single-turn safety check can pass every individual response while missing that a user repeated the same question four times — only a conversation-level judge catches that pattern.
多轮判官评测的是整段对话(通过 File 32 D1 讲的mlflow.trace.session元数据分好组的会话),评估结果挂在该会话的第一条 trace 上。单轮的安全检查可能让每一个单独的回答都通过,却完全漏掉"用户把同一个问题重复问了四次"这种情况——只有会话级别的判官才能抓到这种模式。
| Judge | What it evaluates |
|---|---|
| ConversationCompleteness | Whether the agent fully resolved the request across all turns |
| UserFrustration | Repeated questions, escalation language, confusion signals |
| ConversationalSafety | Safety violations emerging only across multiple turns |
| KnowledgeRetention | Whether the agent correctly retains earlier information |
| ConversationalGuidelines | Compliance with provided guidelines throughout |
| ConversationalRoleAdherence | Whether the agent maintains its assigned role throughout |
| ConversationalToolCallEfficiency | Whether tool usage across the conversation was efficient |
C Online Evaluation (Beta)
Production monitoring runs as a background job, separate from your notebook process. When traces are UC-backed, that job reads them through a SQL warehouse set on the experiment via the mlflow.monitoring.sqlWarehouseId tag — set with set_databricks_monitoring_sql_warehouse_id(), before registering any scorer, or the job fails. Setting MLFLOW_TRACING_SQL_WAREHOUSE_ID is not a substitute — it only applies to the process that set it, not the separately-running job.
生产监控跑在一个后台任务里,跟你 notebook 的进程是分开的。当 trace 存在 UC 里时,这个任务是通过设在 experiment 上的mlflow.monitoring.sqlWarehouseId标签、经由一个 SQL warehouse 来读取数据的——用set_databricks_monitoring_sql_warehouse_id()设置,而且必须在注册任何 scorer之前设好,不然这个任务就会失败。设置MLFLOW_TRACING_SQL_WAREHOUSE_ID不能替代它——那只对设置它的那个进程有效,不影响单独运行的那个后台任务。
| Tier | Rate | Reasoning |
|---|---|---|
| Critical | 100% | Safety/security scorers — the cost of missing a violation far outweighs evaluation cost |
| Expensive | 5-20% | LLM judges that make their own model calls; 5% still gives statistically meaningful signal at scale |
| Development | 30-50% | While tuning the agent or judge — higher for fast feedback, dial back once signal is stable |
| Custom | Variable | Lightweight function scorers can run at higher rates |
Maximum 20 scorers per experiment. The immutability pattern matters in practice: every lifecycle method returns a new instance, so calling scorer.stop() without reassigning leaves the local variable pointing at the old, still-running state.
每个 experiment 最多 20 个 scorer。不可变模式在实际用起来很关键:每个生命周期方法都会返回一个新实例,所以如果调用了scorer.stop()却没有重新赋值,本地变量指向的还是旧的、仍在运行的那个状态。
D Scorer Management
get_scorer(name=...) retrieves any registered scorer by name — essential for managing a scorer created in a different notebook session or through the UI, since it works identically for UI-created and API-created scorers. Stopping pauses a running scorer (restartable, history preserved); the background job keeps running until all scorers in the experiment are stopped. Deleting permanently removes it (running or stopped); historical assessments remain on their traces either way.
get_scorer(name=...)可以按名字取回任何已注册的 scorer——这对管理一个在别的 notebook session 里或通过 UI 创建的 scorer 很关键,因为它对 UI 创建的和 API 创建的 scorer 处理方式完全一样。停止会暂停一个正在运行的 scorer(可以重新启动,历史记录保留);只要 experiment 里还有一个 scorer 没停,后台任务就会一直跑着。删除永久移除它(不管正在跑还是已停止);两种情况下,历史评估结果都会留在对应的 trace 上。
E Backfill and Trace Storage
Metric backfill (backfill_scorers, from databricks.agents.scorers) retroactively applies scorers to traces logged before the scorer existed — a one-shot job, distinct from the ongoing scheduled job .start() creates. Scorers must already be registered and started. Pass name strings to use registered sample rates, or BackfillScorerConfig objects for custom rates and an explicit start_time/end_time — with neither, backfill covers only the last seven days.
指标回填(backfill_scorers,来自databricks.agents.scorers)把 scorer 追溯性地套用到这个 scorer 存在之前就已经记录下来的 trace 上——这是一次性的任务,跟.start()创建的那个持续运行的定时任务不一样。Scorer 必须已经注册并启动过。可以传字符串名字来用已注册的采样率,也可以传BackfillScorerConfig对象来自定义采样率,并显式指定start_time/end_time——两个都不传的话,回填只会覆盖最近七天。
| Traces in Unity Catalog | Traces in the experiment | |
|---|---|---|
| Storage limit | Unlimited | 100,000 traces per experiment |
| Query options | MLflow UI/SDK, plus SQL, AI/BI dashboards, Genie Code, Spark | MLflow UI and SDK only |
| Governance | Unity Catalog schema/table permissions | Experiment permissions |
| Format | OpenTelemetry — readable by other OTel tools | MLflow only |
CCAR-P crosswalk
- D4 (evaluation/testing/optimization) — eval dataset/framework design (named weak spot): the four-scorer-type taxonomy, plus the sampling-tier table, is the single clearest statement in the whole course of "which evaluation tool fits which cost/risk tradeoff," which is exactly the judgment D4 tests.
- D5 (governance/safety/risk) — LLM risk/failure modes (named weak spot): "a single-turn safety check can pass every response while missing a four-times-repeated question" is a precise, nameable failure mode an exam scenario would test recognition of.
- D6 (stakeholder comm & lifecycle): the register/start/update/stop/delete lifecycle, with its immutability-pattern gotcha, is lifecycle-management material in the literal sense D6 names.
The sampling-tier logic maps directly onto an FM Insight production monitoring plan: a GFEBS/Navy ERP balance-accuracy judge is "Critical" (100%, matching how the course treats Safety), while an expensive multi-turn completeness judge over a KSD-drafting conversation could run at the "Expensive" 5-20% tier — the same cost/coverage tradeoff, applied to audit-relevant correctness instead of generic safety. And backfill is the concrete mechanism for a scenario Peter will face in practice: FM Insight ships with a narrower set of scorers at first, and six months later the team wants to retroactively score every historical GFEBS query trace against a newly-written guideline judge, without rerunning a single real query against the production system.
采样分级这套逻辑,可以直接套用到 FM Insight 的生产监控计划上:一个判断 GFEBS/Navy ERP 余额准确性的判官属于"关键"级(100%,跟课程对待 Safety 的方式一样),而一个评测 KSD 撰写对话完整性的昂贵多轮判官,可以跑在"昂贵"那一档(5-20%)——同样的成本/覆盖权衡,只是用在审计相关的正确性上,而不是通用的安全性上。而回填正是 Peter 实际工作中会碰到的那种场景的具体解法:FM Insight 一开始只上线一小部分 scorer,六个月之后团队想把所有历史 GFEBS 查询 trace,都拿去对照一个新写的准则判官重新打分一遍,而且完全不用在生产系统上把任何一条真实查询重跑一次。
File 34 Lab — Online Evaluation with Multi-Turn Conversations
Scenario: Peter is the ML engineer for a production travel agent whose users report incomplete answers and conversations that take too many turns. The lab's build→verify structure walks through deploying three multi-turn judges in code (ConversationCompleteness at 0.5, UserFrustration at 0.5, ConversationalSafety at 1.0, all registered against the course judge model), adding a fourth judge entirely through the UI (ConversationalGuidelines named professional, with the single guideline "The interaction must be professional"), and a fifth scorer as custom code (a response_length function scorer with mean/min/max aggregations, handling the possibility that UC-stored traces hand outputs back as JSON text rather than a dict).
场景:Peter 是一个生产级旅行助手 agent 的 ML 工程师,用户反馈回答不完整、对话要反复好几轮才能解决问题。实验按"搭建→验证"的结构,先用代码部署三个多轮判官(ConversationCompleteness采样率 0.5,UserFrustration采样率 0.5,ConversationalSafety采样率 1.0,全部挂在课程的判官模型上),再完全通过 UI 加上第四个判官(ConversationalGuidelines,取名professional,只有一条准则:"这次互动必须保持专业"),最后再加上第五个 scorer,是一段自定义代码(一个带mean/min/max汇总的response_length函数 scorer,还要处理 UC 存储的 trace 可能把outputs以 JSON 文本而不是 dict 形式传回来的情况)。
The critical first step, easy to get backwards, is A1: set the monitoring SQL warehouse on the experiment before registering any scorer — set_databricks_monitoring_sql_warehouse_id(sql_warehouse_id=...), writing the mlflow.monitoring.sqlWarehouseId tag the separately-running job reads. Skip it and every scorer registration later fails. After all five scorers are live, the Trace Metrics Computation Job (named [experiment_id] Trace Metrics Computation Job in Jobs & Pipelines, running on a fixed ~15-minute schedule) evaluates them together; list_scorers() is how you confirm all five show as active and at what rate; get_scorer() + .update(sampling_config=...) tunes a rate afterward; and cleanup is the full lifecycle in reverse — .stop() each (fetching the UI-created professional judge with get_scorer() since there's no local variable for it), then delete_scorer() on every name from list_scorers(), verifying the list comes back empty.
最关键、也最容易搞反顺序的第一步,是A1:在注册任何 scorer 之前,先给 experiment 设好监控用的 SQL warehouse——set_databricks_monitoring_sql_warehouse_id(sql_warehouse_id=...),写下的是那个单独运行的任务要读的mlflow.monitoring.sqlWarehouseId标签。跳过这一步,后面每一次注册 scorer 都会失败。五个 scorer 都上线之后,Trace Metrics Computation Job(在 Jobs & Pipelines 里叫[experiment_id] Trace Metrics Computation Job,按固定的约 15 分钟一次的计划跑)会把它们放在一起评测;list_scorers()用来确认五个全都显示为活跃状态、各自的采样率是多少;get_scorer()配合.update(sampling_config=...)可以事后调采样率;清理工作就是把整个生命周期反着走一遍——先对每一个调用.stop()(那个通过 UI 创建的professional判官没有本地变量,要先用get_scorer()取回来),再对list_scorers()里的每个名字调用delete_scorer(),最后确认列表真的是空的。
Multi-turn judges run only after a conversation is considered complete — by default, 5 minutes of inactivity on that session ID. The lab's setup script needs to have run at least 5 minutes before the job runs, or sessions will look incomplete and judges won't fire.
CCAR-P crosswalk
- D6 (stakeholder comm & lifecycle): three deployment paths for the same evaluation capability — code, UI, custom function — landing on one experiment and one job run, is a direct illustration of "lifecycle management doesn't require one uniform tool," which is the kind of nuance D6 questions reward.
The mixed code/UI/custom-scorer deployment pattern matters for FM Insight's actual team shape: a data scientist can register judges in code, a less-technical SME reviewer can add a guideline judge entirely through the UI with no Python, and a third team member can ship a one-off business-rule scorer — all three landing on the same experiment, evaluated by the same job, with no coordination overhead beyond the shared SQL-warehouse-first setup step.
这种混合了代码、UI、自定义 scorer 的部署方式,对 FM Insight 实际的团队构成很有意义:数据科学家可以用代码注册判官,一个技术背景不那么深的 SME 评审员完全可以通过 UI 加一个准则判官而不用写一行 Python,第三个团队成员也可以上线一个一次性的业务规则 scorer——三者都落在同一个 experiment 里,被同一个任务评测,彼此之间不需要额外协调,唯一的前提就是那个共享的、必须先做好的 SQL warehouse 设置步骤。
File 35 Lab — Backfilling and Querying Multi-Turn Conversations
The setup script pre-creates a UC-backed experiment with 3 multi-turn sessions (9 traces: a Japan trip-planning session with thorough answers as the baseline, a flight-booking session with vague incomplete answers, and a hotel-cancellation session where the agent ignores the request entirely) and a deployed ConversationCompleteness judge at 70% sampling. Peter's job is to inspect that setup in the UI, run the already-created Trace Metrics Computation Job once manually, confirm Session 1 passes while Sessions 2-3 get flagged, then add a new Safety scorer and backfill it onto the 9 existing traces — because .start() only evaluates new incoming traces, and these nine already exist.
Setup 脚本预先建好一个绑定了 UC 的 experiment,带 3 个多轮会话(9 条 trace:一个日本行程规划会话,回答详尽,作为基准;一个订机票会话,回答含糊不清、不完整;一个取消酒店预订会话,agent 完全不理这个请求),还部署了一个采样率 70% 的ConversationCompleteness判官。Peter 的任务是在 UI 里检查这套设置,手动运行一次已经创建好的 Trace Metrics Computation Job,确认 Session 1 通过、Session 2-3 被标记出来,然后再加一个新的Safety scorer,把它回填到已有的这 9 条 trace 上——因为.start()只评测新进来的 trace,而这九条早就存在了。
from mlflow.genai.scorers import Safety, ScorerSamplingConfig
from databricks.agents.scorers import backfill_scorers, BackfillScorerConfig
safety = Safety(model=judge_model).register(name="safety_check")
safety = safety.start(sampling_config=ScorerSamplingConfig(sample_rate=1.0))
job_id = backfill_scorers(scorers=[BackfillScorerConfig(scorer=safety, sample_rate=1.0)])
print(f"Backfill job ID: {job_id}")
Two distinct background jobs are created across the two labs — a Trace Metrics Computation Job (ongoing, scheduled, evaluates new incoming traces) and a Metric Backfill Computation Job (one-shot, evaluates historical traces once). After the backfill completes, mlflow.search_traces() confirms assessments landed; the real payoff is a single SQL query over the <prefix>_trace_metadata view that lists every session's user, assessment name, and value in one shot by exploding the assessments array and filtering out scorer errors — the exact kind of query an AI/BI dashboard would run, and one the lab notes works with no copying or syncing because the UC tables are the trace store, not a copy of it.
两个实验里一共创建了两种不同的后台任务——一个Trace Metrics Computation Job(持续运行、按计划触发,评测新进来的 trace)和一个Metric Backfill Computation Job(一次性的,把历史 trace 评测一遍就结束)。回填完成之后,用mlflow.search_traces()确认评估结果真的落地了;真正有用的是那一条对<prefix>_trace_metadata视图跑的 SQL 查询,把assessments数组展开、过滤掉 scorer 报错的那些,一次性列出每个会话的用户、评估名字和结果——这正是一个 AI/BI 仪表盘会跑的那种查询,而且实验特别指出,这里不需要任何复制或同步,因为 UC 里的表本身就是 trace 的存储地,不是存储地的一份拷贝。
SELECT trace_metadata:['mlflow.trace.session']::STRING AS session_id,
trace_metadata:['mlflow.trace.user']::STRING AS user_id,
a.assessment_name,
a.feedback.value AS value
FROM {catalog}.{schema}.backfill_traces_trace_metadata
LATERAL VIEW explode(assessments) t AS a
WHERE a.feedback.error IS NULL
ORDER BY user_id, a.assessment_name
CCAR-P crosswalk
- D4 (evaluation/testing/optimization) — A/B testing / eval design (named weak spot area): scheduled job vs. backfill job is a clean conceptual pair — ongoing vs. one-shot, forward-looking vs. retroactive — worth holding as a fixed distinction rather than two instances of "a job that scores things."
- D3 (integration) — observability at scale: the trace-table permission model (SELECT + MODIFY as ordinary Unity Catalog grants, lineage and auditing included for free) is the governance answer to "how do traces fit into an existing UC-governed data estate," not a bolt-on exception.
Backfill is the realistic rollout path for FM Insight's own scorer coverage: ship a narrow first judge, accumulate months of GFEBS/Navy ERP agent traces in production, and only later — once a specific audit-remediation finding sharpens exactly what "correct" means for a given query type — write the guideline judge that captures it and apply it retroactively to everything already logged, rather than needing perfect foresight on day one. The UC table permission model (table-by-table SELECT + MODIFY) also directly answers how FM Insight's own trace tables should sit inside Advana's existing Unity Catalog governance once that rollout is further along there.
回填正是 FM Insight 自己 scorer 覆盖面的现实推进路径:先上线一个范围很窄的判官,让 GFEBS/Navy ERP 的 agent trace 在生产环境里积累上几个月,等到某个具体的审计整改发现,把某种查询类型的"正确"到底是什么意思说清楚了,再去写一个能捕捉到这一点的准则判官,并把它追溯性地套用到已经记录下来的所有数据上——而不需要在第一天就有完美的预见能力。UC 表权限模型(逐表授予 SELECT + MODIFY)也直接回答了,等 Advana 那边的 Unity Catalog 治理进一步落地之后,FM Insight 自己的 trace 表该怎么放进那套既有治理体系里。
File 36 Lecture (Appendix, optional) — Agent Bricks CLI
The Agent Bricks CLI (databricks-agentbricks) splits agent-building into two parts: you write application logic (model choice, prompts, custom Python tools), and the CLI manages Databricks resources (model access, managed memory, managed sessions, managed tools declared in agent.toml, MLflow tracing on by default, deployment and permissions). It is a code-first alternative to the Apps+DABs pattern Files 29-30 built by hand, not a replacement for the tracing, scorer, and evaluation material in Files 31-35 — a CLI-deployed agent's traces land in a standard MLflow experiment, so every technique in this folder still applies.
Agent Bricks CLI(databricks-agentbricks)把建 agent 这件事拆成了两部分:你写应用逻辑(选模型、写 prompt、自定义 Python 工具),CLI 负责管理 Databricks 资源(模型访问权限、托管的 memory、托管的 session、在agent.toml里声明的托管工具、默认开启的 MLflow tracing、部署和权限)。这是一种代码优先的替代方案,对标的是 File 29-30 手动搭出来的 Apps+DABs 那套模式,而不是取代 File 31-35 讲的 tracing、scorer、评测那套东西——用 CLI 部署的 agent 产生的 trace,照样落在一个标准的 MLflow experiment 里,所以这个 Folder 里讲的每一种技巧,照样全都适用。
| Apps + DABs (Files 29-30) | Agent Bricks CLI | |
|---|---|---|
| Resource wiring | Declared in databricks.yml | Declared in agent.toml |
| Deploy | databricks bundle deploy, then databricks apps deploy | agentbricks deploy |
| MCP tools | Connected in agent code with McpServer | agentbricks tools add mcp <service>, connected at runtime |
| Tracing | Added with autologging + @mlflow.trace | On by default, per-project MLflow experiment |
For an agent already built with LangGraph or the OpenAI Agents SDK, agentbricks init --framework <fw> --existing . does not rewrite code itself — it writes an agent-bricks-migrate/ directory with migration instructions for a coding agent (Claude Code, Codex) to follow, which then converts the project to agent.toml plus a DurableAgentServer entrypoint; agentbricks doctor . checks the conversion without running code or contacting Databricks. Switching to a managed session store does not carry over existing conversation history — a real decision point to make explicitly before migrating, not something the tooling resolves for you.
对于一个已经用 LangGraph 或 OpenAI Agents SDK 搭好的 agent,agentbricks init --framework <fw> --existing .本身不会去改写代码——它会写出一个agent-bricks-migrate/目录,里面是给编码 agent(Claude Code、Codex)跟着做的迁移说明,后者会把项目转换成agent.toml加一个DurableAgentServer入口;agentbricks doctor .在不运行代码、不联系 Databricks 的前提下检查这次转换做得对不对。切换到托管的 session store,不会把已有的对话历史一起带过去——这是迁移之前需要明确做出的一个真实决策点,工具不会替你解决。
CCAR-P crosswalk
- D7 (dev productivity & ops enablement) — Agent Bricks CLI is the clearest D7 material in the entire course: a declarative-source-of-truth tool whose entire purpose is reducing the hand-written infrastructure surface, named explicitly against the DABs alternative it's trying to make faster.
- D1 (architecture) — "the CLI is a code-first alternative, not a replacement for the tracing/scorer layer" is a composability judgment worth having crisp for an exam question that tries to frame two tools as mutually exclusive when they're actually orthogonal.
Because the CLI is Beta and this appendix is explicitly optional, it is not the near-term build path for FM Insight — but the agent.toml declarative-resource pattern is worth tracking as it matures, since "one file, not a hand-wired databricks.yml + app.yaml + agent.py triangle" would meaningfully lower the barrier for the less code-heavy members of Peter's three teams to stand up their own scoped agents inside the FM Insight platform, once the CLI leaves Beta and Advana's environment catches up to supporting it.
因为这个 CLI 还在 Beta 阶段,而且这一节本身就被课程明确标注为选读内容,它暂时不是 FM Insight 近期的建设路径——但agent.toml这种声明式资源的模式,随着它逐渐成熟,值得持续关注,因为"一个文件,而不是一个手工搭起来的 databricks.yml + app.yaml + agent.py 三角",一旦这个 CLI 走出 Beta、Advana 的环境也跟上支持它,就能实实在在地降低 Peter 三个团队里那些代码背景没那么深的成员,在 FM Insight 平台内部搭建自己限定范围 agent 的门槛。
· Folder 4 Complete — and the Course's Full Arc, Closed
Folder 4 closes a loop that opened on Day 1: Folder 1 built retrieval, Folder 2 built tools and multi-agent orchestration, Folder 3 built the vocabulary for judging whether any of it was any good, and Folder 4 is what happens when that whole stack has to survive contact with real users and real traffic. The one idea that ties the entire course together, named explicitly in File 29 and never contradicted since: everything — deployment, tracing, evaluation, monitoring — is designed to be incremental. You can deploy before tracing, trace before evaluating, evaluate offline before going online, and backfill a judge you hadn't thought to write yet. Nothing in this architecture demands getting it all right on day one.
Folder 4 把 Day 1 开的一个口子给合上了:Folder 1 搭的是检索,Folder 2 搭的是工具和多 agent 编排,Folder 3 搭的是怎么判断前面这些东西到底做得好不好的那套词汇,而 Folder 4 讲的是,当这整套东西要真的扛住真实用户和真实流量的时候,会发生什么。贯穿整门课的那一个核心想法,在 File 29 里明确点出来、后面从没被打破过:不管是部署、tracing、评测还是监控,整套设计都是可以一步一步加的。你可以先部署再加 tracing,先 tracing 再做评测,先离线评测再上线,也可以给一个当初根本没想到要写的判官做回填。这套架构从来没要求你第一天就把什么都做对。
| Capability needed | Feature | Where in the Databricks UI | File |
|---|---|---|---|
| Ship an agent as a live web app | Databricks Apps + DABs | Apps page in the sidebar | 29, 30 |
| Govern model calls centrally | Unity Gateway | AI/ML > Unity Gateway (model service config) | 29 |
| Connect a governed external tool at runtime | MCP (Databricks-provided, external, or custom) | Catalog (MCP is a UC object) | 30, 31 |
| See what the agent actually did, per request | MLflow Tracing (autolog + manual spans) | Experiments > Traces tab | 30, 31, 32 |
| Group a multi-turn conversation into one unit | Session-level trace metadata | Experiments > Traces > Sessions switcher | 32 |
| Query trace history with SQL / dashboards | UC-backed trace tables + views | Catalog > your schema > *_trace_unified / *_trace_metadata | 31, 32, 33, 35 |
| Continuously score live traffic | Scorer register/start + sampling tiers | Experiments > Scorers tab | 33, 34 |
| Catch a multi-turn-only failure pattern | Conversation judges (Completeness, Frustration, Safety, ...) | Experiments > Sessions view, after a judge is deployed | 33, 34, 35 |
| Score traces that predate a scorer | backfill_scorers() | Jobs & Pipelines > Metric Backfill Computation Job | 33, 35 |
| Lower the build floor further (Beta) | Agent Bricks CLI + agent.toml | N/A — local CLI | 36 |
Taken together with Day 2 Part 1's phased adoption plan, Folder 4 supplies the missing back half of that plan: Phases 0-1 there were about getting tracing and offline evaluation onto one agent; everything this page covers — Databricks Apps deployment, resource-injected config that survives Advana's lagging feature rollout, Unity Gateway governance, UC-backed trace storage with explicit table grants, and sampling-tiered production scorers starting at Safety=100% — is the concrete, file-by-file answer to what Phases 2 through 5 actually build. The single open question this page does not resolve is Advana's own deployment surface: whether Databricks Apps is available there at all (Day 1's reconnaissance confirmed it is, alongside Lakehouse, but with Unity Catalog and serverless still "in the implementation"), which determines whether File 29-30's pattern can be followed as-is or needs the Model Serving fallback File 29 B3 describes.
把这一页跟 Day 2 第一部分那份分阶段采用计划放在一起看,Folder 4 正好补上了那份计划缺的后半段:那边的 Phase 0-1 讲的是怎么把 tracing 和离线评测先用到一个 agent 上;这一页讲的这些东西——Databricks Apps 部署、能扛住 Advana 功能滞后上线的资源注入式配置、Unity Gateway 治理、带明确表级授权的 UC trace 存储、从 Safety=100% 开始的分级采样生产 scorer——正是 Phase 2 到 Phase 5 具体要搭什么的、一个文件接一个文件的答案。这一页留下的唯一一个没解决的开放问题,是 Advana 自己的部署面:Databricks Apps 在那边到底能不能用(Day 1 的侦察已经确认能用,跟 Lakehouse 一起,但 Unity Catalog 和 serverless 还"在实施中"),这决定了 File 29-30 这套模式能不能原样照搬,还是需要退回到 File 29 B3 讲的 Model Serving 方案。