CCAR-P × Databricks — Day 1 Part 2

CCAR-P and Databricks GenAI Study Notebook — Day 1, Part 2

This is Part 2 of the same notebook. The big picture, the CCAR-P crosswalk, the Databricks platform map, the key-terminology glossary, and the Folder 1 production path all stay living in Part 1 — this page starts straight into Folder 2.

这是同一本笔记的第二部分。大图景、CCAR-P 对照、Databricks 平台结构、术语表,以及 Folder 1 的生产落地路径,都继续保留在第一部分里——这一页直接从 Folder 2 开始讲。

· Note on this part

Why Folder 2 is a different kind of material than Folder 1

Folder 1 was about retrieval: getting the right chunk of text in front of a model. Folder 2 is about control: once an agent can call tools, who decided it was allowed to, what happens when it picks the wrong tool, and who is accountable when it spends money or touches data it should not. That shift is exactly the shift FM Insight has to make once Folder 1's retrieval work (AI Search over audit-evidence PDFs) gets wired to agents that can actually act on DoW financial data, not just answer questions about it.

Folder 1 讲的是检索:怎么把正确的文本片段送到模型面前。Folder 2 讲的是控制:一旦 agent 能调用工具,是谁批准它可以调用、它选错工具会发生什么、它花了钱或碰了不该碰的数据时谁来负责。这正是 FM Insight 接下来要走的那一步——Folder 1 的检索能力(在审计证据 PDF 上做 AI Search)一旦接到真正能对国防部财务数据"动手"的 agent 上,而不只是回答问题,就必须解决这一整套控制问题。

05 Day 1 (continued) — Folder 2: Building Agentic Applications

Course agenda — Files 9-16, continuing the global file count from Part 1

Folder 1 taught retrieval. Folder 2 teaches agency: giving a model governed tools, exposing those tools through a standard protocol (MCP), letting single agents call them, letting multiple agents hand work to each other, and keeping all of it inside Unity Catalog's and Unity Gateway's governance. The course's own learning objectives name the arc directly: define agents and architectures, build governed tools in Unity Catalog, expose them via MCP, build single and multi-agent systems with the OpenAI Agents SDK, repeat the pattern in LangChain and DSPy, and observe everything with MLflow tracing.

Folder 1 教的是检索能力。Folder 2 教的是"能动性":给模型配上受治理的工具,用一个标准协议(MCP)把这些工具暴露出来,让单个 agent 去调用它们,让多个 agent 之间互相分派任务,并且这一切都还在 Unity Catalog 和 Unity Gateway 的治理范围之内。课程自己写的学习目标就是这条主线:定义 agent 和它的架构、在 Unity Catalog 里建受治理的工具、用 MCP 把工具暴露出来、用 OpenAI Agents SDK 搭单 agent 和多 agent 系统、在 LangChain 和 DSPy 里重复同一套模式、再用 MLflow tracing 把整个过程观测下来。

· Three sections, eight files

Folder 2 lesson list, numbered globally from Part 1 (File 9 = Folder 2's first file)
FileTypeLesson
09LectureAgents, MCP, and AI Governance on Databricks
10DemoBuilding Agent Tools on Databricks
11LabAssessing and Fixing Agent Tools
12LectureBuilding Agents with Popular Frameworks on Databricks
13DemoIntroduction to OpenAI Agents SDK on Databricks
14LabMulti-Agent Orchestration with the OpenAI Agents SDK on Databricks
15DemoIntroduction to LangChain on Databricks
16LabBuilding Agents with DSPy on Databricks

上表是 Folder 2 的课程列表,延续 Part 1 的全局文件编号(File 9 是 Folder 2 的第一个文件)。课程把这八个文件分成三段:基础篇(09-11,agent/MCP/治理概念,再动手建工具并修正它)、OpenAI Agents SDK 篇(12-14,先综览框架,再搭单 agent,最后在 Lab 里搭多 agent 系统)、其他框架篇(15-16,LangChain 和 DSPy 各走一遍同样的套路)。

Advana / FM link

The course's own learning objective 2 ("create governed agent tools in Unity Catalog") is the single most directly reusable skill in this folder for FM Insight. Every Advana data source FM Insight would let an agent query — GFEBS extracts, Navy ERP tables, USSGL mappings, the audit-evidence index built in Folder 1 — becomes a Unity Catalog function with the same discipline this course teaches: a descriptive name, type hints, and a docstring an agent can reason about. Get that step wrong and no amount of downstream agent framework choice (OpenAI SDK vs. LangChain vs. DSPy) fixes it; agents misuse badly documented tools regardless of which SDK calls them.

这个课程自己写的学习目标 2("在 Unity Catalog 里创建受治理的 agent 工具")是这个 Folder 里对 FM Insight 最直接可复用的一项技能。凡是 FM Insight 想让 agent 查询的 Advana 数据源——GFEBS 抽取数据、Navy ERP 表、USSGL 映射、Folder 1 建的审计证据索引——都要变成一个 Unity Catalog 函数,遵循课程教的同一套纪律:清晰的名字、类型标注、agent 能读懂的文档字符串。这一步做不好,后面选哪个 agent 框架(OpenAI SDK、LangChain 还是 DSPy)都救不回来——工具文档写得差,agent 用哪个 SDK 调用都会用错。

File 9 Lecture — Agents, MCP, and AI Governance on Databricks

Duration: 20 minutes · the conceptual foundation for the rest of Folder 2

Big picture first: this lecture answers one question with three parts. What is an agent (a model wrapped in a reason-act-observe loop instead of one prompt-response pair), what does it act on (Unity Catalog functions, exposed through MCP so any framework can discover and call them the same way), and who is watching (Unity Gateway, which tracks spend, enforces rate limits, and applies guardrails across every model and tool call). Everything later in Folder 2 is a variation on building and governing that loop.

先说大图景:这节课用三部分回答一个问题。什么是 agent(把模型包进一个"推理-行动-观察"的循环,而不是一问一答);它操作什么(Unity Catalog 函数,再通过 MCP 暴露出来,让任何框架都能用同一种方式发现和调用它们);谁在看着(Unity Gateway,跟踪花费、执行速率限制、在所有模型和工具调用上套治理护栏)。Folder 2 后面的内容,全都是围绕"怎么搭建并治理这个循环"做的各种变体。

A What are AI Agents?

A1 Single Agents

An AI agent is a model wrapped in a loop that can take actions and react to their results, instead of mapping one prompt straight to one response. The loop has four moves: reason and plan (break a goal into steps instead of answering in one shot), use tools (call functions, query data, reach external systems for real information), observe and adapt (read each tool result and decide the next action, looping until the goal is met), and stay grounded (rely on retrieved, governed data rather than the model's frozen training knowledge). On Databricks specifically, the tools an agent calls are Unity Catalog functions: governed, discoverable, and permission-checked, which is what makes agent actions auditable in production.

AI agent 就是把模型包进一个能采取行动、并根据行动结果做反应的循环里,而不是一个提示对应一个回答。这个循环有四个动作:推理和规划(把目标拆成步骤,而不是一次答完);使用工具(调用函数、查询数据、连接外部系统来获取真实信息);观察和调整(读取每次工具调用的结果,决定下一步,循环直到目标达成);保持有据可依(依赖检索到的、受治理的数据,而不是模型训练时就冻结的知识)。具体到 Databricks:agent 调用的工具就是 Unity Catalog 函数——受治理、可被发现、经过权限检查,这正是让 agent 的行为在生产环境里可审计的原因。

Prompt system + user Reason & plan break goal into steps Use tools call UC functions Observe & adapt read result, decide next loop until goal met Response grounded
The reason-act-observe loop: a prompt enters, cycles through planning, tool use, and observation until the goal is met, then exits as a grounded response.

A2 Multi-Agent Supervisors

The supervisor-worker pattern (also called router-delegate) is the common way to go from one agent to several. A supervisor agent receives the request, analyzes intent, and delegates to the right specialized worker (a data agent for Unity Catalog functions and SQL, a research agent for AI Search over documents, a general agent for reasoning that needs no tools), then synthesizes the worker's result back into a response. In the OpenAI Agents SDK this delegation is a first-class concept called a handoff: Agent(name="Supervisor", instructions="Route requests to the appropriate specialist.", handoffs=[data_agent, business_agent]).

supervisor-worker 模式(也叫 router-delegate,路由-分派)是从单 agent 扩展到多 agent 最常见的做法。一个 supervisor agent 接收请求、分析意图,把任务分派给合适的专职 worker(负责 Unity Catalog 函数和 SQL 的 data agent、负责在文档上做 AI Search 的 research agent、不需要工具、只做推理的 general agent),再把 worker 的结果整合成最终回答。在 OpenAI Agents SDK 里,这种分派是一个一等概念,叫 handoff:Agent(name="Supervisor", instructions="Route requests to the appropriate specialist.", handoffs=[data_agent, business_agent])。

A3 Single-Agent vs. Multi-Agent

The course gives this as a factor-by-factor comparison rather than a rule of thumb, and its own recommendation is to start with a single agent and only decompose when tool-selection errors, instruction conflicts, or separate team ownership force it.

课程把这个问题拆成一个个因素来比较,而不是给一条简单的经验法则,它自己的建议是:先从单 agent 开始,只有在出现工具选择错误、指令冲突,或者不同团队必须各自独立拥有某部分能力时,才拆成多个 agent。

Single-agent vs. multi-agent, by factor (Lecture File 9, Section A3)
FactorSingle AgentMulti-Agent
Number of toolsBest up to ~8-10 total; beyond that, tool selection degrades.Better with many tools spanning distinct capabilities (often >10).
Domain complexityOne focused or tightly related domain.Multiple distinct domains or verticals.
Instruction lengthShort, coherent system prompt.Would need a long, fragmented prompt if kept in one agent.
Failure isolationFailures acceptable as one unit.Need to isolate and replace individual agent capabilities.
Team ownershipSingle team owns most/all behaviors.Different teams own different domains and need independent evolution.
LatencyMinimal overhead, fewer model calls.Extra routing calls add latency and token cost.
ScalabilityFine while bounded; limited parallelism in one context window.Better for parallelizing across domains, at the cost of coordination.

CCAR-P D1

  • Architectural pattern selection and multi-agent orchestration are both named weak spots in Peter's own CCAR-P study log (0/3 each).
  • This factor table is the concrete, vendor-specific version of that same CCAR-P decision: it gives real thresholds (≈8-10 tools) instead of an abstract heuristic.

Advana / FM link

  • An FM Insight obligation Q&A agent over one Advana data domain (e.g. just the audit-evidence index) is squarely single-agent territory.
  • A full cross-system FM Insight (GFEBS + Navy ERP + USSGL + audit evidence, each with its own owning team) is exactly the multi-agent case this table describes.

A4 Agents on Databricks: the spectrum

Databricks offers three starting points for building an agent, trading customization for managed convenience. Knowledge Assistant (legacy) lets you bring your own AI Search index and chunking strategy with full retrieval control, but is a legacy path. Genie Agent (managed, recommended for data-aware agents) is declarative: you attach tables or UC volumes and Databricks handles tool orchestration and query generation. Custom Agent (code-first) is where you own the agent logic, tools, and orchestration end to end, deployed as a Databricks App, the platform's recommended hosting path.

在 Databricks 上搭 agent 有三个起点,分别在"可定制"和"托管便利"之间做不同取舍。Knowledge Assistant(旧版)让你自带 AI Search 索引和分块策略,对检索管线有完全控制权,但属于一条 legacy 路径。Genie Agent(托管,官方推荐用于数据感知型 agent)是声明式的:你只需要挂上表或 UC volume,Databricks 负责工具编排和查询生成。Custom Agent(代码优先)是你从头到尾自己掌控 agent 逻辑、工具和编排,部署成 Databricks App,这是平台推荐的托管方式。

B Tools and Common Patterns

B1 Model Context Protocol (MCP)

MCP is an open standard for connecting agents to tools and context. Databricks managed MCP servers are Databricks-hosted, ready-to-use endpoints for AI Search, Genie Agents, Databricks SQL, and Unity Catalog functions. The payoff is standardization: define a tool once, and any MCP-aware client or framework can discover its schema at runtime and call it, instead of every framework needing bespoke glue to reach every tool (an N-frameworks by M-tools integration problem). Unity Catalog permissions stay enforced underneath, and usage is tracked and managed through Unity Gateway.

MCP 是一个开放标准,用来把 agent 连接到工具和上下文。Databricks 托管的 MCP 服务器是 Databricks 自己托管的、开箱即用的端点,覆盖 AI Search、Genie Agent、Databricks SQL 和 Unity Catalog 函数。它带来的好处是标准化:工具只定义一次,任何支持 MCP 的客户端或框架都能在运行时发现它的 schema 并调用它,而不需要每个框架都为每个工具写一套定制胶水代码(否则就是一个 N 个框架 × M 个工具的集成难题)。底层的 Unity Catalog 权限始终生效,使用情况通过 Unity Gateway 跟踪和管理。

Agent MCP Client discovers & calls tools Genie structured data GFEBS / Navy ERP tables AI Search unstructured data audit-evidence index UC Functions custom logic Unity Catalog permissions enforced Unity Gateway tracks & governs usage catalog.schema.*
One agent, one MCP client interface, three governed tool types. Every call still passes through Unity Catalog permission checks and Unity Gateway usage tracking.

CCAR-P D3

  • Integration protocol choice (MCP vs. API/CLI vs. agent-to-agent) is a named weak spot in Peter's CCAR-P study log (0/3).
  • This is the concrete answer for one platform: Databricks' own managed MCP servers make MCP the path of least resistance for any tool already registered in Unity Catalog, because the governance comes for free.

Advana / FM link

  • FM Insight's own future tool surface (audit-evidence retrieval, GFEBS/Navy ERP lookups, budget-execution functions) is a natural fit for Databricks managed MCP, once those sources are UC objects.
  • One MCP interface means FM Insight is not locked to one agent framework — the same tools work whether a future team builds on OpenAI Agents SDK, LangChain, or DSPy.

B2 Genie Agents: single agent with on-behalf-of governance

A Genie Agent is a managed single agent whose main tool is text-to-SQL (optionally augmented with trusted UC functions you attach). The part that matters for an enterprise deployment is the governance model around it, not just the SQL generation. The user authenticates as themselves; the agent's access-control list decides whether they can view or run it; and every query then executes on behalf of that user: the SQL warehouse borrows the agent author's compute delegation (configured once, at setup time), but data access is enforced against the requesting user's own Unity Catalog permissions, including row filters and column masks, and every query is audited back to that user, not to a shared service account.

Genie Agent 是一个托管的单 agent,它的主要工具是 text-to-SQL(可以再加上你附加的受信任 UC 函数)。对企业级部署来说,真正重要的是它周围的治理模型,而不只是 SQL 生成本身。用户以自己的身份登录;agent 的访问控制列表决定他能不能查看或运行它;然后每一次查询都是"代表该用户"执行:SQL 仓库借用的是 agent 作者在配置时设定好的算力委托,但数据访问是按照发起请求的那个用户自己的 Unity Catalog 权限(包括行过滤和列遮蔽)来强制执行的,每一次查询都会被审计到那个具体用户身上,而不是归到一个共享的服务账号下。

User own identity ACL check can view / can run? Genie Agent Text-to-SQL / UC Functions COMPUTE — author's delegation set once, at agent config time DATA — end user's identity row filters, column masks, audited grounded answer, scoped to this user
On-behalf-of execution: the agent's compute comes from the author's delegation, but every data access is checked and audited against the requesting user's own Unity Catalog permissions.
Advana / FM link

This is the governance pattern that answers a question FM Insight will face immediately: if a Genie Agent sits over GFEBS or Navy ERP tables, two different auditors with different row-level access to the same ledger must get different answers from the same agent, automatically, without anyone writing per-user logic into the agent itself. On-behalf-of execution is exactly that mechanism, built into the platform rather than something FM Insight would have to engineer by hand. The capstone-level question this raises for Folder 3/4: whether audit-evidence citations returned to a restricted user leak scope through the cited document text itself, which row filters alone will not catch.

这个治理模型正好回答了 FM Insight 马上就会遇到的一个问题:如果一个 Genie Agent 架在 GFEBS 或 Navy ERP 的表上面,两位对同一本总账有不同行级访问权限的审计员,必须从同一个 agent 那里自动得到不同的答案,而不需要任何人在 agent 里手写按用户区分的逻辑。On-behalf-of 执行机制正是做这件事的平台内置能力,而不是 FM Insight 需要自己手工搭建的东西。这也给 Folder 3/4 留了一个值得深挖的问题:返回给受限用户的审计证据引用,会不会通过被引用文档本身的文本内容泄露出行过滤拦不住的范围信息。

B3 Other Tools and Common Patterns

Beyond Unity Catalog functions and Genie, the course names AI Search (vector search built into the platform's governance) and a short taxonomy of tool patterns that recurs across every agent framework: structured retrieval, unstructured retrieval, code interpreter, and external connections.

除了 Unity Catalog 函数和 Genie,课程还提到了 AI Search(内置在平台治理体系里的向量检索)以及一套在所有 agent 框架里反复出现的工具模式分类:结构化检索、非结构化检索、代码解释器、外部连接。

Common tool patterns on Databricks today (Lecture File 9, Section B3)
Tool patternWhat it does
Structured data retrievalQuery SQL tables, databases, and structured data sources.
Unstructured data retrievalSearch document collections and perform retrieval-augmented generation.
Code interpreterLet agents run Python for calculations, data analysis, and dynamic processing.
External connectionConnect to external services and APIs such as Slack.

C Governance and AI Management with Unity Gateway

Unity Gateway is the platform's central governance layer for LLM endpoints, MCP servers, and coding agents. It gives six things at once: governance (tracking which users, agents, and applications make which calls, with on-behalf-of execution for MCP so agents act with the requesting user's own permissions instead of a shared service account), rate limiting (per-endpoint and per-identity QPM/TPM caps), guardrails (input/output safety and data-protection filters), usage tracking (token consumption and cost across endpoints), payload logging (request/response audit trails via inference tables), and hard spend caps. Without it, every agent or application would have to build its own access control, guardrails, and logging from scratch, which gets unreliable fast once more than one model or provider is in play.

Unity Gateway 是平台针对 LLM 端点、MCP 服务器和编码 agent 的中央治理层。它一次性提供六样东西:治理(跟踪哪些用户、agent、应用在发起哪些调用,MCP 场景下用 on-behalf-of 执行方式,让 agent 用发起请求的那个用户自己的权限行事,而不是用一个共享服务账号)、速率限制(按端点和按身份设 QPM/TPM 上限)、护栏(输入输出的安全过滤和数据保护策略)、用量跟踪(跨端点的 token 消耗和成本)、payload 日志(通过推理表记录请求/响应审计轨迹)、硬性花费上限。没有它,每个 agent 或应用都得从零开始自己搭访问控制、护栏和日志,一旦涉及一个以上的模型或供应商,这套自建的东西很快就会变得靠不住。

FM Insight Other DoW app Agent over cap $ exceeded Unity Gateway spend tracking · budget policies rate limits · chargeback guardrails · usage attribution payload logging (inference tables) hard spend cap: blocks over-budget calls Model service A Model service B Blocked!
Unity Gateway sits between every caller and every model service: one policy surface, applied the same way whether the caller is FM Insight or any other application on the metastore.

CCAR-P D5

  • Guardrails/safety controls and LLM risk/failure modes are both named weak spots (1/3 and 0/3).
  • Unity Gateway is a worked example of CCAR-P's enforcement ladder applied correctly: hard spend caps and rate limits are deterministic controls outside the model, not instructions or logging after the fact.

Advana / FM link

  • This confirms the finding already on file from the Databricks "Operationalizing Agent Fleets" ebook: Unity Gateway is the fleet-scale governance control plane FM Insight would sit all of its agent/model traffic behind.
  • Per-identity rate limits and chargeback map directly onto a multi-team DoW Comptroller environment, where different offices' AI usage needs separately attributable cost and separately enforceable budget caps.

C1 Fallback Routing

Unity Gateway endpoints support fallback routing: a request goes to a primary model, and on a 429 or 5xx error, the gateway retries against a configured fallback model, then a second fallback if needed, logging every attempt (success or failure) to an inference and usage-tracking table. The point is availability without the caller having to implement retry logic itself.

Unity Gateway 端点支持 fallback 路由:请求先发到主模型,一旦遇到 429 或 5xx 错误,gateway 会自动重试到配置好的备用模型,需要的话再试第二个备用模型,并把每一次尝试(无论成功失败)都记到推理和用量跟踪表里。这样做的意义是:调用方不需要自己写重试逻辑,也能获得可用性保障。

C2 Workspace-Scoped Endpoints vs. Model Services

Legacy model serving endpoints are workspace-scoped: the same endpoint gets duplicated per workspace, with permissions managed separately in each. Databricks recommends moving most governed LLM use cases to model services instead: a Unity Catalog securable object, defined once in a catalog.schema, shared across the metastore, discoverable in Catalog Explorer, and governed centrally through Unity Gateway controls rather than per-workspace permissions.

旧版的 model serving 端点是"按 workspace 划定作用域"的:同一个端点要在每个 workspace 里各建一份,权限也要在每个 workspace 里分别管理。Databricks 建议大多数受治理的 LLM 使用场景改用 model services:它是一个 Unity Catalog 可授权对象,在某个 catalog.schema 下定义一次,就能在整个 metastore 范围内共享,可以在 Catalog Explorer 里被发现,并且通过 Unity Gateway 的控制手段统一治理,而不是按 workspace 各自维护权限。

Legacy workspace-scoped endpoints vs. model services (Lecture File 9, Section C2)
Legacy Model Serving EndpointsModel Services
ScopeWorkspace-scoped AI GatewayUnity Catalog securable object
DefinitionDuplicated per workspaceDefined once in catalog.schema
PermissionsPer-workspaceCentralized UC privileges
DiscoverabilityPer workspaceDiscoverable in Catalog Explorer, shared across the metastore

对 FM Insight 来说,这一条直接决定了架构选择:一旦 FM Insight 要跨多个 Advana workspace 运行(比如不同的军种或办公室各有自己的 workspace),model services 而不是旧版端点,才是能让模型访问权限做到一次定义、全局治理的路径。

File 10 Demo — Building Agent Tools on Databricks

Duration: 20 minutes · File 9's B1 (MCP) made concrete, end to end

Big picture first: File 9 described MCP in the abstract. This demo builds the whole loop with two real tools: a SQL function and a Python function, both registered in Unity Catalog, both exposed through the same Databricks managed MCP server, and both offered to a model that has to decide which one answers which half of a two-part question. The second half of the demo repeats the same pattern against a Databricks out-of-the-box managed MCP (Genie One), which answers asynchronously rather than in one call. The throughline: register once in UC, and the tool is usable by any agent framework through MCP, with governance intact.

先说大图景:File 9 只是抽象地讲了 MCP 是什么。这个 demo 把整个链路用两个真实工具完整搭了一遍:一个 SQL 函数和一个 Python 函数,都注册在 Unity Catalog 里,都通过同一个 Databricks 托管 MCP 服务器暴露出来,再都提供给一个模型,让它自己判断一个两段式问题里哪一段该用哪个工具回答。demo 的后半段用同样的模式再跑一遍,但这次连的是 Databricks 开箱即用的托管 MCP(Genie One),它的回答是异步的,而不是一次调用就返回。贯穿全程的主线是:在 UC 里注册一次,任何 agent 框架都能通过 MCP 用这个工具,治理能力原封不动保留。

Terminology, pinned down

SUM and AVG are system functions. A SQL function is any reusable computation callable in SQL, including user-defined ones. Any function registered to Unity Catalog, whether written in SQL or Python, is a user-defined function (UDF). The demo uses "SQL function" or "function" loosely to mean a SQL UDF registered to UC.

SUM、AVG 这类是系统函数(system function)。SQL 函数是指任何能在 SQL 里调用的可复用计算,包括用户自己定义的。任何注册到 Unity Catalog 里的函数,不管是用 SQL 还是 Python 写的,都叫用户自定义函数(UDF)。demo 里说的"SQL 函数"或"函数",通常就是指注册到 UC 里的 SQL UDF。

B SQL Tool: Airbnb Data Analysis

The SQL tool, avg_neigh_price(neighborhood_name), follows five practices the demo calls out explicitly: clear parameter names and types, a COMMENT on both the function and each parameter, DETERMINISTIC where the function always returns the same result for the same input, an explicit return type, and handling for edge cases like NULL or malformed price strings. Every one of those five is there because an agent, not a person, is the one reading the function's metadata to decide whether and how to call it.

SQL 工具 avg_neigh_price(neighborhood_name) 遵循 demo 明确指出的五条实践:清晰的参数名和类型;函数本身和每个参数都有 COMMENT;相同输入总是返回相同结果时标注 DETERMINISTIC;明确指定返回类型;处理 NULL 或格式不对的价格字符串这类边界情况。这五条之所以每一条都要做到,是因为读这些函数元数据、决定要不要调用、怎么调用的,是 agent,不是人。

C Python Tool: Extract Airbnb Listing Information

The Python tool, airbnb_posting_info(id), does what SQL cannot: it makes an HTTP request to an external site and parses HTML out of the response. The demo's five Python practices mirror the SQL ones but for a different medium: explicit type hints on every argument and the return value (so create_python_function() can infer the tool's interface), explicitly named parameters, types compatible with the Spark SQL type system, a structured (Google-style) docstring precise enough for an agent to judge when to use the tool, and importing external libraries inside the function body rather than at module level, which is the safe pattern for UC-registered Python tools. Registration goes through client.create_python_function(func=..., catalog=..., schema=..., replace=True), the same DatabricksFunctionClient used to test the SQL tool.

Python 工具 airbnb_posting_info(id) 做的是 SQL 做不到的事:对外部网站发 HTTP 请求,再从返回的 HTML 里解析内容。demo 给出的五条 Python 实践,和 SQL 那五条对应,只是换了一种介质:每个参数和返回值都要有明确的类型标注(这样 create_python_function() 才能推断出工具接口);参数要显式命名;类型要和 Spark SQL 的类型系统兼容;用结构化(Google 风格)的 docstring,精确到 agent 能据此判断什么时候该用这个工具;需要用到的外部库要在函数体内部导入,而不是在模块顶层导入,这是给注册到 UC 的 Python 工具用的安全写法。注册方式是 client.create_python_function(func=..., catalog=..., schema=..., replace=True),用的是测试 SQL 工具时同一个 DatabricksFunctionClient。

Advana / FM link

This SQL-vs-Python split is the exact shape FM Insight's own tool layer needs. A balance or obligation lookup against a GFEBS or Navy ERP table is a SQL function: deterministic, fast, and fully governed by Unity Catalog row/column security. A tool that has to call out to the FIAR evidence repository, parse a scanned PDF, or hit an external DoW system's API is a Python function, following the same File 4/5 parsing patterns already in Part 1. Keeping that split explicit, rather than writing everything as one kind of function, is what makes each tool's governance and testing story simple instead of mixed.

这个 SQL 和 Python 的划分,正好是 FM Insight 自己的工具层需要的形状。查 GFEBS 或 Navy ERP 表里的余额或义务数据,就应该是 SQL 函数:确定性强、速度快,而且完全受 Unity Catalog 的行/列安全治理。需要调用 FIAR 证据库、解析扫描版 PDF,或者访问国防部其他系统 API 的工具,就应该是 Python 函数,沿用 Part 1 里 File 4/5 已经讲过的解析套路。把这个划分讲清楚,而不是什么都写成一种函数,才能让每个工具的治理和测试逻辑保持简单,而不是混在一起。

D Discover and Test Tools via MCP

With both tools registered, DatabricksMCPClient connects to the managed MCP server URL for that catalog and schema (/api/2.0/mcp/functions/{catalog}/{schema}). list_tools() returns both the SQL and the Python function with their name and description, exactly what an agent would see. Tool names on the wire follow the pattern catalog__schema__function, and the demo calls out explicitly to select a tool by that name rather than by its position in the returned list, because list order is not guaranteed. Calling a tool through MCP (await mcp_client.acall_tool(tool_name, {...})) runs it exactly as an agent would, end to end through the protocol rather than through a direct function call.

两个工具都注册好之后,DatabricksMCPClient 连接到这个 catalog 和 schema 对应的托管 MCP 服务器 URL(/api/2.0/mcp/functions/{catalog}/{schema})。list_tools() 会把 SQL 函数和 Python 函数一起列出来,带着各自的名字和描述——这正是 agent 会看到的内容。工具在协议层的名字遵循 catalog__schema__function 这种格式,demo 特别强调要按这个名字选工具,而不是按返回列表里的位置选,因为列表顺序是不保证的。通过 MCP 调用一个工具(await mcp_client.acall_tool(tool_name, {...})),走的是和 agent 完全一样的协议路径,而不是直接调函数。

A technical wrinkle worth keeping: sync vs. async on Serverless

Notebook cells on Serverless already run inside a live asyncio event loop. The synchronous call_tool() is a convenience wrapper that internally tries to bridge into that loop, and nesting one event loop inside another this way can raise an ExceptionGroup that escapes a normal try/except. The fix is to stay fully async end to end: await acall_tool() and await asyncio.sleep(), which Databricks Serverless supports as top-level await in a cell.

Serverless 上的 notebook 单元本身就跑在一个活着的 asyncio 事件循环里。同步版本的 call_tool() 是一个便利封装,内部试图桥接进那个已经在跑的事件循环,而这样把一个事件循环嵌套进另一个事件循环,可能会抛出一个逃过普通 try/except 的 ExceptionGroup。解决办法是从头到尾保持异步:用 await acall_tool() 和 await asyncio.sleep(),Databricks Serverless 支持在单元里直接写顶层 await。

avg_neigh_price SQL function in UC airbnb_posting_info Python function in UC Managed MCP server catalog__schema__* Model reads name + description + parameters (inputSchema) picks the right tool
Two tools, one registration discipline, one MCP server: the model's only basis for choosing between them is each tool's name, description, and parameter schema.

E Test Your Tools with a Model

The demo asks one two-part question twice: "Compare the average price in Mission with the detailed information for listing 958. Which provides better value?" Asked with no tools offered, the model can only answer from what it already knows, or describe what it would need. Asked with both tools offered as specs (name, description, and inputSchema turned into an OpenAI-style function-calling payload), the model calls avg_neigh_price for the neighborhood average and airbnb_posting_info for the listing, filling in each argument from the question text itself. The code in this demo only asks the model what it wants to call; it never runs the tools. Running tool calls and feeding results back is the agent's job, covered in File 13 (Introduction to OpenAI Agents SDK).

demo 把同一个两段式问题问了两遍:"比较 Mission 社区的平均价格,和 958 号房源的详细信息,哪个更划算?"不提供任何工具时问,模型只能凭自己已知的东西回答,或者说出它还需要什么信息。把两个工具都以工具说明(名字、描述,以及转成 OpenAI 风格 function-calling 格式的 inputSchema)提供给模型后问,模型会调用 avg_neigh_price 取社区均价,调用 airbnb_posting_info 取房源信息,并且直接从问题文本里填好每个参数。这段 demo 代码只是问模型"你想调用什么",并不会真的去运行这些工具——运行工具调用、把结果喂回模型,是 agent 的工作,在 File 13(OpenAI Agents SDK 入门)里才会讲到。

CCAR-P D3 / D4

  • Tool capability bloat (D3, 0/3) and eval dataset/framework design (D4, 0/3) are both named weak spots.
  • "Ask the same question with and without tools" is a minimal but real evaluation method: it directly tests whether a model's tool choice improves on no-tool behavior, at the smallest possible scale (2 tools, 1 question).

Advana / FM link

  • This before/after pattern (no tools vs. tools) is a ready-made way to demonstrate FM Insight's value to non-technical stakeholders: show the same audit question answered vaguely without tools, then precisely with governed UC tools attached.
  • Tool-naming discipline (catalog__schema__function) is the reason FM Insight's catalogs and schemas need a naming convention decided early, before GFEBS, Navy ERP, and audit-evidence tools start colliding on short function names.

F Managed MCPs: Genie One

Beyond custom MCP servers built from your own UC functions, Databricks exposes out-of-the-box managed MCP servers through Unity Gateway's MCPs menu. The demo connects to one of these, system.ai.genie_one_mcp, at a URL that needs the workspace ID, not just the workspace host. Genie's answers are asynchronous: genie_ask returns a conversation_id and response_id immediately, and the client then polls genie_poll_response (the demo does up to 30 polls, 3 seconds apart) until the text contains "Genie has finished," at which point genie_get_query_result can fetch the full result set if Genie ran SQL underneath. Access to this MCP still runs through the same governance as any other: the demo notes that all account users get EXECUTE on system.ai as part of the classroom setup, not as a general default.

除了用自己的 UC 函数搭建的自定义 MCP 服务器,Databricks 还通过 Unity Gateway 的 MCPs 菜单提供开箱即用的托管 MCP 服务器。demo 连的是其中一个,system.ai.genie_one_mcp,它的 URL 需要 workspace ID,而不只是 workspace host。Genie 的回答是异步的:genie_ask 立刻返回一个 conversation_id 和 response_id,客户端再去轮询 genie_poll_response(demo 里最多轮询 30 次,每次间隔 3 秒),直到文本里出现"Genie has finished"为止;到那时如果 Genie 底层跑的是 SQL,就可以用 genie_get_query_result 取到完整结果集。访问这个 MCP 依然要走和其他工具一样的治理:demo 特别说明,所有账号用户在这次课堂配置里都被给了 system.ai 的 EXECUTE 权限,这是课堂设置,不是平台的通用默认行为。

genie_ask returns ids at once Poll loop genie_poll_response up to 30x, every 3s "still running" → loop finished Answer text narrative result Full query result genie_get_query_result EXECUTE on system.ai
Genie One's request-and-poll shape: the caller gets ids back immediately and must poll for completion, unlike the single-call SQL and Python tools earlier in this file.
Advana / FM link

This async ask-then-poll shape is not a Genie One quirk to work around; it is the pattern FM Insight's own natural-language query tools over GFEBS, Navy ERP, or the audit-evidence index should expect once queries run long enough to matter (a multi-year obligation trend, a full-catalog evidence search). Building the ask/poll/fetch contract into FM Insight's own tool layer now avoids a synchronous timeout surprise later, and it directly answers part of the open question noted after File 9: a Genie-based audit-evidence tool over Advana needs this same polling contract, not a single blocking call.

这种"先问再轮询"的异步形状,不是 Genie One 的一个需要绕开的怪癖,而是 FM Insight 自己在 GFEBS、Navy ERP 或审计证据索引上做自然语言查询工具时,一旦查询跑得足够久(比如多年期的义务趋势、全量证据库搜索)就该预期到的模式。现在就把"问-轮询-取结果"这套契约写进 FM Insight 自己的工具层,能避免以后遇到同步调用超时的意外,也正好回答了 File 9 之后留下的一个待解问题:架在 Advana 上的 Genie 型审计证据工具,需要的就是这套轮询契约,而不是一次阻塞式调用。

File 11 Lab — Assessing and Fixing Agent Tools

Duration: 30 minutes · File 10's "tools have to be documented" claim, proven the hard way

Big picture first: this lab takes one claim File 10 only asserted — "documentation is the interface between an agent and its tool" — and proves it with a real before/after. The classroom setup for this file registers a Unity Catalog function, est_listing_value, that is already fully correct in its logic and already fully broken in its documentation: meaningless parameter names (p1, p2, p3), a two-word description, and a docstring that flatly contradicts the code (it says p1 is the price; the code uses p1 as the bedroom count). You will watch a model misuse this tool with total confidence, rewrite only the documentation, re-register the exact same logic, and watch the same model use it correctly. Nothing about the math changes. Everything about whether the agent can use it changes.

先说大图景:File 10 只是断言了"文档是 agent 和工具之间的接口",这一关要用一次真实的前后对比把它证明出来。这一关的课堂配置注册了一个 Unity Catalog 函数,est_listing_value,它的计算逻辑完全正确,但文档完全是坏的:参数名毫无意义(p1、p2、p3),描述只有两个词,docstring 还直接和代码本身矛盾(docstring 说 p1 是价格,代码却把 p1 当作卧室数在用)。你会先看到一个模型非常自信地用错这个工具,然后只改文档、不改逻辑,重新注册,再看同一个模型正确使用它。数学逻辑一个字没变,agent 能不能正确使用它的结果却完全变了。

Where this function came from

est_listing_value is not something you write from scratch in this lab. It is registered ahead of time by %run ./Includes/Classroom-Setup-3, the same mechanism File 10's agent_training schema came from — a per-notebook config (config-3.yaml) drives setup_demo_environment(), which provisions the catalog/schema and seeds this one deliberately bad function into it. That is also why Catalog Explorer, once you have run several of this folder's notebooks, shows functions no single file created directly: each file's classroom setup seeds its own fixtures into the same shared agent_training schema.

est_listing_value在这一关里不是你从零写出来的。它是 %run ./Includes/Classroom-Setup-3 提前注册好的,用的是和 File 10 的 agent_training schema 完全一样的机制——每个 notebook 有自己的配置文件(这里是 config-3.yaml),驱动 setup_demo_environment() 去建好 catalog/schema,再故意把这一个写坏了文档的函数塞进去。这也是为什么你在这个文件夹跑过几个 notebook 之后,Catalog Explorer 里会看到一些不是某一个文件直接创建的函数:每个文件的课堂配置都会把自己的"道具"塞进同一个共享的 agent_training schema 里。

B The Broken Documentation

The function as registered:

def est_listing_value(
    p1: float,
    p2: float,
    p3: str
) -> str:
    """
    Calculates value.

    Args:
        p1: price
        p2: count
        p3: market

    Returns:
        str: result
    """
    base_value = p2 * 365 * 0.7  # assume 70% occupancy
    bedroom_factor = 1 + (p1 - 1) * 0.15
    if p3.lower() == 'entire home/apt':
        multiplier = 1.2
    elif p3.lower() == 'private room':
        multiplier = 0.8
    else:
        multiplier = 0.5
    estimated = base_value * bedroom_factor * multiplier
    return f"Estimated annual revenue: ${estimated:,.2f}"

Read the code, not the docstring, and the mismatch is immediate: the docstring says p1 is the price and p2 is a count, but the code multiplies p2 as if it were the nightly price and uses p1 as the bedroom count — the two are swapped relative to what the docstring claims. p3 fares no better: anything that isn't exactly "entire home/apt" or "private room" — including a city name like "San Francisco" — silently falls through to the lowest multiplier instead of raising an error. The function never fails. It just produces a confident, wrong, dollar-shaped number.

去读代码而不是 docstring,问题立刻就看出来了:docstring 说 p1 是价格、p2 是数量,但代码里是把 p2 当夜间价格来乘,p1 当卧室数来用——两者和 docstring 说的正好对调。p3 也一样糟:只要不是精确等于 "entire home/apt" 或 "private room" 的任何值——包括像 "San Francisco" 这样的城市名——都会默默落到最低档乘数,而不是报错。这个函数从来不会失败,它只会给出一个自信、错误、但看起来像钱的数字。

B1 · Watch a model misuse it

The lab's ask_model(question, tool_names=[...]) helper is File 10's ask_model with one change: it sets tool_choice="required", forcing the model to call a tool so its chosen arguments are always visible, and it re-reads the tool's definition from the MCP server on every call — so it will automatically pick up the fix in Section C without any code change to ask_model itself. Asked the realistic question "I have a 2-bedroom entire-home Airbnb listing in San Francisco priced at $250. What could I expect to make from it per year?", the model reads only p1: price, p2: count, p3: market and calls:

est_listing_value({'p1': 250, 'p2': 2, 'p3': 'San Francisco'})

The $250 price landed in p1, which the code treats as bedroom count. The city landed in p3, where the code expects a room type and falls through to the 0.5 multiplier. If this call ran, the tool would return $9,798.42. The right answer, given the actual numbers in the question, is $88,147.50 — off by a factor of roughly 9. The model is not confused or careless here; it is doing exactly what the documentation told it to do. That is the point: bad documentation that is confidently wrong is more dangerous than no documentation, because nothing about the interaction looks like a failure.

250 美元的价格被塞进了 p1,而代码把 p1 当卧室数用;城市名被塞进了 p3,代码在那里期待的是房型,匹配不上就落到 0.5 这个最低档乘数。如果真的跑了这次调用,工具会返回 $9,798.42。按问题里给的真实数字,正确答案应该是 $88,147.50,差了大约 9 倍。这里模型并不是犯糊涂或者粗心,它完全是照着文档说的做的。这正是这一关要说明的重点:自信地错着的文档,比完全没有文档更危险,因为整个交互过程看起来一点都不像是出了故障。

What the docstring claims p1 : price p2 : count p3 : market What the code actually does p1 → bedroom count p2 → nightly price p3 → multiplier (0.5 if unmatched) swapped swapped Model trusts the docstring calls est_listing_value(p1=250, p2=2, p3="San Francisco")
Nothing throws an error anywhere in this path. The model follows the docstring exactly; the docstring is simply wrong about what the code does with each argument.

C Fix the Function

The fix touches only documentation and parameter names — the arithmetic inside the function body does not change at all. Three things change: the parameter names become descriptive and typed (nightly_price_usd: float, num_bedrooms: float, room_type: str), the one-line description becomes a real explanation of what is computed and when to use the tool, and the Args/Returns sections become specific enough that a model can get every value right on the first try, including listing the exact three strings room_type accepts.

这次修复只动了文档和参数名,函数体里的计算逻辑一行都没改。改的是三件事:参数名变得有意义且带类型(nightly_price_usd: float、num_bedrooms: float、room_type: str);原来一句话的描述变成了真正说明这个函数算的是什么、什么时候该用;Args/Returns 部分写得足够具体,模型第一次就能把每个值填对,包括把 room_type 能接受的三个字符串原样列出来。

def est_listing_value(
    nightly_price_usd: float,
    num_bedrooms: float,
    room_type: str
) -> str:
    """
    Estimate the annual revenue for a San Francisco Airbnb listing based on
    its nightly price, number of bedrooms, and room type. Assumes 70%
    occupancy year-round.

    Use this tool when a user asks how much a listing could earn per year.

    Args:
        nightly_price_usd: The nightly price of the listing in US dollars (e.g. 250.0).
        num_bedrooms: The number of bedrooms in the listing (e.g. 1, 2, 3). A
            studio should be passed as 1. Each additional bedroom beyond
            the first increases the estimate by 15%.
        room_type: The Airbnb room type. Must be exactly one of:
            "Entire home/apt", "Private room", or "Shared room".

    Returns:
        A string describing the estimated annual revenue in USD.
    """
    base_value = nightly_price_usd * 365 * 0.7  # assume 70% occupancy
    bedroom_factor = 1 + (num_bedrooms - 1) * 0.15
    if room_type.lower() == 'entire home/apt':
        multiplier = 1.2
    elif room_type.lower() == 'private room':
        multiplier = 0.8
    else:
        multiplier = 0.5
    estimated = base_value * bedroom_factor * multiplier
    return f"Estimated annual revenue: ${estimated:,.2f}"

Re-registering reuses the exact same DatabricksFunctionClient call File 10 used for its Python tool, with one addition: replace=True, which overwrites the existing Unity Catalog function definition in place rather than erroring on a name collision.

重新注册用的是和 File 10 注册 Python 工具时完全一样的 DatabricksFunctionClient 调用,只多了一个 replace=True:它会原地覆盖掉 Unity Catalog 里已有的函数定义,而不是因为名字冲突而报错。

function_info = client.create_python_function(
    func=est_listing_value,
    catalog=catalog_name,
    schema=schema_name,
    replace=True
)
Advana / FM link — this is a change-control gap, not just a docs gap

replace=True is convenient in a lab and worth treating with more caution in FM Insight: it silently overwrites a UC function's definition with no version history of what changed, when, or why. A GFEBS or Navy ERP lookup tool whose docstring or logic changes without an audit trail is exactly the kind of undocumented control change DODIG scrutinizes under A-123 testing. FM Insight's own tool registration workflow should pair every replace=True with an external record (a git commit, a change ticket, a version tag in the function's own COMMENT) — the same discipline File 10 already flagged for tool-naming conventions, extended to tool version history.

replace=True 在这一关的实验环境里很方便,但在 FM Insight 里需要更谨慎地对待:它会原地覆盖 UC 函数的定义,却没有留下"改了什么、什么时候改的、为什么改"的版本记录。一个 GFEBS 或 Navy ERP 查询工具的 docstring 或逻辑在没有留痕的情况下被改掉,正是 DODIG 在 A-123 测试里会盯的那种"未留痕的控制变更"。FM Insight 自己的工具注册流程,应该给每一次 replace=True 配上一条外部记录(一个 git commit、一张变更工单,或者写进函数自己 COMMENT 里的版本标签)——这其实是把 File 10 已经提过的工具命名规范这条纪律,延伸到了工具版本历史上。

D Verify via MCP

Re-registering a UC function does not automatically prove an agent can now use it correctly — the lab verifies through the same two steps any production tool change should go through. First, mcp_client.list_tools() is called again, confirming the MCP server now reports the improved name, type hints, and docstring (MCP always reads the live UC registration, so this reflects Section C's change immediately, with no separate MCP-side update step). Second, the tool is actually executed through the protocol, not called directly as a Python function, using the exact name format from File 10 ({catalog}__{schema}__est_listing_value) with keyword arguments matching the new parameter names.

重新注册一个 UC 函数,并不能自动证明 agent 现在就能正确使用它——这一关用任何生产环境工具变更都该走的两步来验证。第一步,再次调用 mcp_client.list_tools(),确认 MCP 服务器现在报告的是改进后的名字、类型标注和 docstring(MCP 读的始终是 UC 里的实时注册信息,所以 Section C 的改动会立刻体现出来,不需要在 MCP 这一侧单独再更新一次)。第二步,真正通过协议去执行这个工具,而不是直接当 Python 函数调用,用的是和 File 10 一样的名字格式({catalog}__{schema}__est_listing_value),参数用新的参数名按关键字传入。

result = mcp_client.call_tool(
    f"{catalog_name}__{schema_name}__est_listing_value",
    {"nightly_price_usd": 250.0, "num_bedrooms": 2, "room_type": "entire home/apt"}
)
print(f"MCP Result: {result}")

E Validate with a Model

The exact same question from Section B1, asked through the exact same ask_model helper, with no change to that helper's code — only the tool's own documentation changed in between. The model now calls:

est_listing_value({'nightly_price_usd': 250, 'num_bedrooms': 2, 'room_type': 'Entire home/apt'})

Every value lands in the right parameter, and room_type is now one of the three exact strings the docstring listed, not a city. If this call ran, the tool would return $88,147.50, the correct figure. The only thing that changed between B1 and E is the documentation the model could read — same model, same question, same underlying arithmetic, same MCP protocol.

每个值都落进了正确的参数,room_type 现在也是 docstring 里列出的三个精确字符串之一,而不是一个城市名。如果真的跑了这次调用,工具会返回正确的 $88,147.50。B1 和 E 之间唯一变了的东西,是模型能读到的文档——同一个模型,同一个问题,底层算法完全没变,走的 MCP 协议也完全没变。

CCAR-P D4 / D5

  • Eval dataset/framework design (D4, 0/3) and LLM risk/failure modes (D5, 0/3) are both named weak spots.
  • This lab's B1-vs-E comparison is a minimal regression-test pattern for tools: same question, same framework, before/after a documentation change — a reusable eval even without a formal harness.
  • The silent-fallback-to-wrong-answer behavior in B1 is a named LLM failure mode worth tracking explicitly: a tool that never raises an error on bad input is a tool that can fail without anyone noticing.

Advana / FM link

  • A GFEBS/Navy ERP balance tool with an ambiguous or stale docstring is this exact failure mode, aimed at an audit-opinion-relevant number instead of an Airbnb listing: confident, wrong, and silent.
  • Tool documentation review belongs in FM Insight's own control-testing cadence (A-123 design-and-operating-effectiveness testing), not just in code review — a docstring is now a control, because an agent reads it the way a person reads a desk procedure.
Same code arithmetic unchanged B1 and E alike Docstring: p1/p2/p3 wrong tool call, wrong $ Docstring: named + typed right tool call, right $ Model via MCP same question, same protocol
Documentation is the only variable that moved between a 9x-wrong answer and the correct one. The code, the model, and the protocol all stayed fixed.
Bad tool (B1)Fixed tool (E)
Call the model makesest_listing_value(p1=250, p2=2, p3="San Francisco")est_listing_value(nightly_price_usd=250, num_bedrooms=2, room_type="Entire home/apt")
What the tool would return$9,798.42 (wrong)$88,147.50 (correct)
WhyThe out-of-date docstring sent each value to the wrong parameterThe names, types, and docstring match what the code does

结论:这一关证明的是"文档就是接口"这句话的具体含义——同样的逻辑,文档写得好坏能让结果相差近 9 倍,而且错的那一侧不会报任何错误。好文档至少要包含:清晰的名字、带例子的详细描述、以及业务背景信息;MCP 给了 agent 一种标准方式去发现和调用 UC 函数;任何工具在接入 agent 代码之前,都应该先过一遍"通过 MCP 测试,再用模型测试"这两道关。

File 12 Lecture — Building Agents with Popular Frameworks on Databricks

Duration: 20 minutes · From "tools are governed and documented" to "how do agents actually get built"

Big picture first: Files 9-11 covered tools in isolation — what they are, how to build and govern them, how to document them so an agent can use them correctly. This lecture is the pivot to the agent itself: the patterns for coordinating one or several agents, the fastest way to try a tool before it earns Unity Catalog registration, the exact class (McpServer) production OpenAI Agents SDK code uses to reach governed tools, what changes when more than one agent is involved, a tour of the other frameworks Databricks supports, and how MLflow tracing turns a multi-step agent run into something you can actually debug. Nothing here is executed in a notebook cell — it is the map you need before File 13 starts writing real agent code.

先说大图景:File 9-11 讲的都是"工具"本身——是什么、怎么建、怎么治理、怎么写文档让 agent 能正确使用。这一讲是转向 agent 本体:怎么编排一个或多个 agent、工具在拿到 Unity Catalog 注册资格之前怎么最快试出来、生产环境的 OpenAI Agents SDK 代码到底用哪个类(McpServer)去连治理好的工具、多了一个以上的 agent 之后什么会变、Databricks 支持的其他框架长什么样、MLflow tracing 怎么把一次多步骤的 agent 运行变成可以真正调试的东西。这一讲没有一行代码会在 notebook 里真的跑起来——它是 File 13 开始写真实 agent 代码之前,你需要先有的地图。

A OpenAI Agent Orchestration Patterns

The OpenAI Agents SDK splits orchestration into two families. LLM-driven orchestration means the model itself decides what happens next — which specialist to call, whether to keep going. Code-driven orchestration means your Python code controls the flow deterministically, and the model only fills in each individual step. Neither is strictly better; the choice is about how much control versus flexibility a given workflow needs.

OpenAI Agents SDK 把编排方式分成两大类。LLM 驱动(LLM-driven)编排是模型自己决定接下来发生什么——该调用哪个专家、要不要继续。代码驱动(code-driven)编排是你的 Python 代码确定性地控制整个流程,模型只负责填好每一个具体步骤。两者没有绝对的好坏之分,怎么选取决于这个具体工作流到底需要多少控制力、又能容忍多少灵活性。

A1 · LLM-Driven Orchestration: Handoffs vs. Agents as Tools

An agent in this framework is an LLM equipped with instructions, tools, and handoffs — the ability to delegate a task to a specialized sub-agent. There are two distinct ways to delegate, and they differ in who ends up owning the conversation.

在这套框架里,agent 就是一个配好了指令、工具、以及handoffs(转交)能力的 LLM——handoffs 就是把任务委托给一个专门化的子 agent 的能力。委托有两种截然不同的方式,区别在于最后谁来"拥有"这段对话。

Handoffs (Agent(handoffs=[agent_a, agent_b])): a triage or supervisor agent routes the conversation to a specialist, and the specialist then becomes the active agent and responds directly to the user. Conversation ownership transfers completely; the supervisor does not see or post-process the specialist's reply. Use this when the specialist should respond directly, when prompts need to stay focused per route, or when each route needs its own distinct instructions and tool set.

Handoffs(Agent(handoffs=[agent_a, agent_b])):一个分诊/主管 agent 把对话路由给某个专家,这个专家接手之后就变成了当前负责对话的 agent,直接回复用户。对话的所有权完全转移过去;主管看不到也不会再加工专家的回复。适合用在:希望专家直接回复用户、每条路由需要保持自己专注的 prompt、或者每条路由需要完全不同的指令和工具集这些场景。

Agents as Tools (Agent(tools=[specialist.as_tool()])): a manager agent keeps conversation control the whole time and invokes specialist agents the same way it would invoke any other tool, via Agent.as_tool(). The manager reads each specialist's output and synthesizes a final answer itself. Use this when one agent should own the final answer, combine outputs from several specialists, or maintain a single uninterrupted conversational thread.

Agents as Tools(把 agent 当工具用)(Agent(tools=[specialist.as_tool()])):一个经理 agent 全程保持对话控制权,像调用任何其他工具一样,通过 Agent.as_tool() 去调用专家 agent。经理会读取每个专家的输出,自己综合出最终答案。适合用在:希望由一个 agent 来拥有最终答案、需要整合多个专家的输出、或者希望保持一条不被打断的单一对话线这些场景。

Handoffs — ownership transfers User Supervisor Specialist User now owns the reply Agents as Tools — manager keeps control User Manager tool: Spec A tool: Spec B calls both, synthesizes User
The question to ask when choosing between them: should the specialist talk to the user directly (handoffs), or should one agent always own the final synthesized answer (agents as tools)?

A2 · Code-Driven Orchestration

Code-driven orchestration trades some of the model's autonomy for predictability over speed, cost, and the order things happen in. Four patterns recur: structured outputs (an agent returns typed data your code branches on, e.g. routing by classification), sequential chaining (one agent's output feeds the next — research → outline → draft → review), parallel execution (independent agents run concurrently via asyncio.gather), and feedback loops (a generator and an evaluator agent iterate until the evaluator approves or a max-iteration count is hit).

代码驱动编排是用模型的一部分自主性,换取在速度、成本、执行顺序上的可预测性。常见的有四种模式:结构化输出(agent 返回带类型的数据,你的代码据此分支,比如按分类结果路由);顺序链式(一个 agent 的输出喂给下一个——研究 → 大纲 → 草稿 → 审阅);并行执行(用 asyncio.gather 并发跑多个相互独立的 agent);反馈循环(一个生成 agent 和一个评估 agent 反复迭代,直到评估通过或者达到最大迭代次数)。

Two implementation details matter across all of these: Runner.run() always returns a RunResult object, so chaining must extract .final_output (for passing a plain value forward) or .to_input_list() (for carrying the full conversation history, including tool calls, forward to the next agent — to_input_list() is the one to prefer in sequential chaining, since final_output alone drops that history). And a feedback-loop evaluator needs a structured output_type (e.g. a Pydantic model with approved: bool and feedback: str) so its verdict can be parsed programmatically rather than scraped from free text.

这四种模式里有两个实现细节是共通的:Runner.run() 永远返回一个 RunResult 对象,所以链式调用时要么取 .final_output(只往下传一个纯值),要么取 .to_input_list()(把包括工具调用在内的完整对话历史往下传给下一个 agent——顺序链式更推荐用 to_input_list(),因为只用 final_output 会把这段历史丢掉)。另外,反馈循环里的评估 agent 需要一个结构化的 output_type(比如一个带 approved: bool 和 feedback: str 字段的 Pydantic 模型),这样它给出的判断才能被代码直接解析,而不是从一段自由文本里硬抠。

Sequential chaining Research Outline Draft Review to_input_list() → Parallel execution Input Agent A Agent B Agent C Combine asyncio.gather(...) Feedback loop Generator Evaluator not approved → feedback approved
All three are deterministic in order and count; only the content each agent produces is left to the model.

CCAR-P D1

  • Architectural pattern selection and multi-agent orchestration (D1, 0/3) is the most directly tested domain in this entire section.
  • CCAR-P exam scenarios that describe a workflow in prose are really asking "which of these five patterns is this," the same reading skill this table trains.

Advana / FM link

  • A monthly close-package assembly workflow (pull trial balance → reconcile → flag anomalies → draft narrative) is sequential chaining, not handoffs — each FM Insight step needs the prior step's full output, in order, every time.
  • A feedback loop fits a KSD (Key Supporting Documentation) drafting tool well: a generator agent drafts the evidence narrative, an evaluator agent checks it against audit-sampling criteria before a human ever sees it.

B Rapid Prototyping with Framework Tool Decorators

Before a tool earns Unity Catalog registration, the fastest way to see whether an agent can use it is to write a plain Python function and hand it to an agent directly inside the notebook. Every framework does this the same way underneath: it reads the function's name, type hints, and docstring, and turns them into the tool schema the model sees — exactly the mechanism File 11 spent a whole lab proving matters. The three frameworks differ only in syntax, not in what they read.

一个工具在拿到 Unity Catalog 注册资格之前,想知道 agent 能不能用它,最快的办法就是直接写一个普通 Python 函数,在 notebook 里当场交给一个 agent 试。三个框架底层做的事情完全一样:读函数的名字、类型标注、docstring,把它们转成模型能看到的工具说明——这正是 File 11 用整整一关去证明的那套机制。三个框架只是语法不同,读的东西完全一样。

# OpenAI Agents SDK
from agents import Agent, function_tool

@function_tool
def classify_price_tier(price: float) -> str:
    """Classify a nightly SF Airbnb price as Budget, Mid-Range, Premium, or Luxury.

    Args:
        price: Nightly listing price in USD.
    """
    if price < 100: return "Budget"
    if price < 175: return "Mid-Range"
    if price < 300: return "Premium"
    return "Luxury"

agent = Agent(name="Data Analyst", tools=[classify_price_tier])
# LangChain — same function, @tool instead of @function_tool
from langchain_core.tools import tool
from langchain.agents import create_agent

@tool
def classify_price_tier(price: float) -> str:
    """Classify a nightly SF Airbnb price as Budget, Mid-Range, Premium, or Luxury.

    Args:
        price: Nightly listing price in USD.
    """
    ...  # identical body

agent = create_agent(llm, tools=[classify_price_tier], system_prompt=system_prompt)
# DSPy — no decorator at all; a typed, documented function already is a tool
import dspy

def classify_price_tier(price: float) -> str:
    """Classify a nightly SF Airbnb price as Budget, Mid-Range, Premium, or Luxury.

    Args:
        price: Nightly listing price in USD.
    """
    ...  # identical body

agent = dspy.ReAct("question -> answer", tools=[classify_price_tier])
# Optional: wrap it yourself to override the name or description
price_tool = dspy.Tool(classify_price_tier, desc="Classify an SF nightly price.")

DSPy's lack of a decorator is not a gap — it is a signal of where DSPy's actual strength lies. Tool definition is not where DSPy differentiates itself; optimizing the prompts and modules wrapped around those tools is (Section E covers this). For tool definition specifically, DSPy is simply the lightest of the three: no decorator required, just a well-typed, well-documented function.

DSPy 没有装饰器,不是功能缺失,而是在提示 DSPy 真正的强项在哪。工具定义不是 DSPy 区别于其他框架的地方,围绕这些工具的 prompt 和模块的优化(optimizing)才是(Section E 会讲到)。单论工具定义这一件事,DSPy 是三者里最轻量的:不需要装饰器,一个类型标注齐全、文档写好的函数本身就已经是工具了。

B1 · From Prototype to Governed Tool

A prototyped tool lives only in that one notebook session. The recommended path from there is identical in every framework: register the logic as a Unity Catalog function so it becomes governed and reusable, then let agents reach it through a Managed MCP server — exactly the pipeline File 10 and File 11 already walked through end to end for UC functions specifically. What differs per framework is only how the agent connects to that governed tool afterward: the OpenAI Agents SDK uses McpServer (Section C, below), LangChain discovers tools with DatabricksMCPClient and wraps each as a StructuredTool, and DSPy converts MCP tools with dspy.Tool.from_mcp_tool(...).

一个原型工具只存在于那一次 notebook 会话里。从这里往下,推荐路径在三个框架里是一样的:把逻辑注册成 Unity Catalog 函数,让它变得受治理、可复用,再让 agent 通过托管 MCP 服务器去访问它——这正是 File 10 和 File 11 已经完整走过一遍的 UC 函数流水线。不同框架唯一的差别,是 agent 之后怎么连到这个受治理的工具:OpenAI Agents SDK 用 McpServer(下面 Section C 讲);LangChain 用 DatabricksMCPClient 发现工具,再把每个工具包成一个 StructuredTool;DSPy 用 dspy.Tool.from_mcp_tool(...) 转换 MCP 工具。

1 · Prototype decorator or plain fn local to the notebook 2 · Register to UC DatabricksFunctionClient governed, permissioned 3 · Expose via MCP any framework discovers it at runtime
Every framework arrives at step 3 the same governed tool. They diverge only in which client class they use to get there.

C Databricks MCP Tools with McpServer

Production OpenAI Agents SDK code reaches governed UC tools through databricks_openai.agents.McpServer, which connects agents to Unity Catalog functions, AI Search indexes, and other Databricks services through MCP. It is layered: the agent layer treats each McpServer as a source of tools and calls tools/list to discover and tools/call to invoke; the McpServer class itself extends the SDK's MCPServerStreamableHttp, adding Databricks OAuth authentication, automatic URL construction, and built-in MLflow tracing (every tool call is wrapped with @mlflow.trace(span_type=SpanType.TOOL) automatically); the protocol layer handles the actual Streamable HTTP connection and token refresh with no manual token management needed; and the Unity Catalog backend is what actually executes the call, with UC permissions always enforced against the authenticated caller.

生产环境里的 OpenAI Agents SDK 代码,是通过 databricks_openai.agents.McpServer 去访问受治理 UC 工具的,它通过 MCP 把 agent 连到 Unity Catalog 函数、AI Search 索引,以及其他 Databricks 服务上。这套结构是分层的:agent 层把每个 McpServer 当作工具来源,调 tools/list 发现工具、调 tools/call 调用工具;McpServer 类本身继承自 SDK 的 MCPServerStreamableHttp,在此之上加了 Databricks OAuth 认证、自动构建 URL,以及内置的 MLflow tracing(每次工具调用都会自动被 @mlflow.trace(span_type=SpanType.TOOL) 包一层);协议层负责真正的 Streamable HTTP 连接和令牌刷新,完全不需要手动管理令牌;Unity Catalog 后端才是真正执行调用的地方,始终对发起调用的认证用户强制 UC 权限检查。

McpServer has three factory methods, and the two UC-specific ones save you from hand-building the URL: McpServer(url=...) takes a direct URL to any MCP endpoint; McpServer.from_uc_function(catalog, schema, function_name) builds /api/2.0/mcp/functions/{catalog}/{schema}/{function} automatically; McpServer.from_vector_search(catalog, schema, index_name) builds /api/2.0/mcp/vector-search/{catalog}/{schema}/{index}. A third backend exists alongside UC functions and AI Search: Genie spaces, reached at /api/2.0/mcp/genie/{space_id}, exposed as natural-language query tools — the same Genie mechanism File 10's Section F introduced via Genie One, now generalized to any Genie space a workspace has configured.

McpServer 有三个工厂方法,其中两个 UC 专用的能让你不用手动拼 URL:McpServer(url=...) 直接传一个 MCP 端点的 URL;McpServer.from_uc_function(catalog, schema, function_name) 自动拼出 /api/2.0/mcp/functions/{catalog}/{schema}/{function};McpServer.from_vector_search(catalog, schema, index_name) 自动拼出 /api/2.0/mcp/vector-search/{catalog}/{schema}/{index}。除了 UC 函数和 AI Search,还有第三种后端:Genie 空间,走 /api/2.0/mcp/genie/{space_id},以自然语言查询工具的形式暴露出来——这正是 File 10 Section F 里 Genie One 介绍过的那套 Genie 机制,这里推广到了一个 workspace 配置过的任意 Genie 空间。

from agents import Agent, Runner
from databricks_openai.agents import McpServer

async with McpServer.from_uc_function(
    catalog="main", schema="tools", function_name="get_top_products", timeout=30.0
) as server:
    agent = Agent(name="my-agent", mcp_servers=[server])
    result = await Runner.run(agent, messages)
Agent OpenAI Agents SDK mcp_servers=[...] McpServer OAuth + MLflow trace tools/list, tools/call MCP Protocol Streamable HTTP UC Functions AI Search Genie spaces UC permissions always enforced
Three UC-governed backends, one protocol, one client class. The agent never needs to know in advance which backend a given tool call reaches.

D Multi-Agent Concepts

A single agent with tools is powerful, but many real workflows are better served by several specialized agents. The OpenAI Agents SDK's handoffs parameter (A1, above) is the native mechanism, and four things change once more than one agent is in the picture.

单个带工具的 agent 已经很强大了,但很多真实工作流更适合拆成几个专门化的 agent 来做。OpenAI Agents SDK 的 handoffs 参数(见上面 A1)就是原生机制,一旦场景里出现不止一个 agent,有四件事会发生变化。

Supervisor pattern: a supervisor agent receives every query and decides which worker to delegate to, using handoffs rather than calling tools directly — it reads each worker's name and instructions to pick the best fit. Worker specialization: each worker keeps a focused role, its own instructions, and its own small tool set, which keeps prompts concise and makes tool selection more accurate than one agent juggling many tools at once (e.g. a Data Analyst worker using classify_price_tier, a Business Analyst worker using neighborhood_summary). MCP-backed workers: each worker connects to its own McpServer instance scoped to only the UC function it needs, so it only ever sees tools relevant to its role — and the async with context manager has to wrap the entire multi-agent flow so every worker's MCP connection stays open for the full run, not just its own turn.

主管模式(Supervisor pattern):一个主管 agent 接收所有请求,决定委托给哪个 worker,用的是 handoffs 而不是直接调工具——它读每个 worker 的名字和指令来判断谁最合适。Worker 专门化:每个 worker 都保持一个专注的角色、自己的指令、自己一小套工具,这样既能让 prompt 保持简洁,也比一个 agent 同时兼顾一大堆工具更能准确地选对工具(比如 Data Analyst worker 用 classify_price_tier,Business Analyst worker 用 neighborhood_summary)。MCP 支撑的 worker:每个 worker 连到自己专属的 McpServer 实例,只作用于它需要的那个 UC 函数,这样它就只会看到和自己角色相关的工具——而且 async with 这个上下文管理器要包住整个多 agent 流程,让每个 worker 的 MCP 连接在整次运行期间都保持打开,而不只是在轮到它说话的那一刻。

Distributed tracing: with only mlflow.openai.autolog(), each agent invocation produces its own independent trace — the supervisor call and each worker call show up as separate traces, making the overall orchestration hard to see. The fix is to wrap the entire multi-agent flow in one parent @mlflow.trace span; every child span (routing, each worker's LLM calls, each MCP tool call) then nests under that single root, producing one trace tree instead of several disconnected ones.

分布式追踪(Distributed tracing):如果只用 mlflow.openai.autolog(),每一次 agent 调用都会产生各自独立的 trace——主管的调用和每个 worker 的调用会变成一堆彼此不相连的 trace,很难看清整体编排过程。解决办法是把整个多 agent 流程包在一个父级 @mlflow.trace span 里,之后每个子 span(路由、每个 worker 的 LLM 调用、每次 MCP 工具调用)都会挂在这同一个根节点下面,变成一棵完整的 trace 树,而不是好几棵互相断开的。

@mlflow.trace root span wraps the whole flow User Supervisor Data Analyst own McpServer Business Analyst own McpServer classify_price_tier neighborhood_summary
Each worker's MCP connection, scoped to one function, stays open for the full flow because the async context manager wraps all of it, not just one worker's turn.
Advana / FM link

Supervisor-plus-specialized-workers is the shape a full cross-system FM Insight needs, exactly as flagged after File 9's single-vs-multi table: a supervisor routes an incoming FM question to a GFEBS specialist, a Navy ERP specialist, or an audit-evidence specialist, each scoped via its own McpServer to only the UC functions its own domain owns. That scoping is not just tidiness — it is a governance boundary. A GFEBS worker that can only reach GFEBS-scoped MCP tools cannot accidentally expose a Navy ERP function, even if the model hallucinates a reason to call it, because the tool was never in that worker's mcp_servers list to begin with.

主管加多个专门化 worker,正是 File 9 的单/多 agent 对比表之后就留下的那个判断:一个完整的跨系统 FM Insight 需要这个形状——主管 agent 把进来的财务问题路由给 GFEBS 专家、Navy ERP 专家,或者审计证据专家,每一个 worker 各自通过自己的 McpServer,只能访问自己领域拥有的那些 UC 函数。这种范围限定不只是整洁好看,它本身就是一道治理边界。一个 GFEBS worker 如果只能连到 GFEBS 范围内的 MCP 工具,就算模型出于某种"幻觉"出来的理由想调用 Navy ERP 的函数,也不可能意外地把它暴露出来,因为这个工具从一开始就没出现在这个 worker 的 mcp_servers 列表里。

E Other Supported Frameworks

This course focuses on the OpenAI Agents SDK, but Databricks supports several other agent-authoring frameworks. The one hard requirement for deployment, regardless of framework, is wrapping the agent with the MLflow ResponsesAgent interface.

这门课重点讲的是 OpenAI Agents SDK,但 Databricks 还支持好几个其他的 agent 开发框架。不管用哪个框架,部署时唯一硬性要求是:用 MLflow 的 ResponsesAgent 接口把 agent 包一层。

LangChain is the composable chains-and-tools framework. databricks-langchain provides ChatDatabricks (the model connection) and UCFunctionToolkit (UC functions as LangChain tools); create_agent from langchain.agents replaces the older AgentExecutor + create_tool_calling_agent pattern from LangChain 0.x; mlflow.langchain.autolog() gives automatic tracing. Note, though: Databricks now recommends MCP-based tools for most new agents — UCFunctionToolkit remains supported, not newly preferred.

LangChain 是那个可组合的链式/工具框架。databricks-langchain 提供 ChatDatabricks(连接模型)和 UCFunctionToolkit(把 UC 函数变成 LangChain 工具);langchain.agents 里的 create_agent 取代了 LangChain 0.x 时代更老的 AgentExecutor + create_tool_calling_agent 这套模式;mlflow.langchain.autolog() 能自动打开 tracing。但要注意:Databricks 现在对大多数新 agent 推荐用基于 MCP 的工具——UCFunctionToolkit 仍然受支持,但已经不是新的首选了。

LangGraph is an open-source library for stateful, multi-actor LLM applications, defining agents as nodes in a directed graph with explicit state management and conditional edges — built for long-running workflows via its persistence/checkpointing features. On Databricks, create_agent (the same entry point as LangChain, since create_agent is built on LangGraph underneath) pairs with ChatDatabricks; MCP tools reach it through DatabricksMCPServer + DatabricksMultiServerMCPClient; mlflow.langchain.autolog() traces graph execution, capturing each graph step as a span.

LangGraph 是一个开源库,用来做有状态、多角色的 LLM 应用,把每个 agent 定义成一张有向图里的节点,带显式的状态管理和条件边——靠它的持久化/检查点能力,专为长时间运行的工作流设计。在 Databricks 上,create_agent(和 LangChain 用的是同一个入口,因为 create_agent 底层就是基于 LangGraph 构建的)搭配 ChatDatabricks 使用;MCP 工具通过 DatabricksMCPServer + DatabricksMultiServerMCPClient 接进来;mlflow.langchain.autolog() 会追踪图的执行过程,把每一步图节点都记录成一个 span。

DSPy is a framework for programmatically defining and optimizing generative AI agents: you specify input/output signatures (not hand-written prompts), and the DSPy compiler automatically optimizes the prompts — and, where applicable, model weights — for your specific task and data. On Databricks, mlflow.dspy.autolog() captures program, evaluation, and compilation traces; Databricks publishes example notebooks for text classification, RAG over AI Search, multi-agent systems combining Genie with DSPy, and migrating existing LangChain code to DSPy; production agents use the databricks-dspy package alongside MLflow's ResponsesAgent.

DSPy 是一个用来以编程方式定义和优化生成式 AI agent 的框架:你写的是输入/输出的 signature(而不是手写 prompt),DSPy 编译器会针对你具体的任务和数据,自动优化 prompt——在适用的情况下,还会优化模型权重。在 Databricks 上,mlflow.dspy.autolog() 会捕获程序、评估、编译过程的 trace;Databricks 提供了文本分类、基于 AI Search 的 RAG、Genie 和 DSPy 结合的多 agent 系统,以及把现有 LangChain 代码迁移到 DSPy 这几个示例 notebook;生产环境的 agent 用 databricks-dspy 包搭配 MLflow 的 ResponsesAgent。

# DSPy — signature instead of hand-written prompt
import dspy

class QA(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

lm = dspy.LM("databricks/databricks-gpt-5-2")
dspy.configure(lm=lm)
predictor = dspy.Predict(QA)

CCAR-P D1 / D3

  • Framework selection is itself an architecture decision (D1) and an integration-protocol decision (D3, 0/3) at once: LangGraph's stateful graph fits a genuinely long-running, checkpointed workflow; DSPy's optimizer fits a workflow whose prompt quality needs systematic, data-driven tuning rather than hand-editing.

Advana / FM link

  • FM Insight's own multi-month reconciliation or audit-cycle workflows are closer to LangGraph's target shape (long-running, needs checkpointing) than to the simpler single-session patterns this course builds in the OpenAI Agents SDK.
  • DSPy's optimizer is worth keeping on file for a specific FM Insight problem: a KSD-narrative-drafting prompt whose quality needs to be tuned against a labeled set of audit-accepted examples, not hand-tuned by a developer's intuition.

F MLflow Integration

Traditional ML workloads are a single call: input in, output out, and the request/response pair is everything MLflow needs to capture. Agents are different in shape — multi-step, often looped — and the thing worth observing is not the call as a whole but each individual span: a span records when one unit of work started and ended, along with its metadata, inputs, and outputs. A full agent run is a trace: a tree of spans. MLflow Tracing captures this automatically for supported libraries (OpenAI SDK, LangChain, and others) and is designed to be compatible with the OpenTelemetry trace specification, so extra information like token counts is stored as key-value attributes on a span rather than as new top-level fields.

传统 ML 任务是一次调用:输入进去、输出出来,请求/响应这一对就是 MLflow 需要捕获的全部。Agent 的形状不一样——多步骤、常常是循环的——真正值得观察的不是整次调用,而是每一个独立的span(跨度):一个 span 记录的是某一个工作单元什么时候开始、什么时候结束,以及它的元数据、输入、输出。一次完整的 agent 运行是一个trace(追踪):一棵由 span 组成的树。MLflow Tracing 对支持的库(OpenAI SDK、LangChain 等)会自动完成这个捕获过程,而且设计上兼容 OpenTelemetry 的 trace 规范,所以像 token 数这样的额外信息,是作为 span 上的键值对"属性"存的,而不是新增一个顶层字段。

Spans nest hierarchically, mirroring execution: a parent span like "process user request" has child spans like "call retrieval tool" or "generate response" underneath it, with span relationships showing execution flow and span types (TOOL, CHAT_MODEL, RETRIEVER) categorizing what each one did. This hierarchy is exactly what distributed tracing (Section D) needs a single root span to produce — without a parent span wrapping the multi-agent flow, there is no tree, only several disconnected traces.

Span 是按层级嵌套的,映射的是真实的执行过程:一个像"处理用户请求"这样的父级 span,下面挂着像"调用检索工具"或者"生成回复"这样的子 span,span 之间的父子关系展示的就是执行流程,而 span 类型(TOOL、CHAT_MODEL、RETRIEVER)标明的是每一个 span 具体做了什么。这套层级结构,正是 Section D 里"分布式追踪"需要一个单一根 span 才能产生的东西——没有一个父级 span 把整个多 agent 流程包起来,就不会有一棵完整的树,只会有好几段互不相连的 trace。

Traces can be registered with Unity Catalog, not just MLflow's own experiment store: binding an experiment to a catalog/schema with a table_prefix writes every trace as governed Delta tables and SQL views. mlflow.set_experiment(experiment_name=..., trace_location=UnityCatalog(catalog_name="prod", schema_name="agents", table_prefix="oai_sa")) produces four Delta tables (oai_sa_otel_spans — one row per span, the call tree with timing and I/O; oai_sa_otel_logs — OpenTelemetry log records; oai_sa_otel_annotations — feedback and tags attached to traces; oai_sa_otel_metrics — metric data points) plus two SQL views built over them (oai_sa_trace_unified — full detail, one row per trace with spans, metadata, and assessments together; oai_sa_trace_metadata — fast filtering, tags and metadata only, no span payloads). This needs a SQL warehouse set via MLFLOW_TRACING_SQL_WAREHOUSE_ID. Once registered, the traces are governed (grants, lineage, audit), queryable with Databricks SQL, and readable programmatically with mlflow.search_traces().

Trace 不是只能存在 MLflow 自己的实验存储里,也可以注册进 Unity Catalog:把一个实验绑定到某个 catalog/schema,带上一个 table_prefix,之后每一条 trace 都会写成受治理的 Delta 表和 SQL 视图。mlflow.set_experiment(experiment_name=..., trace_location=UnityCatalog(catalog_name="prod", schema_name="agents", table_prefix="oai_sa")) 会产出四张 Delta 表(oai_sa_otel_spans——每个 span 一行,带时间和输入输出的调用树;oai_sa_otel_logs——OpenTelemetry 日志记录;oai_sa_otel_annotations——挂在 trace 上的反馈和标签;oai_sa_otel_metrics——指标数据点),再加两个建在这些表之上的 SQL 视图(oai_sa_trace_unified——全细节版,每条 trace 一行,span、元数据、评估结果都在一起;oai_sa_trace_metadata——快速过滤版,只有标签和元数据,不带 span 的完整载荷)。这需要通过 MLFLOW_TRACING_SQL_WAREHOUSE_ID 配一个 SQL 仓库。注册好之后,这些 trace 就是受治理的(授权、血缘、审计都有),可以用 Databricks SQL 查询,也可以用 mlflow.search_traces() 编程方式读取。

Your GenAI app mlflow.openai.autolog() mlflow.langchain.autolog() mlflow.dspy.autolog() @mlflow.trace (custom) no changes to app logic MLflow Tracing inputs/outputs, latency, tokens, tool calls, errors trace_location= UnityCatalog(catalog, schema, table_prefix) 4 Delta tables *_otel_spans · *_otel_logs *_otel_annotations *_otel_metrics 2 SQL views *_trace_unified (full detail) *_trace_metadata (fast filter)
Governed, queryable, programmatically readable: once bound to Unity Catalog, agent traces get the same grants/lineage/audit treatment as any other UC table.
Advana / FM link — this answers a real FM Insight requirement, not just a debugging nicety

UC-registered MLflow traces solve a problem FM Insight will have regardless of which framework it ends up using: every agent decision that touches an audit-opinion-relevant number needs to be reconstructible later, the same way a GFEBS or Navy ERP transaction needs a traceable audit trail under A-123. A trace written to prod.agents.*_otel_spans is exactly that: which tool was called, with what arguments, returning what result, nested under which parent decision, queryable with ordinary Databricks SQL by an auditor who has never touched the agent's code. This is a stronger evidentiary artifact than a chat transcript, because it captures the tool calls and their actual arguments, not just the model's prose summary of what it did.

注册进 UC 的 MLflow trace,解决的是一个 FM Insight 不管最终选哪个框架都会遇到的问题:每一个碰到审计意见相关数字的 agent 决策,之后都得能被重新还原出来,就跟 GFEBS 或 Navy ERP 的一笔交易在 A-123 下需要有可追溯的审计轨迹一样。写进 prod.agents.*_otel_spans 的 trace 正好就是这个东西:调用了哪个工具、传了什么参数、返回了什么结果、挂在哪个父级决策下面,而且一个完全没碰过这个 agent 代码的审计人员,用普通的 Databricks SQL 就能查。这比一段聊天记录更有力的证据价值,因为它捕获的是实际的工具调用和真实参数,而不只是模型自己总结出来的一段"我做了什么"的文字描述。

G Conclusion

This lecture is the map for everything File 13-16 will build: orchestration patterns (handoffs, agents-as-tools, sequential, parallel, feedback loops), rapid prototyping across three frameworks before a tool earns UC registration, McpServer as the production bridge from agent to governed tool, what changes once multiple agents are involved (supervisor routing, worker specialization, scoped MCP connections, the need for one parent trace span), the other frameworks Databricks supports and when each one's strength actually matters, and MLflow tracing as the mechanism that makes any of this debuggable and, once bound to Unity Catalog, auditable.

这一讲是 File 13-16 接下来要搭建的一切的地图:编排模式(handoffs、agents-as-tools、顺序、并行、反馈循环)、在一个工具拿到 UC 注册资格之前怎么用三个框架快速试、McpServer 作为从 agent 到受治理工具之间的生产级桥梁、一旦出现多个 agent 之后会变化的东西(主管路由、worker 专门化、限定范围的 MCP 连接、需要一个父级 trace span)、Databricks 支持的其他框架以及各自的强项到底在什么场景下才真正用得上,还有 MLflow tracing 作为让这一切变得可调试、一旦绑定 Unity Catalog 之后还变得可审计的机制。

File 13 Demo — Introduction to OpenAI Agents SDK on Databricks

Duration: 20 minutes · The first real, running agent in this notebook

Big picture first: this is the moment File 9's open question finally resolves. File 9 explained agents in the abstract; File 10-11 built and documented tools but never ran an agent against them; File 12 was pure architecture, no execution. This demo is the first file in the whole course where an actual agent runs, calls a tool, and answers a question — a single Data Analyst agent, built from scratch with the OpenAI Agents SDK, that classifies Airbnb prices into market tiers. It follows the exact progression File 12's B1 table described: prototype with @function_tool, register to Unity Catalog, expose through MCP — and then layers MLflow tracing on top so every step of that progression is observable.

先说大图景:这是 File 9 留下的那个悬而未决的问题,终于在这里得到解决的时刻。File 9 只是抽象地讲了 agent 是什么;File 10-11 把工具建好、文档写好,但从没真的让一个 agent 跑起来调用过它们;File 12 纯粹是架构层面的内容,没有任何执行。这个 demo 是整门课里第一个真的跑起一个 agent、调用工具、回答问题的文件——一个用 OpenAI Agents SDK 从零搭起来的单一 Data Analyst agent,用来把 Airbnb 价格分到不同的市场档位。它走的正是 File 12 B1 那张表描述的那条路径:用 @function_tool 原型化,注册进 Unity Catalog,再通过 MCP 暴露出来——然后在上面再叠一层 MLflow tracing,让这整个过程的每一步都可观测。

A. Setup — the four things every OpenAI Agents SDK notebook on Databricks needs

set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True)) routes every SDK call through Unity Gateway (File 9's C) instead of OpenAI's own endpoint. set_default_openai_api("chat_completions") picks the API shape the model service speaks. set_trace_processors([]) disables the SDK's own OpenAI-hosted trace processor, clearing the way for MLflow to be the single source of traces instead of two separate systems fighting over the same spans. A WorkspaceClient instance (already familiar from File 10-11) rounds out the four.

set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True)) 把 SDK 的每一次调用都路由经过 Unity Gateway(File 9 的 C 部分),而不是走 OpenAI 自己的端点。set_default_openai_api("chat_completions") 指定 model service 讲的是哪种 API 格式。set_trace_processors([]) 关掉 SDK 自带的、托管在 OpenAI 那边的 trace processor,这样就不会出现两套系统互相抢着记录同一批 span 的局面,让 MLflow 成为唯一的 trace 来源。再加上一个(File 10-11 里已经很熟悉的)WorkspaceClient 实例,一共四件事。

B Define the Data Analyst Agent

The tool is classify_price_tier(price: float) -> str, decorated with @function_tool — a fully documented function from the first line (Budget/Mid-Range/Premium/Luxury tiers mapped to specific dollar thresholds and percentile bands, a structured docstring, a positive-price guard), built correctly the first time because File 11 already made the cost of skipping that discipline impossible to ignore. The agent's configuration — name, the llm_endpoint it calls, its system prompt — is loaded from an external YAML file (agent_config/data_analyst_agent.yaml) rather than hardcoded, the same "config outside the notebook" discipline already seen in config-N.yaml for classroom setup. The model it points to, {catalog_name}.{schema_name}.agent-training-model, is the model service File 9's C2 introduced: a Unity Catalog object that routes to databricks-gpt-5-2 through Unity Gateway, governed by UC permissions, swappable underneath without touching agent code.

工具是 classify_price_tier(price: float) -> str,用 @function_tool 装饰——从第一行开始就是文档齐全的函数(Budget/Mid-Range/Premium/Luxury 四档对应具体的美元门槛和百分位区间,结构化的 docstring,对价格为正数的校验),这一次一开始就写对了,因为 File 11 已经把跳过这套纪律的代价变得没法被忽视。agent 的配置——名字、要调用的 llm_endpoint、系统提示词——是从一个外部 YAML 文件(agent_config/data_analyst_agent.yaml)读进来的,而不是硬编码在 notebook 里,这和课堂配置里 config-N.yaml 那套"配置放在 notebook 外面"的纪律是一致的。它指向的模型,{catalog_name}.{schema_name}.agent-training-model,正是 File 9 C2 介绍过的那个 model service:一个 Unity Catalog 对象,通过 Unity Gateway 路由到 databricks-gpt-5-2,受 UC 权限治理,底层可以换模型而不用动 agent 代码。

data_analyst_agent = Agent(
    name=name,                 # from agent_config/data_analyst_agent.yaml
    instructions=system_prompt, # from the same YAML
    model=llm_endpoint,        # "{catalog}.{schema}.agent-training-model"
    tools=[classify_price_tier],
)

Three test queries progressively stress the agent: a straightforward single-tool-call question ("Is $150/night a good deal in SF?"), a tier classification at the top of the price range ("$500/night luxury listing"), and a multi-value question ("$80, $200, $350") that tests whether the agent calls the tool three separate times rather than guessing at a combined answer. Every call runs through await Runner.run(data_analyst_agent, query) — the SDK's execution interface, which drives the full agent loop: decide whether to call a tool, call it if so, then generate the final response from the result. result.final_output is where the agent's answer lands.

三个测试问题逐步加压:一个直接的单次工具调用问题("$150/晚在 SF 划算吗?")、一个价格区间顶端的档位分类("$500/晚的豪华房源")、以及一个多值问题("$80、$200、$350"),用来测试 agent 会不会分别调用三次工具,而不是凭空猜一个合并答案。每次调用都走 await Runner.run(data_analyst_agent, query)——SDK 的执行接口,驱动完整的 agent 循环:判断要不要调用工具、调用(如果需要的话)、再根据结果生成最终回复。result.final_output 就是 agent 答案落地的地方。

C Register Tools to Unity Catalog, Then MCP

The inline @function_tool version exists only in this notebook session. Section C moves it one step up the pipeline: DatabricksFunctionClient.create_python_function() registers the identical logic, as a plain undecorated function, to Unity Catalog — the exact mechanism File 10's Python tool and File 11's fix both used, now applied to this demo's own tool. A direct SQL call confirms it works (SELECT {catalog}.{schema}.classify_price_uc(150.0)), and then DatabricksMCPClient connects to the managed MCP server for that catalog/schema, discovers it with list_tools(), and calls it end to end through the protocol — mcp_client.call_tool(f"{catalog}__{schema}__classify_price_uc", {"price": 120.00}) — proving the full prototype → UC → MCP progression File 12's B1 only diagrammed in the abstract.

内联的 @function_tool 版本只存在于这一次 notebook 会话里。Section C 把它往流水线上游推了一步:DatabricksFunctionClient.create_python_function() 把一模一样的逻辑,以一个不带装饰器的普通函数形式,注册进 Unity Catalog——这正是 File 10 的 Python 工具和 File 11 的修复都用过的机制,现在用在这个 demo 自己的工具上。一次直接的 SQL 调用确认它能跑(SELECT {catalog}.{schema}.classify_price_uc(150.0)),然后 DatabricksMCPClient 连到这个 catalog/schema 对应的托管 MCP 服务器,用 list_tools() 发现它,再通过协议完整调用一遍——mcp_client.call_tool(f"{catalog}__{schema}__classify_price_uc", {"price": 120.00})——把 File 12 B1 那张只停留在示意图层面的"原型 → UC → MCP"全流程,真正跑通了一遍。

McpServer vs. DatabricksMCPClient — which one, when

The demo is explicit about a distinction File 12's Section C glossed over: McpServer from databricks_openai.agents is an async context manager built for the Databricks Apps runtime — it is what a deployed agent uses. In a notebook, the demo instead uses DatabricksMCPClient from databricks_mcp to talk to the same MCP endpoint for discovery and manual testing (exactly as File 10 and File 11 did). Section D4 later does use McpServer directly, inside the notebook, to show what the Apps-runtime pattern looks like — so both appear here, deliberately, for different purposes.

这个 demo 明确区分了一件 File 12 Section C 里一笔带过的事:databricks_openai.agents 里的 McpServer 是一个为 Databricks Apps 运行时设计的异步上下文管理器——这是一个已部署的 agent 会用的东西。在 notebook 里,demo 用的是 databricks_mcp 里的 DatabricksMCPClient,去和同一个 MCP 端点对话,做发现和手动测试(和 File 10、File 11 做的完全一样)。后面的 Section D4 又确实在 notebook 里直接用了 McpServer,为的是演示 Apps 运行时那套模式长什么样——所以这两个类都会在这个文件里出现,是刻意为之,各自服务不同的目的。

D Enable MLflow Tracing

mlflow.openai.autolog() patches the OpenAI SDK client itself, so every call automatically produces an MLflow trace with no code changes to the agent. Registering traces to Unity Catalog follows the exact pattern File 12's F3 described in the abstract, now run for real: UnityCatalog(catalog_name=catalog_name, schema_name=schema_name, table_prefix="oai_sa") ("OpenAI Single Agent") passed as trace_location to mlflow.set_experiment(), which also takes an experiment path built from dbutils-derived username. This produces the same 6 objects File 12 described: 4 Delta tables (oai_sa_otel_logs, oai_sa_otel_spans, oai_sa_otel_annotations, oai_sa_otel_metrics) and 2 views (oai_sa_trace_unified, oai_sa_trace_metadata), all empty until the agent actually runs.

mlflow.openai.autolog() 直接打了 OpenAI SDK 客户端本身的补丁,所以之后每一次调用都会自动产生一条 MLflow trace,agent 的代码一行都不用改。把 trace 注册进 Unity Catalog 走的是 File 12 F3 抽象描述过的那套模式,这里是真的跑了一遍:把 UnityCatalog(catalog_name=catalog_name, schema_name=schema_name, table_prefix="oai_sa")("OpenAI Single Agent")作为 trace_location 传给 mlflow.set_experiment(),同时还传了一个用 dbutils 拿到的用户名拼出来的实验路径。这会产出和 File 12 描述的一模一样的 6 个对象:4 张 Delta 表(oai_sa_otel_logs、oai_sa_otel_spans、oai_sa_otel_annotations、oai_sa_otel_metrics)和 2 个视图(oai_sa_trace_unified、oai_sa_trace_metadata),在 agent 真正跑起来之前全都是空的。

Running the agent once without MCP produces an unexpected result worth understanding, not just noting: one Runner.run() call produces two separate top-level traces, not one. mlflow.openai.autolog() patches at the OpenAI client level, and a single agent turn typically makes two underlying LLM calls — one where the model reasons about the question and decides to call classify_price_tier, and a second where it turns the tool's result into a final natural-language answer. With no parent span tying them together, each of those two calls becomes its own disconnected trace.

不带 MCP 跑一次 agent,会产生一个值得真正理解、而不只是记一笔的意外结果:一次 Runner.run() 调用会产生两条独立的顶层 trace,而不是一条。mlflow.openai.autolog() 是在 OpenAI 客户端这一层打补丁的,而一次典型的 agent 轮次底层通常会发生两次 LLM 调用——一次是模型推理这个问题、决定要调用 classify_price_tier,另一次是把工具返回的结果整理成最终的自然语言回答。没有一个父级 span 把这两次调用绑在一起,这两次调用就各自变成了互不相连的 trace。

Runner.run(agent, q) LLM call 1 — Trace A reason, decide to call tool classify_price_tier() tool executes LLM call 2 — Trace B compose final answer D4 fix @mlflow.trace(name= "...mcp_execution")
Two disconnected traces is expected behavior with client-level autologging, not a bug — the fix is a parent span, exactly as File 12's Section D described for multi-agent flows, applied here to a single agent's two-LLM-call turn.

Section D4 applies the fix by combining three things in one small function: McpServer.from_uc_function(...) builds the MCP connection for classify_price_uc specifically (not the whole schema — scoped to one function); the agent is redefined with mcp_servers=[mcp_server] in place of tools=[...], so it now discovers its tool at runtime through MCP rather than from an inline Python decorator; and the entire call is wrapped in @mlflow.trace(span_type="AGENT", name="data_analyst_mcp_execution"), an async def function using async with mcp_server: to open and close the MCP connection around the run. The decorator is what concatenates the MCP connection, the LLM calls, and the tool call into one unified trace instead of several disconnected ones — the same single-parent-span fix File 12's distributed-tracing discussion named for multi-agent flows, here solving the exact same problem for a single agent with two LLM calls per turn.

Section D4 用一个小函数把三件事合在一起,解决了这个问题:McpServer.from_uc_function(...) 专门为 classify_price_uc 这一个函数建好 MCP 连接(不是整个 schema——范围限定到一个函数);agent 被重新定义,用 mcp_servers=[mcp_server] 取代了 tools=[...],这样它现在是在运行时通过 MCP 发现工具,而不是靠内联的 Python 装饰器;整个调用被包在 @mlflow.trace(span_type="AGENT", name="data_analyst_mcp_execution") 里,是一个用 async with mcp_server: 来打开和关闭 MCP 连接的 async def 函数。真正把 MCP 连接、LLM 调用、工具调用串成一条统一 trace(而不是好几条互不相连的)的,就是这个装饰器——正是 File 12 讨论分布式追踪时提到的"单一父级 span"修复方式,这里用在了同一个问题上:一个单 agent 每轮要发生两次 LLM 调用的场景。

CCAR-P D4 / D5

  • Eval dataset/framework design (D4) and LLM risk/failure modes (D5) both apply: the "two disconnected traces" behavior is a concrete example of an observability failure mode that looks like a bug but is actually documented client-level autologging behavior — worth distinguishing on the exam between "the system is broken" and "the system is doing exactly what client-level patching implies."
  • The three progressively complex test queries in B3 are themselves a minimal eval set: single tool call, boundary value, multi-value — a pattern worth reusing whenever a new tool needs a first smoke test.

Advana / FM link

  • This is the first file where Peter can point to running code and say "this is the shape of an FM Insight single-domain agent" — one model service, one or two scoped UC tools, MLflow traces registered to Unity Catalog for after-the-fact audit review.
  • The config-outside-the-notebook pattern (agent_config/data_analyst_agent.yaml) is directly reusable: FM Insight's own agents should keep system prompts and model references in versioned config files, not hardcoded in notebooks, for the same change-control reasons flagged after File 11's replace=True discussion.

The two viewing paths for traces mirror each other: the Experiments UI (search for oai-sa-sdk-training, the experiment path set in D2) gives a visual breakdown per trace of tools used and model calls; SELECT * FROM oai_sa_trace_unified gives the identical information as queryable rows, with the full span tree in a spans column. Both are reading the same underlying UC tables — the UI is simply a rendering of what the SQL view already exposes.

查看 trace 的两条路径彼此是对应的:Experiments UI(搜索 oai-sa-sdk-training,就是 D2 里设置的那个实验路径)给出的是每条 trace 用了哪些工具、哪些模型调用的可视化分解;SELECT * FROM oai_sa_trace_unified 给出的是完全一样的信息,但是以可查询的行的形式呈现,完整的 span 树放在一个 spans 列里。两者读的是同一批底层 UC 表——UI 只是把 SQL 视图已经暴露出来的东西渲染了一遍而已。

结论:这个 demo 是全课程第一次把一个真正的、会运行的 agent 从头搭起来——不是示意图,不是伪代码,是一个用 @function_tool 定义工具、用 Agent() 搭起来、用 await Runner.run() 跑起来的 Data Analyst agent,然后把同一个工具重新注册进 Unity Catalog、接上 MCP、打开 MLflow tracing,并一路注册进 Unity Catalog 里可查询的表。File 9 留下的那个"还没有 agent 存在"的悬念,到这里才算真正解开。

File 14 Lab — Multi-Agent Orchestration with The OpenAI Agents SDK on Databricks

Duration: 35 minutes · File 12's multi-agent theory, built and tested for real

Big picture first: File 13 built one agent with one tool. This lab builds the real version of what File 12's Section D only diagrammed — a supervisor agent that holds no tools of its own and routes every incoming question to one of two specialized workers via handoffs, each worker scoped to its own MCP-exposed UC function. The lab's own scenario names it directly: a Data Analyst (classify_price_tier) and a Business Analyst (neighborhood_summary), both behind a supervisor that reads the request and decides who answers. The real payoff of this file is not that routing works on the easy cases — it is watching routing fail on an ambiguous case, then fixing it by editing a YAML prompt, not a line of Python.

先说大图景:File 13 搭的是一个 agent、一个工具。这一关要把 File 12 Section D 只画了示意图的东西,真正搭出来并跑通——一个自己不拿任何工具、靠 handoffs 把每个进来的问题路由给两个专门化 worker 之一的主管 agent,每个 worker 各自只接到自己那一个通过 MCP 暴露出来的 UC 函数。这一关的场景说得很直白:一个 Data Analyst(classify_price_tier)和一个 Business Analyst(neighborhood_summary),背后是一个读请求、决定由谁来回答的主管。这个文件真正的收获,不在于路由在简单场景下能跑通——而在于亲眼看到路由在一个有歧义的场景下失败,然后只靠改一个 YAML 提示词、而不是改一行 Python,就把它修好。

B MCP-Backed Worker Agents

Setup repeats File 13's A1 three-line Databricks routing config verbatim. Discovery confirms both functions are live: DatabricksMCPClient(server_url=f"{workspace_host}/api/2.0/mcp/functions/{catalog}/{schema}") followed by list_tools() should surface both classify_price_tier and neighborhood_summary before any agent is built — the same "verify the tool is actually there" discipline File 11's Section D ran after a fix, here run before construction even starts.

Setup 部分原样重复了 File 13 A1 那三行 Databricks 路由配置。发现阶段确认两个函数都在:DatabricksMCPClient(server_url=f"{workspace_host}/api/2.0/mcp/functions/{catalog}/{schema}") 后面跟 list_tools(),应该能在任何 agent 被搭起来之前,就看到 classify_price_tier 和 neighborhood_summary 都在。这和 File 11 Section D 修复之后才做的"确认工具真的在那儿"的纪律一样,只是这次是在搭建之前就先做了。

Three YAML configs are loaded, not two — data_analyst_agent.yaml, business_data_analyst_agent.yaml, and supervisor_agent.yaml — all through the same agent_files dict pattern File 13 used for one. All three agents share one model_fqn ({catalog}.{schema}.agent-training-model), built once from agents["da"]["llm_endpoint"] since the YAML only needs to name the service once. Each worker then gets its own McpServer.from_uc_function(catalog, schema, function_name, workspace_client=ws, timeout=60.0) — da_mcp_server scoped to classify_price_tier alone, ba_mcp_server scoped to neighborhood_summary alone — passed to its Agent(...) as mcp_servers=[...] rather than tools=[...], exactly the MCP-scoped-worker pattern File 12's D named and File 13's own agent never needed (it only had one tool to begin with).

这次加载了三个 YAML 配置,而不是两个——data_analyst_agent.yaml、business_data_analyst_agent.yaml、supervisor_agent.yaml——都是用 File 13 加载一个配置时同一套 agent_files 字典模式。三个 agent 共用一个 model_fqn({catalog}.{schema}.agent-training-model),只需要用 agents["da"]["llm_endpoint"] 建一次,因为 YAML 里只需要给这个服务起一次名字。之后每个 worker 各自拿到自己专属的 McpServer.from_uc_function(catalog, schema, function_name, workspace_client=ws, timeout=60.0)——da_mcp_server 只绑 classify_price_tier,ba_mcp_server 只绑 neighborhood_summary——传给各自的 Agent(...) 时用的是 mcp_servers=[...] 而不是 tools=[...],正是 File 12 D 部分点名过的"MCP 限定范围 worker"模式,而 File 13 自己的那个 agent 因为本来就只有一个工具,从没真正需要用到这一招。

C Build a Supervisor Agent with Handoffs

The supervisor holds no tools at all: Agent(name=agents["sa"]["name"], instructions=agents["sa"]["system_prompt"], model=model_fqn, handoffs=[data_analyst_agent, business_analyst_agent]). Its only job is picking a worker. The SDK does something the lab makes explicit and worth remembering: it auto-generates a callable tool for each handoff, named transfer_to_{agent.name} — transfer_to_Data_Analyst and transfer_to_Business_Analyst in this case — that never appears anywhere in the notebook's own code. The supervisor's LLM reads the user's question plus each worker's name and instructions, and picks whichever transfer_to_* tool matches.

主管一个工具都不持有:Agent(name=agents["sa"]["name"], instructions=agents["sa"]["system_prompt"], model=model_fqn, handoffs=[data_analyst_agent, business_analyst_agent])。它唯一的工作就是挑一个 worker。SDK 做了一件这一关特意讲清楚、也值得记住的事:它会给每一个 handoff 自动生成一个可调用的工具,名字是 transfer_to_{agent.name}——这里就是 transfer_to_Data_Analyst 和 transfer_to_Business_Analyst——这两个工具名在 notebook 自己的代码里从未出现过。主管的 LLM 读用户的问题,再读每个 worker 的名字和指令,挑出匹配的那个 transfer_to_* 工具。

Once a handoff happens, ownership transfers completely — exactly as File 12's A1 described. This is why result.last_agent.name, not the supervisor's name, is what the code checks to confirm routing: the supervisor does not post-process or see the worker's reply, it only decides who gets it. The trace later shows this as a four-step chain: supervisor LLM call → handoff decision → worker LLM call → tool call (if any) → final output, with the worker's output going straight back to the user.

一旦 handoff 发生,对话所有权就完全转移了——和 File 12 A1 描述的一样。这正是为什么代码里用来确认路由结果的是 result.last_agent.name,而不是主管的名字:主管不会再加工、甚至不会看到 worker 的回复,它只负责决定交给谁。之后的 trace 会把这个过程展示成一条四步链:主管 LLM 调用 → handoff 决策 → worker LLM 调用 → 工具调用(如果有的话)→ 最终输出,worker 的输出直接原样返回给用户。

User Supervisor no tools, only handoffs transfer_to_* (auto) Data Analyst da_mcp_server only Business Analyst ba_mcp_server only Response worker now owns the reply — result.last_agent.name
The supervisor never sees the final answer. result.last_agent.name is the only reliable way to confirm which worker actually handled a given question.

D Test and Refine Routing

Every test wraps the Runner.run(supervisor, query) call in async with da_mcp_server, ba_mcp_server: — both MCP connections open at once, even though a given query will only end up using one. That is deliberate, not sloppy: at the point the context manager opens, routing has not happened yet, so the code cannot know in advance which worker's connection it will need. A straightforward price question ("Is $200/night a good deal?") routes to the Data Analyst; a straightforward neighborhood question routes to the Business Analyst. Both confirm cleanly via result.last_agent.name.

每个测试都把 Runner.run(supervisor, query) 这次调用包在 async with da_mcp_server, ba_mcp_server: 里——两个 MCP 连接同时打开,哪怕某一次查询最后只会用到其中一个。这不是写得粗糙,是故意的:在这个上下文管理器打开的那一刻,路由还没发生,代码没办法提前知道接下来会需要哪一个 worker 的连接。一个直接的价格问题("$200/晚划算吗?")会路由给 Data Analyst;一个直接的社区问题会路由给 Business Analyst。两种情况都能通过 result.last_agent.name 干净利落地确认。

The mixed-routing test is where the lab earns its 35 minutes. Five queries run against the supervisor, each with an expected agent name, producing a PASS/MISMATCH table. The last query is the deliberate trap: "Is $250/night expensive for the Mission?" looks like a price question (it mentions a dollar figure), but answering it correctly requires the Mission's specific average price — a number only neighborhood_summary can supply. classify_price_tier only knows citywide tiers; it has no concept of "the Mission." A supervisor whose routing instructions only mention "price classification" for the Data Analyst and "neighborhood summaries" for the Business Analyst has no explicit rule covering a question that is both. Routing is an LLM decision end to end, so a MISMATCH here (or anywhere) can appear on one run and not the next — the lab's own framing, not a flaw to paper over.

混合路由测试才是这一关真正花功夫的地方。五个问题拿去问主管,每个都配了一个预期应该路由到的 agent 名字,跑出来是一张 PASS/MISMATCH 的表。最后一个问题是故意设的陷阱:"$250/晚在 Mission 算贵吗?"看起来像个价格问题(它提到了一个具体金额),但要答对,需要 Mission 这个社区具体的平均价格——这个数字只有 neighborhood_summary 能提供。classify_price_tier 只知道全市范围的档位,完全没有"Mission"这个概念。如果主管的路由指令里,关于 Data Analyst 只写了"价格分类",关于 Business Analyst 只写了"社区汇总",那对于一个两者都沾边的问题,就没有任何一条明确的规则能覆盖它。路由从头到尾都是一个 LLM 决策,所以 MISMATCH 在这一条(或者任何一条)上,这一次跑出来、下一次又跑不出来,都是正常的——这是这一关自己的说法,不是要掩盖的缺陷。

The fix is not in Python at all. agent_config/supervisor_agent.yaml is opened directly and a new rule is added under the existing Route to Business Analyst for: list, with a concrete worked example in the comment itself: "Comparing a specific price to a specific neighborhood (for example, 'Is $250/night expensive for the Mission?'), because answering requires that neighborhood's average price from neighborhood_summary." Saving the file and re-running reloads the YAML, rebuilds the supervisor object fresh from it, and re-runs the exact same five-query table — the loop File 11 ran for one UC function's docstring, now run for a supervisor's routing policy.

这次的修复完全不涉及 Python。直接打开 agent_config/supervisor_agent.yaml,在已有的 Route to Business Analyst for: 列表下面加一条新规则,注释里还给了一个具体的例子:"把一个具体价格和一个具体社区放在一起比较的问题(例如,'$250/晚在 Mission 算贵吗?'),因为要回答这个问题,需要用 neighborhood_summary 查到那个社区的平均价格。" 保存文件、重新运行,会重新加载这份 YAML,从头用它重建一遍主管对象,再把同样那五个问题的测试表重跑一遍——这正是 File 11 为一个 UC 函数的 docstring 跑过的那个循环,现在用在了一个主管的路由策略上。

CCAR-P D1 / D4 / D5

  • D1 (architecture/multi-agent orchestration): this is the first fully working build of the supervisor pattern File 9 and File 12 only described.
  • D4 (eval design): the five-query expected-vs-actual table is a real, minimal eval harness for a routing policy — reusable for any future supervisor.
  • D5 (LLM risk/failure modes): routing nondeterminism is a named, concrete failure mode here — the same question can route correctly on one run and incorrectly on the next, which is why the fix targets the instructions (reducing ambiguity) rather than trying to patch one bad run.

Advana / FM link

  • The ambiguous test case is the FM Insight pattern in miniature: a question that names a number (a dollar figure, an obligation amount) but actually needs a different domain's data to answer correctly (a GFEBS balance that reads like a budget-execution question but actually needs a Navy ERP transaction detail) is exactly the kind of routing ambiguity this test caught.
  • Fixing routing by editing YAML, not code, is the right change-control shape for FM Insight: a routing-policy change should be reviewable and versionable on its own, separate from any code deploy, the same discipline already flagged for tool docstrings after File 11.

E-F Distributed Tracing Across a Multi-Agent Flow

mlflow.openai.autolog() turns on the same client-level patching File 13 used, and Section E runs the supervisor once more just to show the problem before fixing it: a multi-agent flow produces not two fractured traces (File 13's problem) but several — one per LLM call across the supervisor and whichever worker it routed to, plus the tool call itself, each disconnected from the others. Section F's fix generalizes File 13's single-parent-span pattern into something closer to real production tracing: traced wrapper functions for each worker (run_data_analyst, run_business_analyst, each @mlflow.trace(span_type="AGENT", name=...), each opening its own single MCP server inside an async with), plus a top-level run_supervisor_traced wrapped the same way.

mlflow.openai.autolog() 打开的是和 File 13 一样的客户端层面打补丁,Section E 先把主管再跑一遍,就是为了在修复之前先把问题摆出来:一个多 agent 流程产生的不是两条碎片化的 trace(File 13 的问题),而是好几条——主管和它路由到的那个 worker 各自的每一次 LLM 调用都算一条,再加上工具调用本身,彼此互不相连。Section F 的修复,把 File 13 那个"单一父级 span"的套路,往更接近真实生产环境的追踪方式上又推进了一步:给每个 worker 都写一个带追踪的包装函数(run_data_analyst、run_business_analyst,各自用 @mlflow.trace(span_type="AGENT", name=...),各自在一个 async with 里只打开自己需要的那一个 MCP 服务器),再加一个顶层的 run_supervisor_traced,用同样的方式包起来。

Inside run_supervisor_traced, routing is done by a separate, undecorated router_agent — a plain agent with no handoffs at all, reusing the supervisor's own instructions, but instructed to reply with the name of the worker rather than actually handing off. That routing decision is wrapped in a manually opened child span, with mlflow.start_span(name="route_decision") as span:, with span.set_inputs({"question": question}) and span.set_outputs({"route": route}) recording exactly what went in and what came out of the routing step — the first time this notebook sequence uses manual span control rather than relying entirely on the decorator and autologging. The result is a clean, inspectable tree: supervisor_orchestration → route_decision (the router's own LLM call) → data_analyst_execution or business_analyst_execution → the worker's own LLM and tool call spans underneath.

在 run_supervisor_traced 内部,路由这件事是交给一个单独的、没有装饰器的 router_agent 来做的——一个完全没有 handoffs 的普通 agent,复用了主管自己的指令,但被要求直接回复该用哪个 worker 的名字,而不是真的去做一次 handoff。这个路由决策被包在一个手动打开的子 span 里,with mlflow.start_span(name="route_decision") as span:,用 span.set_inputs({"question": question}) 和 span.set_outputs({"route": route}) 精确记录路由这一步进去了什么、出来了什么——这是这整套 notebook 序列里第一次用手动的 span 控制,而不是完全依赖装饰器和自动打点。最后得到的是一棵干净、可检查的树:supervisor_orchestration → route_decision(router 自己的那次 LLM 调用)→ data_analyst_execution 或 business_analyst_execution → 再往下是那个 worker 自己的 LLM 调用和工具调用 span。

@mlflow.trace supervisor_orchestration route_decision mlflow.start_span(...) set_inputs / set_outputs route data_analyst_execution OR business_analyst_execution @mlflow.trace(span_type="AGENT") AsyncDatabricksCompletions worker LLM + tool call What File 13's single agent had only 2 LLM calls, no routing layer, no router_agent needed
The same single-parent-span fix from File 13, extended with one more layer: a manually-recorded routing span sits between the orchestration root and whichever worker actually ran.
Advana / FM link

This exact trace shape — supervisor_orchestration → route_decision → worker execution → tool call — is what an auditor reviewing an FM Insight agent decision would need to see, in order: which domain was this question routed to, on what basis, and what did that specific worker actually do. The manual span.set_inputs/set_outputs on the routing step specifically is worth keeping: it is the one place in this whole pipeline where the reasoning behind a governance-relevant decision (which specialist got this question) is captured as structured, queryable data rather than buried inside a model's free-text output.

这个 trace 结构——supervisor_orchestration → route_decision → worker 执行 → 工具调用——正是一个审查 FM Insight agent 决策的审计人员需要按顺序看到的东西:这个问题被路由到了哪个领域、依据是什么、那个具体的 worker 到底做了什么。路由这一步上手动写的 span.set_inputs/set_outputs,尤其值得保留:这是整条流水线里唯一一个把"一个和治理相关的决策(这个问题分给了哪个专家)背后的推理过程",记成结构化、可查询数据的地方,而不是埋在模型一大段自由文本输出里。

结论:这一关把三件事真正跑通了:搭了一个没有工具、只靠 handoffs 路由的主管 agent,接到两个各自限定范围的 MCP worker;用一张期望值对实际值的表测试了路由,抓到一个真实的歧义案例,并且只靠改 YAML(不改代码)把它修好了;把一个碎片化的多 agent trace,通过手动 span 加装饰器的组合,变成了一棵干净、可审查的 trace 树。

File 15 Demo — Introduction to LangChain on Databricks

Duration: 20 minutes · The course's own words: "mirrors notebook 05... using LangChain instead of the OpenAI Agents SDK"

Big picture first: this file is deliberately the same demo as File 13, run through a different framework. Same tool (classify_price_tier, same four-tier SF pricing logic), same progression (prototype → register to UC → discover via MCP → trace with MLflow), different library doing the agent work. That repetition is the point — it is the clearest possible proof that the UC-and-MCP governance layer sits underneath the framework, not inside it. Swap LangChain in for the OpenAI Agents SDK and the tool, its UC registration, and its MCP exposure do not change at all. Only the agent-construction code changes.

先说大图景:这一关故意跟 File 13 是同一个演示,只是换了一个框架来跑。同一个工具(classify_price_tier,同样的四档 SF 定价逻辑),同样的推进路径(原型 → 注册到 UC → 通过 MCP 发现 → 用 MLflow 做追踪),只是做 agent 这部分活儿的库换了。这种重复正是重点所在——它最清楚地证明了 UC 和 MCP 这层治理,是架在框架底下的,不是框架自己的一部分。把 OpenAI Agents SDK 换成 LangChain,工具本身、它在 UC 里的注册、它通过 MCP 暴露出来的方式,统统不变。只有搭 agent 那部分代码变了。

B LangChain's @tool and create_agent

The tool definition is almost character-for-character File 13's classify_price_tier, just decorated with LangChain's @tool from langchain_core.tools instead of the OpenAI SDK's @function_tool — the same "name + type hints + docstring become the tool schema" contract File 12's Section B already established as framework-agnostic. The agent itself is built with create_agent(llm, tools=[classify_price_tier], system_prompt=system_prompt), where llm is a ChatDatabricks(model=llm_endpoint, use_ai_gateway=True) pointed at the same agent-training-model UC model service introduced in File 9. create_agent runs a ReAct loop under the hood — reason, call a tool, observe the result, repeat until a final answer — and the notebook is explicit that it replaces LangGraph's older create_react_agent, deprecated as of LangGraph 1.0, while still running on LangGraph internally. Three progressively complex test queries (single tool call, high-end boundary value, three prices in one request) validate it, the same minimal eval shape File 13 used for the OpenAI version.

工具的定义和 File 13 的 classify_price_tier 几乎一字不差,只是把 OpenAI SDK 的 @function_tool 换成了 LangChain 的 @tool(来自 langchain_core.tools)——还是 File 12 B 部分已经讲过的那条"名字+类型提示+docstring 组成工具 schema"的规则,跟框架无关。agent 本身是用 create_agent(llm, tools=[classify_price_tier], system_prompt=system_prompt) 搭的,这里的 llm 是一个 ChatDatabricks(model=llm_endpoint, use_ai_gateway=True),指向的还是 File 9 里引入的那同一个 agent-training-model UC 模型服务。create_agent 底层跑的是一个 ReAct 循环——推理、调用工具、观察结果、重复,直到给出最终答案——notebook 里明确说它替代了 LangGraph 里更老的 create_react_agent(LangGraph 1.0 起已弃用),但内部仍然跑在 LangGraph 上。三个逐步复杂的测试问题(单次工具调用、高端边界值、一次问三个价格)验证了它,和 File 13 给 OpenAI 版本用的是同一套最小化评测方式。

C Register to Unity Catalog

Section C re-registers the identical logic as a plain Python function, classify_price_tier_uc (note the _uc suffix convention, same as File 13's classify_price_uc), via DatabricksFunctionClient().create_python_function(func=..., catalog=catalog_name, schema=schema_name, replace=True) — verbatim the same call File 11, 13, and 14 all used. The notebook is explicit about why a second, undecorated copy exists: DatabricksFunctionClient inspects the plain function's signature and docstring directly; it has no awareness of LangChain's @tool wrapper at all. Verification is a direct SQL call, spark.sql(f"SELECT {catalog_name}.{schema_name}.classify_price_tier_uc(150.0)") — the same "call it as plain UC SQL before trusting an agent with it" discipline from File 10 and File 13.

Section C 把同一套逻辑重新注册成一个普通的、不带装饰器的 Python 函数,classify_price_tier_uc(注意 _uc 后缀的命名习惯,跟 File 13 的 classify_price_uc 一样),用的是 DatabricksFunctionClient().create_python_function(func=..., catalog=catalog_name, schema=schema_name, replace=True)——和 File 11、13、14 用的是一模一样的调用。notebook 明确说了为什么要再搞一份不带装饰器的副本:DatabricksFunctionClient 直接读取的是普通函数的签名和 docstring,它完全不知道 LangChain 的 @tool 包装是什么。验证方式是直接发一条 SQL:spark.sql(f"SELECT {catalog_name}.{schema_name}.classify_price_tier_uc(150.0)")——跟 File 10、File 13 一样的纪律:先把它当纯粹的 UC SQL 调一遍,再把它交给 agent 去用。

D Discover Tools via MCP

Discovery repeats File 13's exact DatabricksMCPClient(server_url=f"{workspace_host}/api/2.0/mcp/functions/{catalog_name}/{schema_name}", workspace_client=ws) pattern, plus one new line not seen before: nest_asyncio.apply(), needed here because LangChain's internals make their own async calls under the hood and the notebook's synchronous cell execution would otherwise collide with them — a concrete instance of the sync-vs-async friction File 10 already flagged as a Serverless wrinkle, surfacing again for a different reason in a different framework.

发现阶段原样重复了 File 13 那套 DatabricksMCPClient(server_url=f"{workspace_host}/api/2.0/mcp/functions/{catalog_name}/{schema_name}", workspace_client=ws),只多了一行之前没见过的:nest_asyncio.apply()。这里需要它,是因为 LangChain 内部自己在底层会发起异步调用,如果不加这一行,notebook 单元格那种同步执行方式就会跟它们撞在一起——这正是 File 10 已经点出过的同步/异步摩擦的一个具体例子,只是这次换了个框架,又因为一个不同的原因冒出来了。

Section D3 is the genuinely new content in this file: converting discovered MCP tools into LangChain's StructuredTool objects is not a one-liner, because LangChain needs a typed argument schema (a Pydantic model) and MCP only hands back a JSON Schema. The helper _make_mcp_tool builds one at runtime: it reads mcp_tool_meta.inputSchema["properties"], maps each JSON Schema type string ("number", "string", "boolean", "integer") to a Python type through a small lookup dict (JSON_TO_PYTHON, falling back to str for anything unrecognized), wraps each field as (python_type, Field(description=...)), and calls Pydantic's create_model(f"{tool_name}_args", **field_definitions) to synthesize a brand-new argument-validation class on the spot — one the notebook's own code never wrote by hand. The tool's actual behavior is just a thin forwarder: _invoke(**kwargs) calls mcp_client.call_tool(mcp_name, kwargs) and joins the returned text, meaning the LangChain tool has no logic of its own at all — the UC function still runs in Databricks under Unity Catalog permissions every single time. One more wrinkle worth keeping: the tool name discovered from MCP is truncated to 64 characters (tool_name = mcp_name[:64]) because the OpenAI-compatible function-calling API that ChatDatabricks talks to enforces that limit on function names — a constraint that will matter the day a catalog/schema/function name combination runs long.

Section D3 是这个文件里真正新的内容:把发现到的 MCP 工具转换成 LangChain 的 StructuredTool 对象,并不是一行代码能搞定的事,因为 LangChain 需要一个带类型的参数 schema(一个 Pydantic 模型),而 MCP 返回的只是一份 JSON Schema。辅助函数 _make_mcp_tool 在运行时现场搭一个:它读取 mcp_tool_meta.inputSchema["properties"],通过一个小的映射字典(JSON_TO_PYTHON,遇到不认识的类型就退回 str)把每个 JSON Schema 类型字符串("number"、"string"、"boolean"、"integer")对应到一个 Python 类型,把每个字段包成 (python_type, Field(description=...)),再调用 Pydantic 的 create_model(f"{tool_name}_args", **field_definitions),当场合成一个全新的参数校验类——这是 notebook 自己的代码从来没有手写过的东西。这个工具真正的行为只是一层很薄的转发:_invoke(**kwargs) 调用 mcp_client.call_tool(mcp_name, kwargs),把返回的文本拼起来,也就是说这个 LangChain 工具自己完全没有任何逻辑——每一次调用,真正跑的还是 Databricks 里那个受 Unity Catalog 权限管控的 UC 函数。还有一个细节值得记住:从 MCP 发现的工具名字被截断到了 64 个字符(tool_name = mcp_name[:64]),因为 ChatDatabricks 背后调用的那个兼容 OpenAI 格式的函数调用 API,对函数名长度有这个硬限制——等某一天 catalog/schema/function 名字拼起来太长的时候,这个限制就会成为真问题。

@tool local only UC Function governed + reusable MCP Server standardized access LangChain Agent identical to File 13's pipeline — only the last box's framework changes
The course's own 4-stage pills, redrawn: the same progression File 13 ran for the OpenAI Agents SDK, now completed in LangChain.
MCP inputSchema {"price": {"type":"number"}} JSON_TO_PYTHON "number" → float create_model(...) synthesized at runtime StructuredTool.from_function args_schema = synthesized model _invoke(**kwargs) mcp_client.call_tool(...) the LangChain tool has no logic of its own — every call still runs the UC function
No hand-written wrapper per tool: the argument schema is generated fresh from whatever MCP reports, for any UC function the schema discovers.

E MLflow Tracing with LangChain

mlflow.langchain.autolog() is the LangChain-specific counterpart to File 13's mlflow.openai.autolog() — same idea, different client library patched. UC trace registration is identical in shape to every prior file: UnityCatalog(catalog_name=catalog_name, schema_name=schema_name, table_prefix="lc_sa") passed to mlflow.set_experiment(trace_location=uc), producing the same 4 Delta tables and 2 views, just with the lc_sa prefix instead of File 13's oai_sa. The agent is rebuilt with the MCP-sourced StructuredTool list instead of the inline @tool, with everything else — same llm, same system_prompt — unchanged, and tested with a query that echoes File 14's ambiguous trap in miniature: "I found a listing for $225/night in the Mission district. Is that a fair price?" Here there is no second worker to misroute to — this is a single agent with one tool — so the test is really checking that classify_price_tier_uc still fires correctly when the question is dressed up with an irrelevant neighborhood name.

mlflow.langchain.autolog() 是 File 13 里 mlflow.openai.autolog() 在 LangChain 这一侧的对应物——思路一样,只是打补丁的客户端库换了。UC trace 注册的形状跟之前每一个文件都一样:UnityCatalog(catalog_name=catalog_name, schema_name=schema_name, table_prefix="lc_sa") 传给 mlflow.set_experiment(trace_location=uc),产生同样的 4 张 Delta 表和 2 个视图,只是前缀从 File 13 的 oai_sa 换成了 lc_sa。agent 用 MCP 提供的那份 StructuredTool 列表重新搭了一遍,取代了内联的 @tool,其他的——同一个 llm、同一个 system_prompt——都没变,测试用的问题,是 File 14 那个歧义陷阱的缩小版:"我在 Mission 区看到一个 $225/晚的房源,这个价格合理吗?"这里没有第二个 worker 可以误路由过去——这就是一个单独的 agent、一个工具——所以这个测试其实是在检查,当问题里被塞进一个本来无关的社区名字之后,classify_price_tier_uc 是不是还能正确触发。

CCAR-P D1 / D3

  • D3 (integration protocol / framework choice): this file is the clearest possible exam material for "does the governance layer depend on the agent framework" — the answer, demonstrated end to end, is no. Same UC function, same MCP server, two different framework clients.
  • D1 (architecture): create_agent's ReAct loop on LangGraph is a second concrete implementation of the reason-act-observe pattern File 9 introduced abstractly, alongside the OpenAI Agents SDK's own loop in File 13.

Advana / FM link

  • FM Insight is not locked into one agent framework by adopting UC and MCP for governance — a team already invested in LangChain/LangGraph tooling gets the same governed-tool story without switching to the OpenAI Agents SDK, and vice versa.
  • The dynamic MCP-to-StructuredTool wrapper (JSON Schema → Pydantic model at runtime) is the generic adapter FM Insight would want: add a new GFEBS or Navy ERP UC function once, and every LangChain-based agent in the fleet can pick it up automatically with no new hand-written wrapper per function.
Advana / FM link

The 64-character tool-name truncation is a small detail with a real consequence for FM Insight's naming conventions: catalog__schema__function names that are already long (a schema named after a DoW component plus a long descriptive function name) could collide once truncated to 64 characters for a LangChain/OpenAI-compatible agent, even though the same name works fine called directly through MCP or UC SQL. Worth validating against FM Insight's actual planned naming scheme before this becomes a silent collision between two differently-named but identically-truncated tools.

64 个字符的工具名截断,是一个很小的细节,但对 FM Insight 的命名规范有实际影响:catalog__schema__function 这种名字如果本来就很长(比如 schema 名字里带了 DoW 某个下属单位的名字,再加一个很长的描述性函数名),截断到 64 个字符之后就可能撞车,即便这同一个名字直接通过 MCP 或者 UC SQL 调用时完全没问题。这一点值得拿 FM Insight 实际打算用的命名方案提前验证一下,免得日后变成两个名字不同、但截断后一模一样的工具,悄无声息地撞在一起。

结论:这一关证明了一件对框架选型很关键的事——把 @tool 换成 LangChain 的版本、把 Runner.run 换成 create_agent,UC 注册、MCP 暴露、MLflow 到 UC 的追踪注册全都原样不变,唯一真正新增的技术难点,是把 MCP 的 JSON Schema 动态转换成 LangChain 需要的 Pydantic 参数模型。

File 16 Lab — Building Agents with DSPy on Databricks

Duration: 30 minutes · The final file of Folder 2 — a third framework, and DSPy's own philosophy: declare what, not how

Big picture first: every prior agent file (9-15) shared one mental model — you write a system prompt as a string, and you write the tool-calling loop (or borrow one from an SDK). DSPy breaks that model on purpose. You never write a prompt by hand. Instead you declare a signature (what goes in, what comes out) and DSPy's own machinery, an adapter, writes the actual prompt text, sends it, and parses the reply back into typed fields. The lab's own scenario is an Airbnb recommendation assistant that needs two tools and has to reason about which one to call and in what order — the same reason-act-observe shape as every prior agent, built through DSPy's declarative style instead of an imperative one.

先说大图景:前面所有搭 agent 的文件(File 9-15)都共享一个心智模型——你把系统提示词写成一段字符串,工具调用的循环要么自己写,要么借用某个 SDK 现成的。DSPy 故意打破了这个模型。你从来不手写提示词。你声明的是一个signature(进去什么、出来什么),DSPy 自己的机制——一个adapter——负责把真正的提示词文字写出来、发出去、再把回复解析回带类型的字段。这一关自己的场景,是一个需要两个工具的 Airbnb 推荐助手,它得自己推理该调用哪个工具、按什么顺序——跟之前每一个 agent 一样的推理-行动-观察结构,只是这次是用 DSPy 的声明式写法搭出来的,不是命令式的。

Connecting DSPy to Databricks (Section B) reuses the by-now-familiar agent-training-model UC model service, but through a third distinct client shape: dspy.LM(model=f"databricks/{model_service}", api_base=f"https://{host}/ai-gateway/mlflow/v1", api_key=token), with the notebook-scoped token pulled via dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get() and dspy.configure(lm=lm) setting it as the default for every DSPy module in the notebook. Three files, three different Databricks-routing idioms now seen: File 13's set_default_openai_client(AsyncDatabricksOpenAI(...)), File 15's ChatDatabricks(model=..., use_ai_gateway=True), and this file's dspy.LM(...) hitting the AI Gateway's own /ai-gateway/mlflow/v1 path directly — all three ultimately resolving to the same governed agent-training-model UC object from File 9.

把 DSPy 接到 Databricks(Section B)用的还是那个已经很熟的 agent-training-model UC 模型服务,但走的是第三种不一样的客户端写法:dspy.LM(model=f"databricks/{model_service}", api_base=f"https://{host}/ai-gateway/mlflow/v1", api_key=token),token 是用 dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get() 取的notebook 范围令牌,dspy.configure(lm=lm) 把它设成这个 notebook 里所有 DSPy 模块的默认模型。三个文件,三种不同的 Databricks 路由写法:File 13 的 set_default_openai_client(AsyncDatabricksOpenAI(...))、File 15 的 ChatDatabricks(model=..., use_ai_gateway=True)、这个文件直接打 AI Gateway 自己的 /ai-gateway/mlflow/v1 路径的 dspy.LM(...)——三种写法最终都落在同一个受 File 9 治理的 agent-training-model UC 对象上。

C Signatures, Modules, and the Adapter Round Trip

A signature is just an input/output contract. The shorthand form, "question -> answer: str", is enough for dspy.Predict, the simplest module, to work: qa = dspy.Predict(signature); qa(question=question). Swapping dspy.Predict for dspy.ChainOfThought with the identical signature adds a reasoning output field and an extra internal step, but — and this is the point of the exercise — the adapter round trip underneath stays exactly the same shape.

signature 说到底就是一个输入/输出的约定。简写形式,"question -> answer: str",就足够让 dspy.Predict(最简单的 module)跑起来:qa = dspy.Predict(signature); qa(question=question)。用同一个 signature,把 dspy.Predict 换成 dspy.ChainOfThought,会多出一个 reasoning 输出字段和一个内部的额外步骤,但是——这正是这个练习要说明的事——底层那个 adapter 的来回流程,形状完全没变。

The course's own diagram walks one call through dspy.Predict in five numbered steps, worth carrying forward because it is the real mental model for everything DSPy does underneath a module: (1) you call qa(question="...") with keyword arguments named exactly by the signature; (2) the adapter's format() step writes a system message listing the input/output fields by name and type, and a user message marking the actual question under a [[ ## question ## ]] marker; (3) the LM itself only ever sees plain chat messages — it never sees your Python types, your Pydantic model, or the word "signature"; (4) the adapter's parse() step finds the [[ ## answer ## ]] marker in the reply and extracts the value, checking it against the declared output type; (5) you get back a typed Prediction object, pred.answer. ChatAdapter is the default adapter doing steps 2 and 4; swapping in JSONAdapter or TwoStepAdapter via dspy.configure(adapter=...) changes nothing about the program itself — the signature and the module code are untouched.

课程自己的图示,用五个编号步骤走了一遍 dspy.Predict 的一次调用,这个思路值得带走,因为它就是 DSPy 在任何一个 module 底下真正做的事:(1)你用跟 signature 里命名完全一致的关键字参数去调用 qa(question="...");(2)adapter 的 format() 这一步,写出一条系统消息,按名字和类型列出输入/输出字段,再写一条用户消息,把真正的问题标在一个 [[ ## question ## ]] 标记下面;(3)LM 本身永远只看得到普通的聊天消息——它从来看不到你的 Python 类型、你的 Pydantic 模型,也看不到"signature"这个词;(4)adapter 的 parse() 这一步,在回复里找到 [[ ## answer ## ]] 这个标记,把值取出来,再拿声明好的输出类型去校验一下;(5)你拿到的是一个带类型的 Prediction 对象,pred.answer。ChatAdapter 是默认负责第 2、4 步的 adapter;用 dspy.configure(adapter=...) 把它换成 JSONAdapter 或者 TwoStepAdapter,程序本身一点都不用改——signature 和 module 的代码原封不动。

"question -> answer" the signature — a contract, not a prompt Adapter.format() writes [[ ## question ## ]] LM plain chat text only Adapter.parse() finds [[ ## answer ## ]] Prediction(answer=...) swap ChatAdapter for JSONAdapter — the program above never changes
You never write the prompt. The signature declares the contract; the adapter is the only thing that ever touches prompt text.

E Two Kinds of Tools, One Agent

Section D's ListingInfo Pydantic model is not incidental — the notebook flags directly that every signature field is itself a Pydantic FieldInfo and dspy.Signature extends pydantic.BaseModel, so returning a typed Pydantic object from a tool, rather than a raw Spark row, is returning something DSPy's own type system already speaks natively. Section E's first tool, get_listing_details(listing_id: int) -> ListingInfo, is a plain Python function with no DSPy decorator at all — DSPy has none, by design, reinforcing File 12's "name + type hints + docstring is the whole contract" finding one more time, now with zero framework-specific annotation whatsoever.

Section D 里的 ListingInfo 这个 Pydantic 模型不是随手一笔——notebook 直接点明,signature 里的每一个字段本身就是一个 Pydantic 的 FieldInfo,dspy.Signature 本身继承的是 pydantic.BaseModel,所以让一个工具返回一个带类型的 Pydantic 对象,而不是一行原始的 Spark 行数据,等于是返回了一个 DSPy 自己的类型系统原生就能听懂的东西。Section E 的第一个工具,get_listing_details(listing_id: int) -> ListingInfo,是一个完全没有任何 DSPy 装饰器的普通 Python 函数——DSPy 压根就没有装饰器,这是故意的设计,再一次印证了 File 12 那个"名字+类型提示+docstring 就是全部契约"的发现,这次连框架专属的标注都完全没有了。

The second tool, avg_neigh_price(neighborhood: str) -> Optional[float], wraps a call to the classroom-seeded UC function of the same name (same provisioning pattern as File 10/11's fixtures) behind a plain Python function so DSPy sees an ordinary callable while the actual logic stays governed inside Unity Catalog. The one detail genuinely worth keeping is the TODO's own warning: the neighborhood string comes from the model, so it must never be pasted directly into SQL text. The fix is a named parameter marker, spark.sql("SELECT avg_neigh_price(:neighborhood) AS average_price", args={"neighborhood": neighborhood}) — Spark treats the value in args as data, not as text to splice into the query, so a model-supplied string containing a quote character cannot alter the query's structure. This is the exact SQL-injection discipline every FM Insight tool that accepts a model-chosen free-text parameter (a trading partner name, a fund code typed as "the one with an apostrophe in it") needs, stated here for the first time in the course as an explicit rule rather than something left implicit in an f-string.

第二个工具,avg_neigh_price(neighborhood: str) -> Optional[float],包的是对同名、课堂预置好的那个 UC 函数的调用(跟 File 10/11 那些 fixture 一样的供给方式),外面套一个普通 Python 函数,这样 DSPy 看到的是一个普通的可调用对象,而真正的逻辑还留在 Unity Catalog 的治理范围之内。真正值得记住的一个细节,是这个 TODO 自己给出的警告:社区名字这个字符串是模型给的,所以绝不能直接拼进 SQL 文本里。解决办法是用一个命名参数标记,spark.sql("SELECT avg_neigh_price(:neighborhood) AS average_price", args={"neighborhood": neighborhood})——Spark 把 args 里的值当成数据,不是拼进查询里的文字,所以模型给出的字符串里即便带了引号字符,也不可能改变这条查询的结构。这正是每一个接受模型自己选定的自由文本参数的 FM Insight 工具(一个交易方名字、一个"带撇号的那个基金代码")都需要的 SQL 注入防护纪律,这是这门课第一次把它说成一条明确的规则,而不是藏在某个 f-string 里靠运气。

F-G Build the ReAct Agent, Run It, Inspect the Trajectory

For an agent (rather than a one-shot Predict call), the signature is written as a class, AirbnbRecommendationAgent(dspy.Signature), whose docstring becomes the agent's system-level instructions and whose fields are declared with dspy.InputField(desc=...) / dspy.OutputField(desc=...) — the class form carries richer per-field descriptions than the shorthand string form could. dspy.ReAct(AirbnbRecommendationAgent, tools=[get_listing_details, avg_neigh_price]) then alternates reasoning and acting until it can answer, and the notebook has you print agent.tools.items() to see something easy to miss: three tools are listed, not two — finish is added automatically by dspy.ReAct itself so the agent has an explicit way to signal "I am done reasoning, answer now," the same role transfer_to_* played implicitly in File 14's handoffs, here made an explicit, visible tool in the agent's own tool list.

要搭一个 agent(而不是一次性的 Predict 调用),signature 要写成一个类,AirbnbRecommendationAgent(dspy.Signature),它的 docstring 变成 agent 系统层面的指令,字段用 dspy.InputField(desc=...)/dspy.OutputField(desc=...) 来声明——类的写法比简写字符串能承载更丰富的每个字段的描述。dspy.ReAct(AirbnbRecommendationAgent, tools=[get_listing_details, avg_neigh_price]) 之后就会在推理和行动之间反复切换,直到能给出答案,notebook 还让你打印 agent.tools.items(),好让你看到一个容易被忽略的细节:列出来的是三个工具,不是两个——finish 是 dspy.ReAct 自己自动加上的,让 agent 有一个明确的方式去表示"我推理完了,现在给答案",这跟 File 14 的 handoffs 里 transfer_to_* 暗中扮演的角色一样,只是这次变成了一个显式地出现在 agent 自己工具列表里、看得见的工具。

The lab's closing test question — "Tell me about listing 958. Is it more expensive than the average listing in the Mission?" — is the same ambiguous-sounding, two-tools-needed shape as File 14's mixed-routing trap, except here one agent with two tools must sequence both calls itself rather than a supervisor routing to one worker or the other. result.trajectory is the DSPy-specific payoff: for every step, it records the agent's thought, the tool chosen, the arguments passed, and the observation received — a structured log of the reasoning chain itself, distinct from (and complementary to) the MLflow trace that mlflow.dspy.autolog() captures automatically from the moment it is turned on in Section A. dspy.inspect_history(n=2) then shows the exact prompt text the adapter actually wrote and sent — the fastest way to confirm the Section C mental model (signature → adapter → literal chat messages) against a real multi-step agent run rather than the single toy dspy.Predict call.

这一关最后的测试问题——"跟我说说 958 号房源的情况,它比 Mission 的平均房源价格贵吗?"——跟 File 14 那个混合路由的陷阱是同一种听起来有歧义、需要两个工具的形状,只不过这里是一个 agent 自己拿着两个工具,得自己把两次调用按顺序排好,而不是靠主管路由给某一个 worker。result.trajectory 是 DSPy 特有的收获:每一步,它都记录了 agent 的想法、选的工具、传的参数、收到的观察结果——这是推理链本身的一份结构化日志,跟 Section A 一打开就自动开始记录的 mlflow.dspy.autolog() 的 MLflow trace 是两件不同、但互补的东西。dspy.inspect_history(n=2) 接着会展示 adapter 实际写出来、发出去的那段提示词原文——这是用一次真实的多步 agent 运行,而不是那个最简单的 dspy.Predict 玩具调用,来验证 Section C 那套心智模型(signature → adapter → 真正的聊天消息)最快的办法。

get_listing_details plain function, no decorator avg_neigh_price spark.sql(..., args={...}) wraps a governed UC function dspy.ReAct tools=[both] agent.tools (3 total) get_listing_details avg_neigh_price finish added automatically
Two differently-sourced tools look identical to ReAct once passed in — and ReAct always adds a third tool you never wrote yourself.

CCAR-P D3 / D4

  • D3 (integration protocol/framework choice): a third working framework for the same tool-and-UC progression — the exam-relevant takeaway is now threefold (OpenAI Agents SDK, LangChain, DSPy), each with a different programming model (imperative tool-calling, graph-based ReAct, declarative signature+adapter) reaching the identical governed UC/MCP foundation.
  • D4 (eval design): DSPy's own biggest strength, noted explicitly in the course's conclusion but out of scope for this lab, is optimizing prompts and modules against real data using the same signatures — worth flagging as the framework to revisit specifically for building an eval/optimization harness, not just a one-off agent.

Advana / FM link

  • The named-parameter-marker fix for avg_neigh_price (:neighborhood + args={...}, never an f-string) is a hard requirement for any FM Insight tool that accepts a model-chosen free-text value — a trading partner name, a fund or appropriation code — and should be written into the tool-development checklist alongside File 11's docstring-accuracy rule and File 10's naming-convention rule.
  • The plain-function-wrapping-a-UC-function pattern (avg_neigh_price) is the simplest possible template for exposing a governed GFEBS/Navy ERP lookup to any framework that has no tool decorator of its own — the UC permission boundary holds regardless of which agent framework calls it.

结论:这一关走完了和 File 13/15 一样的工具-到-UC-到治理这条路,但用的是一套完全不一样的写法——declare 契约,让 adapter 去写提示词——还顺带把一条明确的 SQL 注入防护规则写进了课程里。

Folder 2 Complete — Three Frameworks, One Governance Layer

Files 9-16 built the same underlying story three times, deliberately, in three frameworks: OpenAI Agents SDK (Files 13-14, @function_tool / Runner.run / handoffs), LangChain (File 15, @tool / create_agent / StructuredTool), and DSPy (File 16, no decorator at all / dspy.ReAct / signatures and adapters). Across all three, the part that never changed is the part that matters for FM Insight: a Unity-Catalog-registered function, discoverable and callable through a Managed MCP server, with MLflow traces registered back to Unity Catalog as queryable Delta tables. The framework is a UI choice for the development team; the governance boundary is a platform property that holds regardless of which framework a given agent team prefers.

File 9-16 用三种框架,故意把同一个底层故事讲了三遍:OpenAI Agents SDK(File 13-14,@function_tool/Runner.run/handoffs)、LangChain(File 15,@tool/create_agent/StructuredTool)、DSPy(File 16,完全没有装饰器/dspy.ReAct/signature 和 adapter)。三种框架里,从来没变过的那部分,正是对 FM Insight 真正重要的那部分:一个注册在 Unity Catalog 里的函数,能通过一个受管 MCP 服务器被发现、被调用,MLflow trace 又注册回 Unity Catalog,变成可查询的 Delta 表。框架是开发团队的一个界面选择;治理边界是一个平台层面的属性,不管某个 agent 团队喜欢用哪个框架,它都一样成立。

Folder 2's own throughline, file by file: File 9 named the concepts (agents, MCP, Unity Gateway) with nothing running yet; File 10-11 built and then fixed real UC tools; File 12 laid out the full orchestration-pattern taxonomy abstractly; Files 13-15 built the identical single/multi-agent story three times across frameworks; File 16 closed with the one framework whose philosophy is genuinely different (declare, don't prompt) rather than a fourth re-skin. Folder 3 (Agent Evaluation on Databricks) is the natural next step after this closing note — File 16's own mention of DSPy's optimization strength is a direct pointer toward it.

第二个文件夹自己的主线,一文件一文件地看:File 9 先把概念(agent、MCP、Unity Gateway)都点了个名,但还没有任何东西真正跑起来;File 10-11 先搭、再修了真正的 UC 工具;File 12 把整套编排模式的分类,抽象地铺了一遍;File 13-15 用三个不同框架,把同一个单/多 agent 的故事讲了三遍;File 16 用唯一一个哲学真正不一样的框架(声明,而不是提示词)收了尾,不是又换了一张皮重讲一遍。这个收尾之后,自然该往 Folder 3(Agent Evaluation on Databricks)走了——File 16 自己提到的 DSPy 优化能力这条线,正好直接指向那边。