Agent Build智能体搭建 Tutor教程
Platforms各平台 / Replication guide复刻指南

Replicate the local build on Databricks在 Databricks 上复刻本地构建

A step-by-step port of the whole local stack (models, gateway, knowledge bank, hybrid retrieval and graph, tools and MCP, skills, memory, the harness and its guard, evaluation, the learning loop and operations) to a Databricks workspace. Every step says why it sits where it does, what it does, how to run it, how to read the result, and what to do when it breaks.把整套本地技术栈(模型、网关、知识库、混合检索与图、工具与 MCP、技能、记忆、Harness 及其护栏、评估、学习循环与运维)一步一步移植到 Databricks 工作区。每一步都说明它为什么在这个位置、做什么、怎么运行、如何解读结果,以及出问题时怎么办。

Not executed on Databricks未在 Databricks 上执行Nothing on Databricks was run for this page: there was no workspace. API names and commands come from the vendor pages listed at the bottom, read in October 2026. Where a step depends on a detail those pages did not show, it says so in a 'Not confirmed' box. The portable logic (ranking, chunking, graph edges, the answer guard, the harness rules, the scorers and the learner's proof rule) was executed here: see the check results below.本页涉及的 Databricks 操作一项都没有实际运行过:这里没有工作区。API 名称和命令来自页面底部列出的厂商文档,阅读时间为 2026 年 10 月。凡是某一步依赖了这些页面没有展示的细节,都会在“未确认”框中注明。可移植的逻辑(排序、切块、图的边、答案护栏、Harness 规则、scorer 以及学习器的证明规则)已在这里执行过:见下方的检查结果。

What was checked here在这里检查过的内容

Run by replicate/databricks/check.py on由 replicate/databricks/check.py 运行于 2026-10-08, Python 3.13.16.

22Python files compile个 Python 文件可编译
3YAML files parse个 YAML 文件可解析
3shell scripts pass bash -n个 shell 脚本通过 bash -n
22/22portable tests passed项可移植测试通过
5SQL files read, not parsed (no Databricks SQL engine here)个 SQL 文件仅阅读,未解析(这里没有 Databricks SQL 引擎)
Test names测试名称
  • test_scorers (test_portable.Evals.test_scorers)
  • test_seal_digest_detects_one_changed_row (test_portable.Evals.test_seal_digest_detects_one_changed_row)
  • test_assistant_words_are_not_evidence (test_portable.Guard.test_assistant_words_are_not_evidence)
  • test_grounded_sum (test_portable.Guard.test_grounded_sum)
  • test_invented_figure (test_portable.Guard.test_invented_figure)
  • test_compose_order (test_portable.Harness.test_compose_order)
  • test_guard_loop (test_portable.Harness.test_guard_loop)
  • test_lineup_no_repeats (test_portable.Harness.test_lineup_no_repeats)
  • test_skill_floor (test_portable.Harness.test_skill_floor)
  • test_triage (test_portable.Harness.test_triage)
  • test_chunks_keep_heading_path (test_portable.Knowledge.test_chunks_keep_heading_path)
  • test_defines_edge (test_portable.Knowledge.test_defines_edge)
  • test_tier_first_match (test_portable.Knowledge.test_tier_first_match)
  • test_validate (test_portable.Knowledge.test_validate)
  • test_authority_breaks_near_tie_only (test_portable.Ranking.test_authority_breaks_near_tie_only)
  • test_dedup_shows_most_authoritative_copy (test_portable.Ranking.test_dedup_shows_most_authoritative_copy)
  • test_empty_has_diagnostic (test_portable.Ranking.test_empty_has_diagnostic)
  • test_flags_off (test_portable.Ranking.test_flags_off)
  • test_rrf_uses_positions_only (test_portable.Ranking.test_rrf_uses_positions_only)
  • test_contract (test_portable.Tools.test_contract)
  • test_learner_proves_by_rerun (test_portable.Tools.test_learner_proves_by_rerun)
  • test_prompt_braces (test_portable.Tools.test_prompt_braces)

All scripts live in replicate/databricks/ in this repository. Clone it, keep that folder's layout (the bundle syncs it as one unit), and run the steps in the order below, or in any order the dependency map allows.所有脚本都在本仓库的 replicate/databricks/ 目录中。克隆仓库,保持该目录的结构(bundle 会把它作为一个整体同步),然后按下面的顺序运行各步骤,或按依赖图允许的任意顺序运行。

What moves where什么搬到哪里

Each part of the local build, where it lives on Databricks, and what changes in the move.本地构建的每个部分、它在 Databricks 上的位置,以及迁移中发生的变化。

Local build本地构建On Databricks在 Databricks 上What changes变化Step步骤
Ollama on the Mac, lineup in model_catalog.jsonMac 上的 Ollama,阵容写在 model_catalog.jsonFoundation Model APIs (pay-per-token or provisioned throughput)Foundation Model API(按 token 计费或预置吞吐量)No memory budget to manage; availability and latency per region become the constraint. Your data leaves the machine.不用再管内存预算;各区域的可用性和延迟成为新的约束。你的数据会离开本机。04
agent-server gateway: keys, rate limits, quotasagent-server 网关:密钥、限流、配额Unity Gateway: permissions, rate limits, usage tracking, inference tablesUnity Gateway:权限、限流、用量追踪、推理表You stop writing auth code. Task-based routing still lives in your code.你不用再写认证代码。按任务的路由仍然写在你的代码里。05
model_router.py and the local-then-cloud fallback chainmodel_router.py 以及先本地后云端的兜底链路router.py with the same before-first-token rule; gateway fallbacks for availability沿用“只在首 token 前兜底”规则的 router.py;可用性交给网关兜底Same rule, fewer local failure modes (no model loading, no keep-alive).规则相同,本地特有的失败情形更少(没有模型加载,没有 keep-alive)。05
.env files, chmod 600chmod 600 的 .env 文件Secret scopes and service principalsSecret scope 与服务主体Reading a secret becomes a permission you can audit.读取密钥变成了一项可以审计的权限。03
knowledge-bank/ folders and source_authority.jsonknowledge-bank/ 目录与 source_authority.jsonA Unity Catalog volume with the same tree目录结构相同的 Unity Catalog volumeTier rules unchanged; access is now a grant on the volume.等级规则不变;访问权限变成了 volume 上的授权。06
The ledger, intake cursor, kb_extract.py台账、收件游标、kb_extract.pyDelta tables with MERGE, an hourly Lakeflow job使用 MERGE 的 Delta 表,每小时运行的 Lakeflow jobIdempotence by hash and MERGE instead of a file cursor; history via time travel.幂等性靠哈希和 MERGE 实现,而不是文件游标;历史靠 time travel。07
Graph edges (defines, cites, section) in PostgresPostgres 中的图边(defines、cites、section)A three-column Delta table rebuilt from chunks从文本块重建的三列 Delta 表No graph database, as before.和以前一样,不需要图数据库。08
Postgres + pgvector HNSW + full-text, hybrid SQLPostgres + pgvector HNSW + 全文检索,混合检索 SQLLakebase + Lakebase Search (ANN, BM25), or AI SearchLakebase + Lakebase Search(ANN、BM25),或 AI SearchLakebase keeps your SQL and plans; AI Search removes the database and some control.Lakebase 保留你的 SQL 和执行计划;AI Search 去掉了数据库,也拿走了一部分控制权。09
tools/knowledge_base.py ranking: RRF, authority, dedup, expansiontools/knowledge_base.py 的排序:RRF、权威、去重、扩展ranking.py, unchanged, after either backendranking.py,原样保留,在任一后端之后执行Nothing: this is your code, and it is tested here.没有变化:这是你自己的代码,并在这里经过测试。12
Tool registry and the brainbank MCP server工具注册表与 brainbank MCP 服务Unity Catalog functions, managed MCP endpointsUnity Catalog 函数、托管 MCP 端点A tool is governed like a table; any MCP client can call it with OAuth.工具像表一样被治理;任何 MCP 客户端都可以用 OAuth 调用它。14
AGENT.md and skills/*/SKILL.mdAGENT.md 与 skills/*/SKILL.mdMLflow prompt registry in Unity Catalog, @production aliasUnity Catalog 中的 MLflow 提示词注册表,@production 别名Rollback is moving an alias, no redeploy.回滚就是移动别名,无需重新部署。15
memory_store.py, conversation index, recall toolmemory_store.py、对话索引、回忆工具Lakebase Postgres tables, partition = signed-in userLakebase Postgres 表,分区 = 登录用户The partition now comes from platform sign-in, which is stronger than a key.分区现在来自平台登录,这比密钥更可靠。16
agent_loop.py, graph.py, answer_guard.py, stream gateagent_loop.py、graph.py、answer_guard.py、流式闸门OpenAI Agents SDK app template + harness.py + answer_guard.pyOpenAI Agents SDK 应用模板 + harness.py + answer_guard.pyThe SDK provides the loop and tracing; triage, budget and guard stay yours.SDK 提供循环和追踪;分流、预算和护栏仍由你负责。17
Install-Autostart, supervised services, Tailscale funnelInstall-Autostart、受守护的服务、Tailscale funnelDatabricks Apps deployed by an asset bundle由 asset bundle 部署的 Databricks AppsCallers sign in with OAuth; the app has its own identity and grants.调用方用 OAuth 登录;App 拥有自己的身份和授权。18
Sealed eval folder, nightly chat and stream evals封存的评估目录、夜间对话与流式评估UC evaluation dataset, mlflow.genai.evaluate, code scorers, a digestUC 评估数据集、mlflow.genai.evaluate、代码 scorer、摘要The seal is a grant plus a digest; repeats and spread are unchanged.封存 = 一条授权 + 一个摘要;重复运行和波动范围的做法不变。19
launchd timers and the duty-cycle schedulerlaunchd 定时器与占空比调度器Lakeflow Jobs on serverless, in the bundlebundle 中定义的 serverless Lakeflow JobsNo GPU contention, so no duty cycle; cost is the new limit.没有 GPU 争用,所以不需要占空比;成本成了新的限制。20
self_observe.py and the cursor tableself_observe.py 与游标表A report-mode job over MLflow traces, cursor in Delta基于 MLflow 追踪、以报告模式运行的 job,游标存在 Delta 中Same discipline: prove, report, a person applies.纪律相同:证明、报告、由人应用。21
Check-All-LLM-Status, pg_backup.shCheck-All-LLM-Status、pg_backup.shSystem tables dashboard, alerts, Delta time travel, Lakebase branches系统表仪表盘、告警、Delta time travel、Lakebase 分支You watch spend daily; backups are built in but restores still need a test.你需要每天关注花费;备份是内置的,但恢复仍需测试。22
This tutor and datamatter on Vercel, local-first chainVercel 上的本教程站与 datamatter,本地优先链路Stays on Vercel; Databricks becomes one more link via M2M OAuth仍留在 Vercel;Databricks 通过 M2M OAuth 成为链路中的又一个环节Apps require sign-in, so a public site cannot be one.App 需要登录,所以公开网站不能做成 App。23

Build order and dependencies构建顺序与依赖

Click a step to see what it needs (green) and what it unlocks (purple). Steps in the same phase with no line between them can be built in either order.点击某一步,查看它需要什么(绿色)和它解锁什么(紫色)。同一阶段中彼此没有连线的步骤,先做哪个都可以。

1 Foundation: identity, storage layout, secrets地基:身份、存储布局、密钥
2 Models: the lineup and the gateway模型:模型阵容与网关
3 Knowledge: files, ledger, chunks, graph知识:文件、台账、文本块、图
4 Retrieval: choose a backend, keep the ranking检索:选择后端,保留排序逻辑
5 The agent: tools, prompts, memory, harness智能体:工具、提示词、记忆、Harness
6 Ship and evaluate上线与评估
7 Learn and operate学习与运维

1 Foundation: identity, storage layout, secrets地基:身份、存储布局、密钥

Before any model or document moves, decide who is acting and where everything lives. On the Mac these were implicit: you were the only user and the disk was the catalog. On Databricks every read and write is checked against an identity and a Unity Catalog object, so they come first.在迁移任何模型或文档之前,先确定由谁来操作、所有东西放在哪里。在 Mac 上这些都是隐含的:你是唯一的用户,磁盘就是目录。在 Databricks 上,每一次读写都要对照一个身份和一个 Unity Catalog 对象做检查,所以这些必须最先做。

01Connect the CLI and prove what the workspace offers连接 CLI,并确认工作区提供了哪些能力
Replaces替代Check-All-LLM-Status: one screen that lists every service and model on the machine.Check-All-LLM-Status:一屏列出本机所有服务和模型。
Do first先完成Nothing. This is a starting point.没有。这是一个起点。

Why this step, and why here为什么要做这一步,为什么在这里

Everything later assumes four things: you can log in with OAuth, Unity Catalog is enabled, the model endpoints you plan to use exist in your region, and there is a SQL warehouse. Finding out at step 17 that the workspace has no Qwen endpoint costs a day. Finding out now costs a minute.后面的每一步都假定四件事成立:你能用 OAuth 登录,Unity Catalog 已启用,你打算使用的模型端点在你的区域存在,并且有一个 SQL warehouse。到第 17 步才发现工作区没有 Qwen 端点,会浪费一天;现在就发现,只花一分钟。

What it does它做什么

Logs the CLI in under a named profile, mints an OAuth token, and lists catalogs, serving endpoints and warehouses. It is the Databricks version of the local inventory: what exists, before you build on it.用一个具名 profile 登录 CLI,生成 OAuth 令牌,并列出 catalog、服务端点和 warehouse。这是本地资产清单的 Databricks 版本:在动手之前先弄清有什么。

How to do it怎么做

  1. Install a recent Databricks CLI (one that has the `bundle` and `apps` command groups).安装较新版本的 Databricks CLI(需要带有 `bundle` 和 `apps` 命令组)。
  2. Set DATABRICKS_HOST to your workspace URL and run the script. A browser opens once for the OAuth login.把 DATABRICKS_HOST 设为你的工作区 URL,然后运行脚本。浏览器会弹出一次用于 OAuth 登录。
  3. Save the printed endpoint list. Step 4 compares it with the lineup.保存打印出来的端点列表。第 4 步会拿它和模型阵容做对比。
  4. Export DATABRICKS_CONFIG_PROFILE=agent in your shell so the Python SDK uses the same login.在 shell 里 export DATABRICKS_CONFIG_PROFILE=agent,让 Python SDK 使用同一个登录。

Scripts脚本

setup/00_workspace.sh · bash -n passes
#!/usr/bin/env bash
# Step 1. Connect the CLI to the workspace and prove what you can reach.
# Run on your laptop. Needs the Databricks CLI (a recent version that has `bundle` and `apps`).
#   brew tap databricks/tap && brew install databricks      # macOS
#   or: curl -fsSL https://raw.githubusercontent.com/databricks/setup-cli/main/install.sh | sh
set -euo pipefail

HOST="${DATABRICKS_HOST:?set DATABRICKS_HOST=https://<workspace-host>}"
PROFILE="${DATABRICKS_PROFILE:-agent}"

databricks --version

# OAuth user login (U2M). Opens a browser once, then caches a refreshable token under the profile.
databricks auth login --host "$HOST" --profile "$PROFILE"

echo "== who am I"
databricks current-user me --profile "$PROFILE" -o json | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("userName"))'

echo "== a short-lived OAuth token can be minted (the deployed agent only accepts these)"
databricks auth token --profile "$PROFILE" >/dev/null && echo "token: ok"

echo "== Unity Catalog is reachable: catalogs I can see"
databricks catalogs list --profile "$PROFILE" -o json | python3 -c 'import json,sys; print([c["name"] for c in json.load(sys.stdin)][:20])'

echo "== serving endpoints this workspace exposes (look for databricks-qwen*, databricks-gemini*, *embedding*)"
databricks serving-endpoints list --profile "$PROFILE" -o json \
  | python3 -c 'import json,sys; d=json.load(sys.stdin); d=d if isinstance(d,list) else d.get("endpoints",[]); print("\n".join(sorted(e["name"] for e in d)))'

echo "== SQL warehouses (needed to run setup/01_catalog.sql)"
databricks warehouses list --profile "$PROFILE" -o json | python3 -c 'import json,sys; d=json.load(sys.stdin); d=d if isinstance(d,list) else d.get("warehouses",[]); [print(w["id"], w["name"], w.get("state")) for w in d]'

How to read the result如何解读结果

  • `token: ok` means OAuth works. The deployed agent accepts only OAuth tokens, so if this fails, nothing later will answer you.`token: ok` 说明 OAuth 可用。已部署的智能体只接受 OAuth 令牌,所以这里失败的话,后面没有任何东西会回应你。
  • The endpoint list is the truth for your workspace. The vendor's model page lists what exists somewhere; your region may have fewer.端点列表才是你这个工作区的真实情况。厂商的模型页面列的是某处存在的模型,你所在的区域可能更少。
  • No warehouse in the list means you cannot run the SQL files in steps 2 and 14 yet. Ask an admin for one, or create a serverless warehouse.列表里没有 warehouse,说明你还不能运行第 2 步和第 14 步的 SQL 文件。请管理员开一个,或者自己创建一个 serverless warehouse。

Troubleshooting排障

You see现象Why原因Do this处理
`databricks auth login` opens no browser or hangs`databricks auth login` 没有打开浏览器,或者卡住Remote shell or a blocked localhost callback port.处于远程 shell 中,或者 localhost 回调端口被拦截。Run it on a machine with a browser, then copy ~/.databrickscfg; or use a service principal with client ID and secret (M2M).在有浏览器的机器上运行,再复制 ~/.databrickscfg;或者改用带 client ID 和 secret 的服务主体(M2M)。
`catalogs list` returns an error about Unity Catalog`catalogs list` 报 Unity Catalog 相关的错误The workspace is not attached to a metastore.工作区没有挂载 metastore。An account admin must assign a metastore. Nothing in this guide works without Unity Catalog.需要账号管理员分配 metastore。没有 Unity Catalog,本指南里的任何步骤都无法进行。
`unknown command "bundle"` or `"apps"``unknown command "bundle"` 或 `"apps"`An old CLI, often the legacy pip package named databricks-cli.CLI 版本太旧,常见的是名为 databricks-cli 的旧版 pip 包。Uninstall the pip package and install the current CLI from the vendor's setup-cli script or Homebrew tap.卸载这个 pip 包,用厂商的 setup-cli 脚本或 Homebrew tap 安装当前版本的 CLI。
Done when完成标准All five sections print, and the endpoint list contains at least one chat model and one embedding model.五个部分都有输出,且端点列表里至少有一个对话模型和一个 embedding 模型。
Not confirmed on a vendor page未在厂商页面上确认The `-o json` output shapes of `serving-endpoints list` and `warehouses list` differ between CLI versions; the script accepts both a list and an object.不同 CLI 版本中 `serving-endpoints list` 和 `warehouses list` 的 `-o json` 输出结构不同;脚本两种结构(列表和对象)都能处理。
02Create the catalog, schemas, volume and core tables创建 catalog、schema、volume 和核心表
Replaces替代The folder layout under the AI data drive, the Postgres schema, and the read-only sealed eval folder.AI 数据盘下的目录结构、Postgres 的表结构,以及只读封存的评估目录。

Why this step, and why here为什么要做这一步,为什么在这里

Permissions in Unity Catalog attach to catalogs, schemas, tables and volumes. If you put chunks, logs and sealed eval questions in one schema, you cannot give the jobs write access to chunks without also letting them edit the exam. Splitting by concern on day one makes the seal a grant, not a promise.Unity Catalog 的权限是挂在 catalog、schema、表和 volume 上的。如果把文本块、日志和封存的评估问题放在同一个 schema,你就没法只给 job 文本块的写权限,而不同时让它能改考题。第一天就按职责拆分,封存就成了一条授权,而不是一句承诺。

What it does它做什么

Creates catalog agentlab with schemas kb, ops and evals, a volume for raw files, the ledger and chunk tables with change data feed on, a findings table, and the grants that separate builders, jobs and the eval owner.创建 catalog agentlab 及其下的 kb、ops、evals 三个 schema,一个存放原始文件的 volume,开启了 change data feed 的台账表和文本块表,一张 findings 表,以及区分开发者、job 和评估负责人的授权。

How to do it怎么做

  1. Open the SQL editor, attach a warehouse, paste the file and run it as a user who can create catalogs.打开 SQL 编辑器,挂上 warehouse,粘贴文件内容,以有权限创建 catalog 的用户身份运行。
  2. Replace `agent-builders` and `agent-jobs-sp` with your group and your jobs' service principal before the GRANT lines.在执行 GRANT 语句前,把 `agent-builders` 和 `agent-jobs-sp` 换成你的用户组和 job 的服务主体。
  3. Keep `delta.enableChangeDataFeed = true` on chunks. Both retrieval backends need it for incremental sync.文本块表上要保留 `delta.enableChangeDataFeed = true`。两种检索后端做增量同步都依赖它。
  4. If you rename the catalog, set AGENT_CATALOG everywhere; config.py reads every name from the environment.如果你改了 catalog 名字,请在所有地方设置 AGENT_CATALOG;config.py 的所有名字都从环境变量读取。

Scripts脚本

setup/01_catalog.sql · read only
-- Step 2. The storage layout. Run in a SQL editor attached to a warehouse, as a user who can create catalogs.
-- One catalog for the agent. One schema per concern, so permissions follow the concern:
--   kb     documents, chunks, ledger, edges     (the agent reads; ingestion jobs write)
--   ops    logs, findings, reports              (jobs write; people read)
--   evals  frozen questions, gold sets          (sealed: almost nobody writes)

CREATE CATALOG IF NOT EXISTS agentlab COMMENT 'Replica of the local agent build';
CREATE SCHEMA  IF NOT EXISTS agentlab.kb    COMMENT 'Knowledge bank: raw files, chunks, ledger, graph edges';
CREATE SCHEMA  IF NOT EXISTS agentlab.ops   COMMENT 'Run logs, self-observation findings, reports';
CREATE SCHEMA  IF NOT EXISTS agentlab.evals COMMENT 'Sealed evaluation material';

-- The landing zone for source files. Same folder taxonomy as knowledge-bank/ on the local machine.
CREATE VOLUME IF NOT EXISTS agentlab.kb.raw COMMENT 'Source documents, uploaded as-is';

-- The ledger: one row per source file version. Intake is a MERGE on (path), so a re-run changes nothing.
CREATE TABLE IF NOT EXISTS agentlab.kb.ledger (
  path        STRING NOT NULL,
  sha256      STRING NOT NULL,
  bytes       BIGINT,
  status      STRING,           -- accepted | rejected | retired
  reason      STRING,
  tier        INT,
  updated_at  TIMESTAMP
) TBLPROPERTIES (delta.enableChangeDataFeed = true);

-- The chunk table. Change data feed is required for a Delta Sync index on a standard endpoint
-- and for Triggered/Continuous synced tables into Lakebase.
CREATE TABLE IF NOT EXISTS agentlab.kb.chunks (
  chunk_id    STRING NOT NULL,
  source      STRING NOT NULL,
  collection  STRING NOT NULL,
  chunk_index INT,
  context     STRING,           -- heading path, embedded together with the text
  text        STRING,
  embed_text  STRING,           -- context + text: what the embedding model sees
  embedding   ARRAY<FLOAT>,     -- filled by ingest.py when you use the Lakebase backend
  tier        INT,
  retired     BOOLEAN,
  sha256      STRING,
  CONSTRAINT chunks_pk PRIMARY KEY (chunk_id)
) TBLPROPERTIES (delta.enableChangeDataFeed = true);

CREATE TABLE IF NOT EXISTS agentlab.ops.findings (
  day STRING, signal STRING, key STRING, proof STRING, created_at TIMESTAMP
);

-- Who may do what. Replace the principal names with your groups and the jobs' service principal.
GRANT USE CATALOG ON CATALOG agentlab TO `agent-builders`;
GRANT USE SCHEMA, SELECT ON SCHEMA agentlab.kb TO `agent-builders`;
GRANT USE SCHEMA, SELECT, MODIFY, CREATE TABLE ON SCHEMA agentlab.kb TO `agent-jobs-sp`;   -- edges.py overwrites its table
GRANT READ VOLUME, WRITE VOLUME ON VOLUME agentlab.kb.raw TO `agent-jobs-sp`;
GRANT USE SCHEMA, SELECT, MODIFY, CREATE TABLE ON SCHEMA agentlab.ops TO `agent-jobs-sp`;  -- the learner creates its cursor table
-- The seal: builders may read the eval schema, only the eval owner may write it.
GRANT USE SCHEMA, SELECT ON SCHEMA agentlab.evals TO `agent-builders`;
GRANT USE SCHEMA, SELECT ON SCHEMA agentlab.evals TO `agent-jobs-sp`;      -- the nightly eval reads, never writes
-- The app's own service principal (created in step 18) needs: USE SCHEMA + SELECT on kb, EXECUTE on the tools.

SHOW GRANTS ON SCHEMA agentlab.evals;
src/common/config.py · compiles
"""One place for every name the replication uses.

Every job, notebook and the agent read their names from here, so moving to another
catalog, workspace or model lineup is a change to environment variables, not to code.
The defaults mirror the local build: one catalog for the agent, one schema per concern.
"""
from __future__ import annotations

import os
from dataclasses import dataclass, field


def _env(name: str, default: str) -> str:
    return os.environ.get(name, default)


def _f(name: str, default: str, cast=str):
    """Read the variable when Config() is created, not when this module is imported,
    so a job can set AGENT_CATALOG from its arguments and then build the config."""
    return field(default_factory=lambda: cast(_env(name, default)))


@dataclass(frozen=True)
class Config:
    catalog: str = _f("AGENT_CATALOG", "agentlab")
    kb_schema: str = _f("AGENT_KB_SCHEMA", "kb")          # documents, chunks, ledger, edges
    ops_schema: str = _f("AGENT_OPS_SCHEMA", "ops")       # logs, findings, eval history
    eval_schema: str = _f("AGENT_EVAL_SCHEMA", "evals")   # sealed: frozen questions, gold sets
    volume: str = _f("AGENT_VOLUME", "raw")               # landing zone for source files

    # Model lineup. Local build: qwen3.8:27b (default) -> qwen3.6:35b-a3b (fast) -> gemini flash lite (cloud).
    # The names below are pay-per-token endpoints listed on the vendor's supported-models page in
    # October 2026. Run src/models/bench.py first: it prints which of them your workspace actually has.
    chat_default: str = _f("AGENT_CHAT_DEFAULT", "databricks-qwen35-122b-a10b")
    chat_fast: str = _f("AGENT_CHAT_FAST", "databricks-qwen3-next-80b-a3b-instruct")
    chat_fallback: str = _f("AGENT_CHAT_FALLBACK", "databricks-gemini-3-5-flash-lite")
    embedding: str = _f("AGENT_EMBEDDING", "databricks-qwen3-embedding-0-6b")
    embedding_dim: int = _f("AGENT_EMBEDDING_DIM", "1024", int)

    # Retrieval backend: "ai_search" (managed index) or "lakebase" (Postgres hybrid, closest to the local pgvector build).
    retrieval: str = _f("AGENT_RETRIEVAL", "lakebase")
    search_endpoint: str = _f("AGENT_SEARCH_ENDPOINT", "agent_search")

    # Lakebase (memory and, optionally, retrieval).
    pg_endpoint: str = _f("ENDPOINT_NAME", "")             # from the Lakebase console Connect dialog
    pg_host: str = _f("PGHOST", "")
    pg_database: str = _f("PGDATABASE", "databricks_postgres")
    pg_user: str = _f("PGUSER", "")                       # the service principal's client ID

    # Ranking, same constants as the local build (module 5).
    rrf_k: int = 60
    candidates: int = 20
    authority_weight: float = 0.0004

    secret_scope: str = _f("AGENT_SECRET_SCOPE", "agent")
    flags: dict = field(default_factory=lambda: {
        "RAG_HYBRID": _env("RAG_HYBRID", "1") == "1",
        "RAG_AUTHORITY": _env("RAG_AUTHORITY", "1") == "1",
        "RAG_DEDUP": _env("RAG_DEDUP", "1") == "1",
        "RAG_GRAPH": _env("RAG_GRAPH", "1") == "1",
    })

    def table(self, schema: str, name: str) -> str:
        return f"{self.catalog}.{schema}.{name}"

    @property
    def chunks(self) -> str:
        return self.table(self.kb_schema, "chunks")

    @property
    def ledger(self) -> str:
        return self.table(self.kb_schema, "ledger")

    @property
    def edges(self) -> str:
        return self.table(self.kb_schema, "edges")

    @property
    def index(self) -> str:
        return self.table(self.kb_schema, "chunks_index")

    @property
    def raw_path(self) -> str:
        return f"/Volumes/{self.catalog}/{self.kb_schema}/{self.volume}"

How to read the result如何解读结果

  • `SHOW GRANTS ON SCHEMA agentlab.evals` must show SELECT for builders and no MODIFY for anyone except the owner. That line is the seal.`SHOW GRANTS ON SCHEMA agentlab.evals` 应该显示开发者只有 SELECT,除负责人外没有人有 MODIFY。这一行就是封存。
  • The PRIMARY KEY on chunks is informational in Delta (not enforced), but the index and the synced table both read it as the key, so keep chunk_id unique yourself. ingest.py does, by MERGE.文本块表上的 PRIMARY KEY 在 Delta 中只是信息性的(不强制),但索引和同步表都会把它当作主键,所以你自己必须保证 chunk_id 唯一。ingest.py 用 MERGE 做到了这一点。

Troubleshooting排障

You see现象Why原因Do this处理
PERMISSION_DENIED on CREATE CATALOGCREATE CATALOG 报 PERMISSION_DENIEDOnly metastore admins or users with CREATE CATALOG can create one.只有 metastore 管理员或拥有 CREATE CATALOG 权限的用户才能创建。Ask for a catalog to be created for you, then run the rest with AGENT_CATALOG set to its name.请管理员为你创建一个 catalog,然后把 AGENT_CATALOG 设为它的名字,再运行其余部分。
PRIMARY KEY constraint rejectedPRIMARY KEY 约束被拒绝Informational constraints need the column to be NOT NULL and a recent runtime or warehouse.信息性约束要求该列为 NOT NULL,并且需要较新的运行时或 warehouse。Keep NOT NULL on chunk_id; if your warehouse still refuses, drop the constraint line. The index takes the key as an argument anyway.保留 chunk_id 上的 NOT NULL;如果 warehouse 仍然拒绝,就删掉约束那一行。索引本来就会把主键作为参数传入。
GRANT fails with principal not foundGRANT 报找不到主体The group or service principal name does not exist in the account.账号里不存在这个用户组或服务主体名。Create the group and the service principal first (admin UI), then rerun only the GRANT lines.先在管理界面创建用户组和服务主体,然后只重跑 GRANT 语句。
Done when完成标准The four schemas-and-volume objects exist and SHOW GRANTS matches the three roles.四个 schema 和 volume 对象都已存在,SHOW GRANTS 的结果与三种角色相符。
03Put secrets in a secret scope and create the service principal把密钥放进 secret scope,并创建服务主体
Replaces替代.env files with chmod 600, the gateway's issued keys, and the funnel secret.chmod 600 的 .env 文件、网关签发的密钥,以及 funnel 的 secret。

Why this step, and why here为什么要做这一步,为什么在这里

Models hosted by Databricks need no key, so the secret list is shorter than on the Mac. What remains (an external tool token, the public tutor's credentials) must never appear in a notebook, a bundle file or git. A scope is the only place code reads them from by name, and reading is itself a permission.Databricks 托管的模型不需要密钥,所以需要管理的密钥比 Mac 上少。剩下的那些(外部工具的令牌、公开教程站的凭证)绝不能出现在 notebook、bundle 文件或 git 里。scope 是代码按名字读取密钥的唯一地方,而读取本身也是一种权限。

What it does它做什么

Creates scope `agent`, shows how to put a secret from stdin so it stays out of shell history, and names the service principal that jobs and the eval will run as.创建名为 `agent` 的 scope,演示如何通过 stdin 写入密钥,使其不进入 shell 历史,并指明 job 和评估将以哪个服务主体身份运行。

How to do it怎么做

  1. Run the script. Uncomment the `put` line only for secrets that live outside Databricks.运行脚本。只有存在于 Databricks 之外的密钥才需要取消 `put` 那一行的注释。
  2. Create a service principal in the admin UI, add it to `agent-jobs-sp`, and generate an OAuth secret for it.在管理界面创建服务主体,把它加入 `agent-jobs-sp`,并为它生成 OAuth secret。
  3. Store that client ID and secret in your password manager, not in the scope it is used to read.把这个 client ID 和 secret 存进你的密码管理器,而不是存进它要读取的那个 scope。

Scripts脚本

setup/02_secrets.sh · bash -n passes
#!/usr/bin/env bash
# Step 3. Secrets and identities.
# On the local machine the keys sit in .env files with chmod 600. On Databricks they sit in a
# secret scope, and code reads them by name. A secret never goes in a notebook, a bundle or git.
set -euo pipefail
PROFILE="${DATABRICKS_PROFILE:-agent}"
SCOPE="${AGENT_SECRET_SCOPE:-agent}"

databricks secrets create-scope "$SCOPE" --profile "$PROFILE" || echo "scope $SCOPE exists"

# Only needed for things that live outside Databricks, for example the public tutor on Vercel
# calling back into the workspace, or an external MCP server. Models hosted by Databricks need no key.
put() {  # put <key>  (reads the value from stdin so it never appears in shell history)
  databricks secrets put-secret "$SCOPE" "$1" --profile "$PROFILE"
}
# printf '%s' "$EXTERNAL_TOOL_TOKEN" | put external-tool-token

databricks secrets list-secrets "$SCOPE" --profile "$PROFILE"

# Service principal for jobs and the app. Create it in the account or workspace admin UI,
# add it to the group `agent-jobs-sp` used in 01_catalog.sql, then give it an OAuth secret
# (machine-to-machine). The app gets its own service principal automatically when it is created.
echo "Next: create a service principal for jobs and add it to agent-jobs-sp (admin UI)."
python
# inside a job or notebook
token = dbutils.secrets.get(scope="agent", key="external-tool-token")
print(token)   # prints [REDACTED]: notebooks mask secret values on output

How to read the result如何解读结果

  • `list-secrets` shows key names and timestamps, never values. If you can read a value back from the CLI, something is wrong with how it was stored.`list-secrets` 只显示键名和时间戳,从不显示值。如果你能从 CLI 读回密钥的值,说明存储方式出了问题。
  • [REDACTED] in notebook output is the platform masking the value, not proof the secret is right. Test it by using it.notebook 输出中的 [REDACTED] 是平台在遮蔽这个值,并不能证明密钥是对的。要验证,就实际用一次。

Troubleshooting排障

You see现象Why原因Do this处理
`create-scope` fails: scope already exists`create-scope` 失败:scope 已存在A previous run created it.之前的运行已经创建过了。Harmless; the script continues. Use `list-scopes` to confirm the owner.无害,脚本会继续执行。可用 `list-scopes` 确认所有者。
A job gets PERMISSION_DENIED reading a secretjob 读取密钥时报 PERMISSION_DENIEDThe job runs as the service principal, which has no READ on the scope.job 以服务主体身份运行,而它对该 scope 没有 READ 权限。`databricks secrets put-acl agent <sp-application-id> READ`.`databricks secrets put-acl agent <sp-application-id> READ`。
Done when完成标准The scope exists, the service principal exists and is in the jobs group.scope 已存在,服务主体已存在并已加入 job 用户组。
Not confirmed on a vendor page未在厂商页面上确认The `put-acl` command form in the troubleshooting line is from the CLI's command list, not from the secrets page read for this guide.排障那一行中 `put-acl` 的命令写法来自 CLI 的命令列表,而不是本指南参考的密钥文档页面。

2 Models: the lineup and the gateway模型:模型阵容与网关

On the Mac you chose models by what fit in unified memory and measured them yourself. On Databricks memory is not your problem, availability and latency from your region are. The rule that carries over unchanged: measure first, then choose, and never switch models after the first token.在 Mac 上,你按统一内存能装下什么来选模型,并亲自测量。在 Databricks 上,内存不再是你的问题,你所在区域的可用性和延迟才是。原样保留的规则是:先测量再选择,首个 token 发出后绝不换模型。

04Choose the lineup by measuring it通过测量来确定模型阵容
Replaces替代ollama-env.sh and model_catalog.json: default qwen3.8:27b, fast qwen3.6:35b-a3b, cloud fallback gemini flash lite.ollama-env.sh 和 model_catalog.json:默认 qwen3.8:27b,快速 qwen3.6:35b-a3b,云端兜底 gemini flash lite。

Why this step, and why here为什么要做这一步,为什么在这里

The lineup decides latency, cost and answer quality for everything after it, and the embedding model decides the index. Changing the embedding model later means re-embedding every chunk, so it is chosen here, once, and recorded. Time to first token is what the user feels; it varies by endpoint and by hour, so the number must come from your workspace.模型阵容决定了后续所有环节的延迟、成本和回答质量,而 embedding 模型决定了索引。日后更换 embedding 模型意味着要重新嵌入每一个文本块,所以要在这里一次选定并记录下来。首 token 时间是用户直接感受到的,它随端点和时段变化,所以这个数字必须来自你自己的工作区。

What it does它做什么

Checks which of the configured endpoints exist, streams the same prompt three times through each chat model and prints the median time to first token and tokens per second, then prints the embedding dimension.检查配置中的端点哪些存在,对每个对话模型用同一个提示词流式请求三次,打印首 token 时间和每秒 token 数的中位数,然后打印 embedding 的维度。

How to do it怎么做

  1. `pip install -U databricks-sdk databricks-openai` on your laptop.在你的笔记本上执行 `pip install -U databricks-sdk databricks-openai`。
  2. Run `python replicate/databricks/src/models/bench.py` with your profile exported.export 好 profile 后,运行 `python replicate/databricks/src/models/bench.py`。
  3. If an endpoint is MISSING, pick the nearest one from step 1's list and set AGENT_CHAT_DEFAULT, AGENT_CHAT_FAST or AGENT_CHAT_FALLBACK.如果某个端点显示 MISSING,就从第 1 步的列表里挑最接近的一个,设置 AGENT_CHAT_DEFAULT、AGENT_CHAT_FAST 或 AGENT_CHAT_FALLBACK。
  4. Run it again at a busy hour. Keep the slower of the two numbers.在繁忙时段再跑一次。两次结果取较慢的那个。
  5. Set AGENT_EMBEDDING_DIM to the printed dimension. Never change it without re-embedding.把 AGENT_EMBEDDING_DIM 设为打印出的维度。没有重新嵌入的话,绝不要改它。

Scripts脚本

src/models/bench.py · compiles
"""Step 4. Which models does this workspace have, and how fast are they from where the agent runs?

The local build measured time to first token and tokens per second on the Mac (module 1).
Here the same two numbers decide the lineup, because pay-per-token endpoints differ by
region, by load and by model, and the vendor's list is not a promise for your workspace.

  pip install -U databricks-sdk databricks-openai
  python bench.py                      # uses your CLI profile (DATABRICKS_CONFIG_PROFILE=agent)
"""
from __future__ import annotations

import os
import statistics
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402

PROMPT = [{"role": "user", "content": "List three reasons a travel claim can be rejected. One line each."}]


def available(names: list) -> dict:
    from databricks.sdk import WorkspaceClient

    have = {e.name for e in WorkspaceClient().serving_endpoints.list()}
    return {n: n in have for n in names}


def measure(client, model: str, runs: int = 3) -> dict:
    """Stream one answer `runs` times. First token time is what a user feels; tokens/s is what a long answer costs."""
    ttft, tps = [], []
    for _ in range(runs):
        t0 = time.perf_counter()
        first, chars = None, 0
        stream = client.chat.completions.create(model=model, messages=PROMPT, max_tokens=200, stream=True)
        for chunk in stream:
            if not chunk.choices:
                continue
            delta = chunk.choices[0].delta.content or ""
            if delta and first is None:
                first = time.perf_counter() - t0
            chars += len(delta)
        total = time.perf_counter() - t0
        if first is None:
            raise RuntimeError("stream ended with no text")
        ttft.append(first)
        tps.append((chars / 4) / max(total - first, 1e-6))        # ~4 characters per token, same estimate as module 1
    return {"ttft_s": round(statistics.median(ttft), 2), "tok_s": round(statistics.median(tps), 1),
            "ttft_spread": (round(min(ttft), 2), round(max(ttft), 2))}


def main() -> None:
    from databricks_openai import DatabricksOpenAI

    cfg = Config()
    chat = [cfg.chat_default, cfg.chat_fast, cfg.chat_fallback]
    have = available(chat + [cfg.embedding])
    for name, ok in have.items():
        print(f"{'present' if ok else 'MISSING':8} {name}")
    client = DatabricksOpenAI()
    for model in chat:
        if not have[model]:
            continue
        try:
            print(f"{model:45} {measure(client, model)}")
        except Exception as e:                                      # noqa: BLE001 - report and keep going
            print(f"{model:45} FAILED {type(e).__name__}: {str(e)[:160]}")
    if have[cfg.embedding]:
        v = client.embeddings.create(model=cfg.embedding, input=["lodging cap for a city trip"]).data[0].embedding
        print(f"{cfg.embedding:45} dimension {len(v)} (config says {cfg.embedding_dim})")


if __name__ == "__main__":
    main()

How to read the result如何解读结果

  • The mapping from the local lineup: databricks-qwen35-122b-a10b stands in for the 27B default (a mixture of experts with 10B active), databricks-qwen3-next-80b-a3b-instruct for the 35B-A3B fast model (3B active, the same idea), and databricks-gemini-3-5-flash-lite is the same family as the local cloud fallback.与本地阵容的对应关系:databricks-qwen35-122b-a10b 替代 27B 默认模型(混合专家,激活 10B),databricks-qwen3-next-80b-a3b-instruct 替代 35B-A3B 快速模型(激活 3B,思路相同),databricks-gemini-3-5-flash-lite 与本地的云端兜底属于同一系列。
  • A first token under about 1.5 s feels immediate in chat. Above 4 s, users start retyping. Compare with your local numbers from module 1: if the hosted model is slower than the Mac, the tutor's local-first chain was the right call for interactive use.对话中首 token 在约 1.5 秒以内会让人觉得是即时的;超过 4 秒,用户就会开始重新输入。和第 1 模块中的本地数据比较:如果托管模型比 Mac 还慢,说明教程站“本地优先”的链路对交互场景是正确的选择。
  • A wide ttft_spread (for example 0.8 to 6 s) means a shared, loaded endpoint. That is an argument for the fast model on chat turns, or for provisioned throughput if the workload justifies it.如果 ttft_spread 很宽(例如 0.8 到 6 秒),说明这是一个共享且负载较高的端点。这就是对话轮次改用快速模型的理由,或者在工作负载足够大时改用预置吞吐量(provisioned throughput)。
  • tok_s is estimated at 4 characters per token, as in module 1. Use it to compare models with each other, not as an exact figure.tok_s 按每 token 4 个字符估算,与第 1 模块相同。用它来比较模型之间的快慢,不要当作精确数字。

Troubleshooting排障

You see现象Why原因Do this处理
Every model prints MISSING所有模型都显示 MISSINGFoundation Model APIs are not enabled in the workspace, or the region has none of these names.工作区没有启用 Foundation Model API,或者该区域没有这些名字的模型。Pick names from step 1's list. If the list has no `databricks-` chat models at all, an admin must enable Foundation Model APIs.从第 1 步的列表里选名字。如果列表里完全没有 `databricks-` 开头的对话模型,就需要管理员启用 Foundation Model API。
FAILED RateLimitError or HTTP 429报 FAILED RateLimitError 或 HTTP 429Pay-per-token endpoints have per-workspace rate limits, and a gateway rate limit may also apply.按 token 计费的端点有工作区级别的限流,网关层面的限流也可能生效。Rerun with fewer runs; for production traffic, request higher limits or use provisioned throughput.减少运行次数后重跑;生产流量的话,申请更高的限额或改用预置吞吐量。
`stream ended with no text`报 `stream ended with no text`Some reasoning models stream reasoning first, or the endpoint does not support streaming chat.有些推理模型会先流式输出推理内容,或者该端点不支持流式对话。Try the model without stream=True in a notebook to see the response shape, then choose another model for the chat role.在 notebook 里去掉 stream=True 试一下,看看响应的结构,然后为对话角色换一个模型。
Done when完成标准You have three present chat models with measured numbers and a recorded embedding dimension.你已有三个可用的对话模型及其实测数据,并记录了 embedding 的维度。
Not confirmed on a vendor page未在厂商页面上确认Endpoint names were read from the supported-models page in October 2026. Availability per region was not confirmed; the script exists to check it.端点名称来自 2026 年 10 月的支持模型页面。各区域的可用性未经确认;这个脚本就是用来检查这一点的。
05Route through the gateway and keep the fallback rule经由网关路由,并保留兜底规则
Replaces替代The agent-server gateway: keys, rate limits, quotas, and model_router.py with the primary, secondary, cloud chain.agent-server 网关:密钥、限流、配额,以及按主模型、次模型、云端顺序工作的 model_router.py。

Why this step, and why here为什么要做这一步,为什么在这里

On the Mac the gateway was your code: it checked keys, counted requests and swapped models. On Databricks the Unity Gateway does the first two for every endpoint, centrally, with usage logged. What it cannot know is your task: whether a turn is chat or analysis. So availability moves to the platform and task routing stays in your code, with the same rule as before: fall back only before the first token.在 Mac 上,网关是你自己的代码:它检查密钥、统计请求、切换模型。在 Databricks 上,Unity Gateway 会集中为每个端点完成前两件事,并记录用量。它无法知道的是你的任务:这一轮是闲聊还是分析。所以可用性交给平台,任务路由留在你的代码里,规则和以前一样:只在首个 token 之前兜底。

What it does它做什么

router.py builds the ordered lineup for a task and streams from the first model that produces text, recording why each earlier one failed. The gateway configuration (rate limits, usage tracking, inference tables, fallbacks) is set in the Unity Gateway UI.router.py 为某个任务构建有序的模型阵容,从第一个产出文本的模型开始流式输出,并记录前面每个模型失败的原因。网关配置(限流、用量追踪、推理表、兜底)在 Unity Gateway 界面里设置。

How to do it怎么做

  1. In the Unity Gateway UI, for each endpoint in the lineup, turn on usage tracking and an inference table in agentlab.ops.在 Unity Gateway 界面中,为阵容里的每个端点开启用量追踪,并在 agentlab.ops 下开启推理表。
  2. Set a per-user rate limit. Start at the limit your local gateway used per key; it is the same protection against one runaway client.设置每用户的限流。起点可以用本地网关为每个密钥设置的限额;它防范的是同一件事:某个客户端失控。
  3. Use the agent code's client with `use_ai_gateway=True` so calls are governed and logged.智能体代码中的客户端使用 `use_ai_gateway=True`,这样调用就会受到治理并被记录。
  4. Keep router.py for task choice. Use gateway fallbacks only for the same task's availability.任务选择仍由 router.py 负责。网关的兜底只用于同一任务下的可用性。

Scripts脚本

src/models/router.py · compiles
"""Step 5. The model router: pick a model per task, fall back only before the first token.

Local build (modules 1 and 2): model_router.py picks default, fast or vision; the gateway
falls back from the primary to the secondary local model and then to a cloud model, and it
only does so before any text has reached the user. The same rule holds here. Once a token has
been sent, a switch would splice two models' answers together.

The gateway can also do fallbacks and traffic splits on its own (configured in the Unity
Gateway UI). Use that for availability. Keep this router for choices that depend on the task.
"""
from __future__ import annotations

import os
import sys
import time
from typing import Iterator

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402

TASKS = {"default": "chat_default", "fast": "chat_fast", "fallback": "chat_fallback"}


def lineup(task: str, cfg: Config) -> list:
    first = getattr(cfg, TASKS.get(task, "chat_default"))
    order = [first, cfg.chat_default, cfg.chat_fast, cfg.chat_fallback]
    return list(dict.fromkeys(order))                     # keep order, drop repeats


def stream_with_fallback(client, messages: list, task: str = "default", cfg: Config | None = None,
                         first_token_s: float = 20.0) -> Iterator[tuple]:
    """Yields (model, text_delta). Tries the next model only if no text was produced yet."""
    cfg = cfg or Config()
    errors = []
    for model in lineup(task, cfg):
        sent = False
        t0 = time.monotonic()
        try:
            stream = client.chat.completions.create(model=model, messages=messages, stream=True,
                                                    timeout=first_token_s)
            for chunk in stream:
                delta = chunk.choices[0].delta.content if chunk.choices else None
                if delta:
                    sent = True
                    yield model, delta
                elif not sent and time.monotonic() - t0 > first_token_s:
                    raise TimeoutError(f"no first token in {first_token_s}s")
            if sent:
                return
            errors.append(f"{model}: empty stream")
        except Exception as e:                            # noqa: BLE001
            if sent:
                raise                                     # mid-answer: never switch models
            errors.append(f"{model}: {type(e).__name__}: {str(e)[:120]}")
    raise RuntimeError("No model answered. " + " | ".join(errors))
python
from databricks_openai import DatabricksOpenAI
from models.router import stream_with_fallback

client = DatabricksOpenAI()
for model, delta in stream_with_fallback(client, [{"role": "user", "content": "hello"}], task="fast"):
    print(delta, end="", flush=True)
print("\nanswered by", model)

How to read the result如何解读结果

  • `answered by` names the model that produced the first token. If it is often the fallback, the primary is unhealthy or too slow for your first-token timeout. Look at the gateway's usage before raising the timeout.`answered by` 显示的是产出首个 token 的模型。如果经常是兜底模型,说明主模型不健康,或者对你设定的首 token 超时来说太慢。在调大超时之前,先看看网关的用量数据。
  • `No model answered. a: reason | b: reason` lists every attempt. That is the same message format as the tutor on this site, so a failure reads the same in both places.`No model answered. a: reason | b: reason` 会列出每一次尝试。这和本站教程使用的消息格式相同,所以两处的失败信息读起来是一样的。
  • The inference table is your new requests.jsonl. Module 15's log lessons apply: read it incrementally, by timestamp, never by full scan.推理表就是你新的 requests.jsonl。第 15 模块中关于日志的经验同样适用:按时间戳增量读取,绝不全表扫描。

Troubleshooting排障

You see现象Why原因Do this处理
A user sees half an answer followed by a different style of answer用户看到半个回答后面接着另一种风格的回答Something retried after text was sent: a gateway fallback on a streaming request, or your own retry wrapper.在文本已经发出之后又发生了重试:可能是流式请求上的网关兜底,也可能是你自己写的重试包装。Retries and fallbacks belong before the first token only. router.py re-raises once `sent` is true; keep any wrapper the same.重试和兜底只能发生在首个 token 之前。router.py 在 `sent` 为真后会直接抛出异常;你写的任何包装都要保持同样的行为。
429 from the gateway in tests, not from the model测试时 429 来自网关,而不是模型Your per-user rate limit applies to your test runs too.你设置的每用户限流同样作用于你的测试运行。Run evals as the service principal with its own limit.以服务主体身份运行评估,并给它单独的限额。
No rows in the inference table推理表里没有数据The table is created empty when you enable it and fills only for requests through the gateway, with some delay.开启时表是空的,只有经过网关的请求才会写入,而且会有一些延迟。Check that the client uses the gateway, send a request, and wait several minutes before concluding.检查客户端是否走了网关,发送一个请求,等几分钟再下结论。
Done when完成标准A request through the router answers, appears in gateway usage, and a forced failure of the first model falls through to the second before any text.通过路由器发出的请求能得到回答,并出现在网关用量中;人为让第一个模型失败时,会在任何文本输出之前转到第二个模型。
Not confirmed on a vendor page未在厂商页面上确认Rate-limit field names, fallback configuration and the inference table schema are set in the UI and were not shown on the gateway page read for this guide. The `timeout=` keyword is passed through the OpenAI client.限流字段名、兜底配置和推理表结构都在界面中设置,本指南参考的网关页面没有展示这些。`timeout=` 参数是经由 OpenAI 客户端传入的。

3 Knowledge: files, ledger, chunks, graph知识:文件、台账、文本块、图

The knowledge bank moves from a folder to a volume, the ledger from SQLite or Postgres rows to a Delta table, and the chunker from a script to a job. The validation, tier and chunking rules do not change at all: chunking.py is the same logic, and it is tested in this repository.知识库从一个文件夹搬到 volume,台账从 SQLite 或 Postgres 的行变成 Delta 表,切块器从脚本变成 job。校验、等级和切块规则完全不变:chunking.py 的逻辑与本地相同,并且在本仓库中经过测试。

06Upload the knowledge bank to the volume把知识库上传到 volume
Replaces替代knowledge-bank/ with its folder taxonomy, source_authority.json, and the publish denylist.knowledge-bank/ 及其目录分类、source_authority.json,以及发布用的拒绝清单。

Why this step, and why here为什么要做这一步,为什么在这里

Folders carry meaning: the authority tier of a file comes from its path. Upload with the same tree and the tier rules work unchanged. The denylist runs before upload, because a file that reaches the volume is readable by every principal with READ VOLUME, and deleting it later does not undo an index built from it.目录本身带有含义:文件的权威等级来自它的路径。按同样的目录树上传,等级规则就无需改动。拒绝清单必须在上传之前执行,因为文件一旦进入 volume,所有拥有 READ VOLUME 权限的主体都能读到,事后删除也撤销不了已经基于它建好的索引。

What it does它做什么

Copies the bank to a temporary staging folder without the denylisted paths, prints the file count, and uploads the staging folder recursively to /Volumes/agentlab/kb/raw.把知识库复制到临时暂存目录(排除拒绝清单中的路径),打印文件数,然后把暂存目录递归上传到 /Volumes/agentlab/kb/raw。

How to do it怎么做

  1. Edit the --exclude lines to match your denylist. Treat the list as code: review changes to it.修改 --exclude 行,使其与你的拒绝清单一致。把这份清单当代码对待:对它的改动要经过审查。
  2. Run `bash replicate/databricks/setup/03_upload_knowledge.sh /path/to/knowledge-bank`.运行 `bash replicate/databricks/setup/03_upload_knowledge.sh /path/to/knowledge-bank`。
  3. Make sure source_authority.json lands at the volume root. ingest.py reads it from there.确保 source_authority.json 位于 volume 根目录。ingest.py 从那里读取它。

Scripts脚本

setup/03_upload_knowledge.sh · bash -n passes
#!/usr/bin/env bash
# Step 6. Copy the knowledge bank into the volume, keeping the folder taxonomy.
# The denylist is the same idea as sync/config.json in this repository: what never leaves the machine.
#   bash setup/03_upload_knowledge.sh /path/to/knowledge-bank
set -euo pipefail
SRC="${1:?usage: 03_upload_knowledge.sh <local knowledge-bank folder>}"
PROFILE="${DATABRICKS_PROFILE:-agent}"
DEST="dbfs:/Volumes/${AGENT_CATALOG:-agentlab}/${AGENT_KB_SCHEMA:-kb}/${AGENT_VOLUME:-raw}"

STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT
# Copy to a staging folder without the denylisted paths, then upload the staging folder.
rsync -a \
  --exclude '_inbox/' --exclude '_rejected/' --exclude '.DS_Store' \
  --exclude '*.env' --exclude 'private/' --exclude 'personal/' \
  "$SRC"/ "$STAGE"/

echo "files to upload: $(find "$STAGE" -type f | wc -l)"
databricks fs cp -r --overwrite "$STAGE" "$DEST" --profile "$PROFILE"
# Authority rules travel with the files: ingest.py reads source_authority.json from the volume root.
databricks fs ls "$DEST" --profile "$PROFILE"

How to read the result如何解读结果

  • Compare `files to upload` with a count of the local folder. The difference must equal what the denylist removed, no more.把 `files to upload` 与本地目录的文件数比较。差额应当恰好等于拒绝清单排除的数量,不能更多。
  • `fs ls` on the volume root shows the top-level collections. Each becomes a value of the `collection` column, which the search tool filters on.对 volume 根目录执行 `fs ls` 会显示顶层的集合。每个集合都会成为 `collection` 列的一个取值,检索工具会按它过滤。

Troubleshooting排障

You see现象Why原因Do this处理
`fs cp` fails with a path error`fs cp` 报路径错误The volume path needs the `dbfs:/Volumes/...` form for the CLI.CLI 要求 volume 路径使用 `dbfs:/Volumes/...` 的形式。Keep the dbfs: prefix as in the script, and check the catalog, schema and volume names.像脚本里那样保留 dbfs: 前缀,并核对 catalog、schema 和 volume 的名字。
Upload is slow for many small files大量小文件上传很慢Each file is a separate request.每个文件都是一个单独的请求。Upload a tar file and extract it in a job, or upload once and let later runs copy only changed files (rsync to staging first does this locally).上传一个 tar 包,在 job 里解压;或者只全量上传一次,之后只复制改动过的文件(先 rsync 到暂存目录就能在本地做到这一点)。
Done when完成标准The volume tree matches the local tree minus the denylist, with source_authority.json at the root.volume 中的目录树与本地目录树一致(去掉拒绝清单部分),且根目录有 source_authority.json。
Not confirmed on a vendor page未在厂商页面上确认The `fs cp -r --overwrite` flags are the CLI's general file commands; the volume-specific upload page was not read for this guide.`fs cp -r --overwrite` 这些参数属于 CLI 的通用文件命令;本指南没有参考 volume 专门的上传文档页。
07Validate, record in the ledger, and chunk, as one idempotent job校验、记入台账、切块,合成一个幂等的 job
Replaces替代Intake from _inbox, magic-byte validation, the ledger, kb_extract.py, and the cursor that made reruns change nothing.从 _inbox 收件、按魔数校验、台账、kb_extract.py,以及让重跑不产生任何变化的游标。

Why this step, and why here为什么要做这一步,为什么在这里

Every later stage reads the chunk table, so its correctness bounds everything. Idempotence is the property that lets the job run hourly: a file that did not change is skipped by hash, a file that changed retires its old chunks before the new ones go in, and a file that turned bad takes its chunks out of service. Without the retire step, a shortened document keeps answering with paragraphs it no longer has.后面所有阶段都读取文本块表,所以它的正确性决定了一切的上限。幂等性让这个 job 可以每小时运行:未变化的文件按哈希跳过;变化了的文件先停用旧文本块,再写入新的;变坏的文件会让它的文本块退出服务。没有停用这一步,一份被删短的文档仍会用它已经不存在的段落来回答。

What it does它做什么

Reads every file in the volume, hashes it, skips known hashes, validates the rest with the local rules, MERGEs ledger rows, chunks text files by heading with the heading path kept as context, retires stale chunks, MERGEs new ones, and optionally embeds `context + text` with the step 4 embedding model.读取 volume 中的每个文件并计算哈希,跳过已知哈希,用本地规则校验其余文件,MERGE 台账行,对文本文件按标题切块并保留标题路径作为上下文,停用过期的文本块,MERGE 新的文本块,并可选地用第 4 步的 embedding 模型对 `context + text` 做嵌入。

How to do it怎么做

  1. Deploy it with the bundle (step 18), or for a first run upload src/ to the workspace and run ingest.py as a one-off job task.用 bundle 部署(第 18 步);或者首次运行时,把 src/ 上传到工作区,把 ingest.py 作为一次性 job 任务运行。
  2. Pass `--backend` with your choice from step 9 (the bundle passes it from a variable). `lakebase` makes the job compute embeddings; AI Search computes them itself.用 `--backend` 传入你在第 9 步的选择(bundle 会从变量中传入)。选 `lakebase` 时 job 会自己计算 embedding;AI Search 则由平台计算。
  3. For PDF and DOCX, install your extractor as a job dependency and emit the same chunk tuple where the comment says. The rest of the job does not change.对于 PDF 和 DOCX,把你的提取器作为 job 依赖安装,在注释标明的位置产出同样结构的文本块元组。job 的其余部分不用改。
  4. Run it twice. The second run must print `changed 0`.运行两次。第二次必须打印 `changed 0`。

Scripts脚本

src/knowledge/ingest.py · compiles
"""Step 7. Volume -> validated files -> ledger (MERGE) -> chunks (MERGE) -> optional embeddings.

Runs as a Lakeflow job task:  python ingest.py --catalog agentlab [--embed]
Idempotent: a second run over unchanged files prints  changed 0, unchanged N  and writes nothing.
"""
from __future__ import annotations

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402
from knowledge.chunking import chunk_markdown, sha256, tier, validate  # noqa: E402

TEXTUAL = (".md", ".txt")


def main(argv: list) -> None:  # pragma: no cover - runs on Databricks
    from pyspark.sql import SparkSession, functions as F

    ap = argparse.ArgumentParser()
    ap.add_argument("--catalog", default=None)
    ap.add_argument("--embed", action="store_true", help="compute embeddings (needed by the Lakebase backend)")
    ap.add_argument("--backend", default=None, help="lakebase or ai_search; lakebase implies --embed")
    args = ap.parse_args(argv)
    if args.catalog:
        os.environ["AGENT_CATALOG"] = args.catalog
    if args.backend:
        os.environ["AGENT_RETRIEVAL"] = args.backend
    cfg = Config()
    embed = args.embed or cfg.retrieval == "lakebase"
    spark = SparkSession.builder.getOrCreate()
    root = cfg.raw_path

    rules_path = f"{root}/source_authority.json"
    rules = json.load(open(rules_path)) if os.path.exists(rules_path) else []   # volumes are mounted as files

    files = (spark.read.format("binaryFile").option("recursiveFileLookup", "true").load(root)
             .select("path", "content", "length"))
    known = {r["path"]: r["sha256"] for r in spark.table(cfg.ledger).select("path", "sha256").collect()}

    ledger_rows, chunk_rows, changed, unchanged = [], [], 0, 0
    for r in files.toLocalIterator():
        rel = r["path"].split(root, 1)[-1].lstrip("/")
        if rel == "source_authority.json":
            continue
        data = bytes(r["content"])
        digest = sha256(data)
        if known.get(rel) == digest:
            unchanged += 1
            continue
        changed += 1
        ok, reason = validate(rel, data)
        t = tier(rel, rules)
        ledger_rows.append((rel, digest, len(data), "accepted" if ok else "rejected", reason, t))
        if ok and rel.endswith(TEXTUAL):
            collection = rel.split("/", 1)[0]
            for c in chunk_markdown(rel, data.decode("utf-8")):
                chunk_rows.append((c["chunk_id"], rel, collection, c["chunk_index"], c["context"], c["text"],
                                   (c["context"] + "\n" + c["text"]).strip(), t, digest))
        # PDF, DOCX and other binary types: run your extractor here (the local kb_extract.py, installed
        # as a job dependency) and emit the same chunk tuple. Nothing below changes.

    print(f"changed {changed}, unchanged {unchanged}")
    if not ledger_rows:
        return

    led = spark.createDataFrame(ledger_rows, "path string, sha256 string, bytes bigint, status string, reason string, tier int") \
        .withColumn("updated_at", F.current_timestamp())
    led.createOrReplaceTempView("incoming_ledger")
    spark.sql(f"""MERGE INTO {cfg.ledger} t USING incoming_ledger s ON t.path = s.path
                  WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *""")

    if chunk_rows:
        ch = spark.createDataFrame(chunk_rows, "chunk_id string, source string, collection string, chunk_index int, "
                                               "context string, text string, embed_text string, tier int, sha256 string")
        ch = ch.withColumn("retired", F.lit(False))
        if embed:
            ch = add_embeddings(spark, ch, cfg)
        else:
            ch = ch.withColumn("embedding", F.lit(None).cast("array<float>"))
        ch.createOrReplaceTempView("incoming_chunks")
        # A changed file retires its old chunks first, so a shortened document leaves no ghosts.
        spark.sql(f"""UPDATE {cfg.chunks} SET retired = true
                      WHERE source IN (SELECT DISTINCT source FROM incoming_chunks)
                        AND chunk_id NOT IN (SELECT chunk_id FROM incoming_chunks)""")
        spark.sql(f"""MERGE INTO {cfg.chunks} t USING incoming_chunks s ON t.chunk_id = s.chunk_id
                      WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *""")
    rejected = [r for r in ledger_rows if r[3] == "rejected"]
    if rejected:                              # a file that turned bad takes its old chunks out of service
        spark.createDataFrame([(r[0],) for r in rejected], "path string").createOrReplaceTempView("rejected_paths")
        spark.sql(f"UPDATE {cfg.chunks} SET retired = true WHERE source IN (SELECT path FROM rejected_paths)")
    print(f"ledger rows {len(ledger_rows)}, chunks {len(chunk_rows)}, rejected {len(rejected)}")
    for r in rejected[:20]:
        print("  rejected", r[0], "->", r[4])


def add_embeddings(spark, df, cfg: Config, batch: int = 64):  # pragma: no cover
    """Embed context + text with the same endpoint the query side uses. One model for both sides, always."""
    from databricks_openai import DatabricksOpenAI

    client = DatabricksOpenAI()
    rows = df.collect()
    out = []
    for i in range(0, len(rows), batch):
        part = rows[i:i + batch]
        vecs = client.embeddings.create(model=cfg.embedding, input=[r["embed_text"] for r in part]).data
        out += [(*r, [float(x) for x in v.embedding]) for r, v in zip(part, vecs)]
    return spark.createDataFrame(out, df.schema.add("embedding", "array<float>"))


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])
src/knowledge/chunking.py · compiles
"""Validation, authority tiers and structure-aware chunking. Pure Python, no platform calls.

The same rules as the local knowledge bank (modules 3 and 5), written so a Databricks job
can import them unchanged. Tested here by tests/test_portable.py.
"""
from __future__ import annotations

import fnmatch
import hashlib
import re

MAGIC = {".pdf": b"%PDF", ".docx": b"PK\x03\x04", ".xlsx": b"PK\x03\x04", ".png": b"\x89PNG"}
TEXT = {".md", ".txt", ".csv", ".json", ".html"}


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def validate(name: str, data: bytes) -> tuple:
    """(ok, reason). A renamed file or an empty export is caught here, before it is chunked."""
    ext = "." + name.rsplit(".", 1)[-1].lower() if "." in name else ""
    if not data:
        return False, "empty file"
    if ext in MAGIC and not data.startswith(MAGIC[ext]):
        return False, f"not a real {ext} file"
    if ext in TEXT:
        try:
            data.decode("utf-8")
        except UnicodeDecodeError:
            return False, "not valid UTF-8 text"
    if ext not in MAGIC and ext not in TEXT:
        return False, f"unsupported type {ext or '(none)'}"
    return True, "ok"


def tier(path: str, rules: list) -> int:
    """rules: [{"pattern": "policy/*", "tier": 1}, ...], first match wins, default tier 3."""
    for r in rules:
        if fnmatch.fnmatch(path, r["pattern"]):
            return int(r["tier"])
    return 3


HEADING = re.compile(r"^(#{1,6})\s+(.*)$")


def chunk_markdown(source: str, text: str, max_chars: int = 1200) -> list:
    """Split on headings, then on blank lines, never inside a paragraph.

    Each chunk carries `context`: the heading path it sits under. That path is stored
    beside the text and embedded with it, so 'Section 5' still means something after
    the chunk is cut out of its document.
    """
    chunks, path, buf = [], [], []

    def flush():
        body = "\n\n".join(p for p in buf if p.strip()).strip()
        if body:
            chunks.append({"source": source, "chunk_index": len(chunks), "context": " > ".join(path), "text": body})
        buf.clear()

    for para in re.split(r"\n\s*\n", text):
        m = HEADING.match(para.strip())
        if m:
            flush()
            level = len(m.group(1))
            path[:] = path[: level - 1] + [m.group(2).strip()]
            continue
        if sum(len(p) for p in buf) + len(para) > max_chars:
            flush()
        buf.append(para.strip())
    flush()
    for c in chunks:
        c["chunk_id"] = f"{source}::{c['chunk_index']}"
    return chunks

How to read the result如何解读结果

  • `changed N, unchanged M`: on the first run M is 0; on every later run N should equal the files you actually touched. A large N with no edits means hashes are not being compared, usually because the ledger table was recreated.`changed N, unchanged M`:首次运行时 M 为 0;之后每次运行,N 应当等于你实际改动过的文件数。没改文件却出现很大的 N,说明没在比对哈希,通常是因为台账表被重建了。
  • `rejected` lines name the file and the reason. `not a real .pdf file` is the module 3 lesson: an export renamed by hand. Fix the source, never the validator.`rejected` 行会列出文件名和原因。`not a real .pdf file` 就是第 3 模块的教训:手动改了扩展名的导出文件。要修的是源文件,而不是校验器。
  • Check one chunk's context column. `Travel > Section 5 Lodging` means the heading path survived; an empty context on a long policy means the file has no markdown headings and will retrieve worse.查看某个文本块的 context 列。`Travel > Section 5 Lodging` 说明标题路径保留下来了;如果一份很长的政策文档 context 为空,说明它没有 markdown 标题,检索效果会更差。

Troubleshooting排障

You see现象Why原因Do this处理
ModuleNotFoundError: commonModuleNotFoundError: commonThe script ran without the rest of src/ next to it.运行脚本时,src/ 的其他部分没有和它放在一起。Deploy the whole src/ folder (the bundle does). Each script adds its parent src/ to sys.path.部署整个 src/ 目录(bundle 会这样做)。每个脚本都会把它上级的 src/ 加进 sys.path。
MERGE fails: multiple source rows matchedMERGE 失败:多个源行匹配同一目标行Two files produced the same chunk_id, or the same file appears twice under different path spellings.两个文件产出了相同的 chunk_id,或者同一个文件以不同的路径写法出现了两次。chunk_id is `<relative path>::<index>`; make sure the volume has no duplicate folders differing only by case.chunk_id 的格式是 `<相对路径>::<序号>`;确保 volume 里没有仅大小写不同的重复目录。
Embedding step is slow or rate-limited嵌入步骤很慢或被限流Pay-per-token embedding has throughput limits; the first run embeds everything.按 token 计费的 embedding 有吞吐量上限;首次运行要嵌入全部内容。Lower the batch size, run the first load off-hours, or use AI Search with managed embeddings instead.调小 batch 大小,在非高峰时段做首次加载,或者改用由 AI Search 托管 embedding 的方式。
Done when完成标准Two consecutive runs: the first loads, the second prints `changed 0`. A deliberately renamed bad file appears as rejected and has no chunks.连续运行两次:第一次加载,第二次打印 `changed 0`。故意改名的坏文件显示为 rejected,并且没有任何文本块。
Not confirmed on a vendor page未在厂商页面上确认Reading source_authority.json with open() on the /Volumes path relies on volumes being mounted as files on the job's compute, which is how serverless and Unity Catalog compute expose them.在 /Volumes 路径上用 open() 读取 source_authority.json,依赖于 volume 在 job 计算资源上以文件形式挂载,serverless 和 Unity Catalog 计算正是这样提供 volume 的。
08Build graph edges as a table把图的边建成一张表
Replaces替代nightly/defines.py and nightly/citations.py: definition edges and 'see Section N' citation edges.nightly/defines.py 和 nightly/citations.py:定义边和“见第 N 节”引用边。

Why this step, and why here为什么要做这一步,为什么在这里

Dense and lexical search find passages that look like the question. They do not follow 'see Section 5' or find where a term is defined. Those links are deterministic and cheap to extract, and a table of three columns is all a graph needs at this size. No graph database is required, and none was used locally either.稠密检索和词法检索找到的是看起来像问题的段落。它们不会顺着“见第 5 节”走,也找不到某个术语是在哪里定义的。这些链接是确定性的,提取成本很低;在这个规模下,一张三列的表就是图所需的全部。不需要图数据库,本地也没有用。

What it does它做什么

Reads chunks in service, applies the three edge rules (section, cites, defines), deduplicates, and overwrites agentlab.kb.edges. Rebuilding from chunks each run means an edge can never outlive the chunk it points to.读取在服务中的文本块,应用三条边规则(section、cites、defines),去重,然后覆盖写入 agentlab.kb.edges。每次都从文本块重建,意味着边永远不会比它指向的文本块活得更久。

How to do it怎么做

  1. Run edges.py as the task after ingest (the bundle in step 20 chains them).在 ingest 之后把 edges.py 作为下一个任务运行(第 20 步的 bundle 会把它们串起来)。
  2. Look at the printed counts per relation.查看打印出来的每种关系的数量。
  3. Spot-check five `defines` rows by reading the chunk they point to.抽查五行 `defines`,读一读它们指向的文本块。

Scripts脚本

src/graph/edges.py · compiles
"""Graph edges as rows in a Delta table. The edge rules are pure Python; the job writes them.

Three relations, as in the local build (module 5):
  section   "<source>#<n>"  -> the chunk that starts Section n of that source
  cites     chunk           -> "<source>#<n>" it refers to ("see Section 5")
  defines   term            -> the chunk that defines it ("X means ...", "X is defined as ...")

Run as a job:  python edges.py --catalog agentlab
"""
from __future__ import annotations

import argparse
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  # .../src, so `common` imports

SECTION = re.compile(r"^\s*(?:section|§)\s*(\d+)\b", re.I)
CITES = re.compile(r"\bsee\s+section\s+(\d+)\b", re.I)
DEFINES = re.compile(r"^\s*(?:\"|“)?([A-Za-z][A-Za-z \-]{2,40}?)(?:\"|”)?\s+(?:means|is defined as|refers to)\b", re.I | re.M)


def build_edges(chunks: list) -> list:
    """chunks: dicts with chunk_id, source, context, text. Returns (relation, from_key, to_chunk) dicts."""
    edges = []
    for c in chunks:
        heading = (c.get("context") or "").split(" > ")[-1]
        m = SECTION.match(heading) or SECTION.match(c["text"])
        if m:
            edges.append({"relation": "section", "from_key": f"{c['source']}#{m.group(1)}", "to_chunk": c["chunk_id"]})
        for n in CITES.findall(c["text"]):
            edges.append({"relation": "cites", "from_key": c["chunk_id"], "to_chunk": f"{c['source']}#{n}"})
        for term in DEFINES.findall(c["text"]):
            edges.append({"relation": "defines", "from_key": term.strip().lower(), "to_chunk": c["chunk_id"]})
    seen, out = set(), []
    for e in edges:
        key = (e["relation"], e["from_key"], e["to_chunk"])
        if key not in seen:
            seen.add(key)
            out.append(e)
    return out


def main(argv: list) -> None:  # pragma: no cover - runs on Databricks
    from pyspark.sql import SparkSession

    from common.config import Config

    ap = argparse.ArgumentParser()
    ap.add_argument("--catalog", default=None)
    args = ap.parse_args(argv)
    if args.catalog:
        os.environ["AGENT_CATALOG"] = args.catalog
    cfg = Config()
    spark = SparkSession.builder.getOrCreate()
    rows = [r.asDict() for r in spark.table(cfg.chunks).where("NOT retired").select("chunk_id", "source", "context", "text").collect()]
    edges = build_edges(rows)
    df = spark.createDataFrame(edges or [], "relation string, from_key string, to_chunk string")
    df.write.mode("overwrite").saveAsTable(cfg.edges)       # rebuilt from chunks each run: no drift
    counts = {r["relation"]: r["n"] for r in df.groupBy("relation").count().withColumnRenamed("count", "n").collect()}
    print("edges written:", counts)


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])

How to read the result如何解读结果

  • `edges written: {'section': 40, 'cites': 12, 'defines': 9}` is a plausible shape for a policy bank. Zero `section` edges means your headings do not start with 'Section N'; adjust SECTION to your documents' convention.`edges written: {'section': 40, 'cites': 12, 'defines': 9}` 对政策类知识库来说是一个合理的分布。`section` 边为零,说明你的标题不是以“Section N”开头的;按你的文档习惯调整 SECTION 正则。
  • A `cites` edge whose target has no `section` edge is a dangling reference. The search tool simply adds nothing for it, which is the safe failure.如果某条 `cites` 边的目标没有对应的 `section` 边,就是悬空引用。检索工具对它什么也不会添加,这是安全的失败方式。

Troubleshooting排障

You see现象Why原因Do this处理
The edges table is empty after a run that printed counts运行时打印了数量,但边表是空的The job wrote to a different catalog: --catalog was not passed, so the default was used.job 写到了另一个 catalog:没有传入 --catalog,于是用了默认值。Pass --catalog as the bundle does, or set AGENT_CATALOG on the job.像 bundle 那样传入 --catalog,或者在 job 上设置 AGENT_CATALOG。
Hundreds of `defines` edges for common words常用词产生了数百条 `defines` 边The pattern matched sentences like 'This means that...'.正则匹配到了 “This means that...” 这类句子。Tighten DEFINES to your glossary format, or require the term to be quoted or bold. Then rerun; the table is rebuilt.把 DEFINES 收紧到你的术语表格式,或者要求术语带引号或加粗。然后重跑,表会被重建。
Done when完成标准The edges table has rows for all three relations, and the module 5 example (a 'see Section 5' chunk) has a cites edge to a section edge.边表中三种关系都有数据,第 5 模块的例子(一个写着“见第 5 节”的文本块)有一条 cites 边连到一条 section 边。

4 Retrieval: choose a backend, keep the ranking检索:选择后端,保留排序逻辑

This is the phase with a real decision. Two backends can serve the chunks; the ranking that made the local search good (fusion by rank, an authority nudge, dedup, graph expansion, a diagnostic on empty) runs after either one, in your code. The gold set from module 11 decides whether the replica retrieves as well as the original.这是需要真正做决定的阶段。有两种后端可以提供文本块检索;让本地检索效果好的排序逻辑(按名次融合、权威加权、去重、图扩展、空结果诊断)在任一后端之后都由你的代码执行。第 11 模块的标准集用来判定副本的检索是否和原版一样好。

09Decide: Lakebase hybrid or AI Search做决定:Lakebase 混合检索还是 AI Search
Replaces替代Postgres with pgvector and full-text search, hybrid SQL, HNSW, the CTE lesson.带 pgvector 和全文检索的 Postgres、混合检索 SQL、HNSW,以及关于 CTE 的教训。

Why this step, and why here为什么要做这一步,为什么在这里

The choice decides who computes embeddings, where BM25 runs, whether you operate a database, and how much of the hybrid query you control. Choosing after building the tool means rewriting the tool. Both options keep Delta as the source of truth, so the choice can be reversed by building the other one from the same table.这个选择决定了由谁计算 embedding、BM25 在哪里运行、你是否要运维一个数据库,以及你对混合查询有多少控制权。先写检索工具再做选择,就意味着要重写工具。两种方案都以 Delta 作为唯一可信来源,所以这个选择可以撤回:用同一张表再搭建另一种即可。

What it does它做什么

A decision, recorded in AGENT_RETRIEVAL. Lakebase: Postgres with pgvector-compatible ANN and BM25 indexes (Lakebase Search), fed by a synced table, closest to the local build. AI Search: a managed Delta Sync index with managed embeddings, nothing to operate, keyword search via query_type FULL_TEXT and fused search via query_type hybrid.一个决定,记录在 AGENT_RETRIEVAL 中。Lakebase:带 pgvector 兼容的 ANN 和 BM25 索引的 Postgres(Lakebase Search),由同步表供数,最接近本地构建。AI Search:托管的 Delta Sync 索引,embedding 也是托管的,无需运维,关键词检索用 query_type FULL_TEXT,融合检索用 query_type hybrid。

How to do it怎么做

  1. Choose Lakebase if you want the same SQL, the same index behavior and EXPLAIN plans you can read, and you will also use Lakebase for memory (step 16).如果你想要同样的 SQL、同样的索引行为以及能看懂的 EXPLAIN 执行计划,并且还会用 Lakebase 做记忆(第 16 步),就选 Lakebase。
  2. Choose AI Search if nobody on the team will operate Postgres. It can fuse dense and keyword results itself (query_type="hybrid"), or return two lists for your own fusion.如果团队里没人会运维 Postgres,就选 AI Search。它可以自己融合稠密和关键词结果(query_type="hybrid"),也可以返回两个列表由你自己融合。
  3. Set AGENT_RETRIEVAL=lakebase or ai_search. Do steps 10 or 11 accordingly, then step 13 either way.设置 AGENT_RETRIEVAL=lakebase 或 ai_search。相应地做第 10 步或第 11 步,然后无论如何都要做第 13 步。

Scripts脚本

text
                        Lakebase (Postgres + Lakebase Search)   AI Search (Delta Sync index)
embeddings computed by  your ingest job (--embed)               the platform (managed)
dense index             lakebase_ann, cosine                    managed ANN
keyword (BM25)          lakebase_bm25 on a tsvector              query_type="FULL_TEXT"
hybrid query            yours: two SQL lists + RRF in Python    two calls + RRF (default), or query_type="hybrid"
you operate             a Postgres project, a refresh           nothing
EXPLAIN / plan visible  yes                                     no
reuse for memory        yes (same project)                      no
closest to local build  yes                                     no

How to read the result如何解读结果

  • If you cannot decide, build Lakebase first. It reproduces the local behavior, so step 13's comparison with the local gold numbers is about the platform, not about a different retrieval design.如果拿不定主意,先搭 Lakebase。它重现了本地的行为,所以第 13 步与本地标准集数据的对比只反映平台差异,而不是检索设计上的差异。
  • Whichever you pick, the ranking constants stay: RRF k = 60, 20 candidates per list, authority weight 0.0004. Module 5 explains why that weight is one rank step near the top.无论选哪个,排序常量都不变:RRF k = 60,每个列表 20 个候选,权威加权 0.0004。第 5 模块解释了为什么这个权重恰好相当于头部的一个名次差。

Troubleshooting排障

You see现象Why原因Do this处理
The workspace has no Lakebase工作区里没有 LakebaseLakebase is not available in every region or tier.并非每个区域或套餐都提供 Lakebase。Choose AI Search for retrieval, and keep memory in a Delta table with a small cache in the app until Lakebase is available.检索选 AI Search;在 Lakebase 可用之前,把记忆放在 Delta 表中,并在 App 里做一个小缓存。
You want both两个都想要They serve the same table.它们服务的是同一张表。Build both, switch with AGENT_RETRIEVAL, and let the gold set pick. That is a variant comparison, as in module 11.两个都搭,用 AGENT_RETRIEVAL 切换,让标准集来选。这就是第 11 模块里的变体对比。
Done when完成标准AGENT_RETRIEVAL is set and the reason is written down next to the gold numbers you will produce in step 13.AGENT_RETRIEVAL 已设置,选择理由已写下来,放在第 13 步将产出的标准集数据旁边。
10Lakebase backend: synced table, ANN and BM25 indexesLakebase 后端:同步表、ANN 和 BM25 索引
Replaces替代pgvector HNSW index, Postgres full-text search, the hybrid SQL in tools/knowledge_base.py.pgvector 的 HNSW 索引、Postgres 全文检索、tools/knowledge_base.py 里的混合检索 SQL。

Why this step, and why here为什么要做这一步,为什么在这里

The chunks are written in Delta, where jobs and governance live, and read in Postgres, where millisecond index lookups live. A synced table connects the two without a copy job of your own. Lakebase Search provides the two index types the local build used: an ANN index for vectors and BM25 for words.文本块写在 Delta 里,那是 job 和治理所在的地方;读取在 Postgres 里,那是毫秒级索引查找所在的地方。同步表把两者连接起来,不需要你自己写复制任务。Lakebase Search 提供了本地构建用到的两类索引:向量用 ANN 索引,词语用 BM25。

What it does它做什么

lakebase_sync.py creates a TRIGGERED synced table from agentlab.kb.chunks with the embedding column mapped to vector(n). lakebase_search.sql installs the extensions, creates a plain search table with a tsvector column, its ANN and BM25 indexes, and the two ranked queries with the vector as a bound parameter. refresh.py is the last ingest task: it runs the synced table's pipeline update, waits, and rebuilds the search table in one transaction.lakebase_sync.py 从 agentlab.kb.chunks 创建一个 TRIGGERED 模式的同步表,并把 embedding 列映射为 vector(n)。lakebase_search.sql 安装扩展,创建一张带 tsvector 列的普通检索表及其 ANN 和 BM25 索引,并定义两个排序查询,其中向量作为绑定参数传入。refresh.py 是 ingest 的最后一个任务:它触发同步表的管道更新,等待完成,然后在一个事务中重建检索表。

How to do it怎么做

  1. Create a Lakebase project (Autoscaling) on Postgres 16 or later. In a dev project first, enable Lakebase Search in project settings; this restarts its computes and cannot be undone.创建一个 Postgres 16 或更高版本的 Lakebase 项目(Autoscaling)。先在开发项目里,于项目设置中启用 Lakebase Search;这会重启它的计算资源,且无法撤销。
  2. Run `python lakebase_sync.py --branch projects/<project>/branches/production --database <db>`. If the SDK rejects the type override, run the printed CLI command instead.运行 `python lakebase_sync.py --branch projects/<project>/branches/production --database <db>`。如果 SDK 不接受类型覆盖参数,就改为运行它打印出来的 CLI 命令。
  3. Connect with psql using the details from the Lakebase console and run lakebase_search.sql.用 Lakebase 控制台里的连接信息通过 psql 连接,运行 lakebase_search.sql。
  4. Keep refresh.py as the last ingest task (resources/jobs.yml already chains it). A TRIGGERED synced table never updates by itself.让 refresh.py 保持为 ingest 的最后一个任务(resources/jobs.yml 已经把它串上了)。TRIGGERED 模式的同步表不会自行更新。
  5. Run both EXPLAIN lines at the end of the SQL file.运行 SQL 文件末尾的两条 EXPLAIN 语句。

Scripts脚本

src/retrieval/lakebase_sync.py · compiles
"""Step 10 (Lakebase backend). Copy the chunk table into Lakebase Postgres, embedding column as vector(n).

The local build keeps chunks in Postgres with pgvector and runs hybrid SQL there (module 5).
This is the nearest copy of that on Databricks: Delta stays the source of truth, a synced table
puts the rows in Postgres, and Lakebase Search adds the vector (ANN) and BM25 indexes.

Before running: create a Lakebase project (Autoscaling), note its branch path, and run
  CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;   (in the Postgres database)
Run:  python lakebase_sync.py --branch projects/<project>/branches/production --database <db>
"""
from __future__ import annotations

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402


def main(argv: list) -> None:  # pragma: no cover - runs against a workspace
    from databricks.sdk import WorkspaceClient
    from databricks.sdk.service.postgres import (
        SyncedTable,
        SyncedTableSyncedTableSpec,
        SyncedTableSyncedTableSpecSyncedTableSchedulingPolicy,
    )

    ap = argparse.ArgumentParser()
    ap.add_argument("--branch", required=True)
    ap.add_argument("--database", required=True)
    ap.add_argument("--target", default=None, help="UC name for the synced table, default <catalog>.kb.chunks_pg")
    args = ap.parse_args(argv)
    cfg = Config()
    target = args.target or cfg.table(cfg.kb_schema, "chunks_pg")

    spec = SyncedTableSyncedTableSpec(
        source_table_full_name=cfg.chunks,
        branch=args.branch,
        primary_key_columns=["chunk_id"],
        # TRIGGERED: incremental, including deletes; needs change data feed on the source (01_catalog.sql enables it).
        scheduling_policy=SyncedTableSyncedTableSpecSyncedTableSchedulingPolicy.TRIGGERED,
        postgres_database=args.database,
        create_database_objects_if_missing=True,
    )
    # The embedding column must arrive as vector(n), not as a Postgres float array, or no ANN index can use it.
    # The vendor page shows this as "type_overrides" in the JSON spec. If your SDK version does not accept the
    # keyword, create the synced table with the CLI command printed below instead.
    overrides = [{"column_name": "embedding", "pg_type": "PG_SPECIFIC_TYPE_VECTOR", "size": cfg.embedding_dim}]
    try:
        spec.type_overrides = overrides            # type: ignore[attr-defined]
    except Exception:                              # noqa: BLE001
        pass
    w = WorkspaceClient()
    try:
        st = w.postgres.create_synced_table(synced_table=SyncedTable(spec=spec), synced_table_id=target).wait()
        print("synced table created:", st.name)
    except Exception as e:                         # noqa: BLE001
        print("SDK create failed:", type(e).__name__, str(e)[:300])
        print("Equivalent CLI:")
        print(f"""databricks postgres create-synced-table {target} --json '{{
  "spec": {{
    "source_table_full_name": "{cfg.chunks}",
    "branch": "{args.branch}",
    "primary_key_columns": ["chunk_id"],
    "scheduling_policy": "TRIGGERED",
    "postgres_database": "{args.database}",
    "create_database_objects_if_missing": true,
    "type_overrides": [{{"column_name": "embedding", "pg_type": "PG_SPECIFIC_TYPE_VECTOR", "size": {cfg.embedding_dim}}}]
  }}
}}'""")
        raise


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])
src/retrieval/lakebase_search.sql · read only
-- Step 10 (Lakebase backend). Search table, ANN and BM25 indexes, and the two ranked lists, in Postgres.
-- Run with psql against the Lakebase database (connection details: Lakebase console, Connect).
-- Needs Lakebase Search enabled on the project (project settings). Enabling it restarts the
-- project's computes and cannot be undone, so do it in a dev project first.

CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;   -- also installs pgvector
CREATE EXTENSION IF NOT EXISTS lakebase_text;              -- BM25

-- The synced table belongs to its sync pipeline: do not alter it, and do not build views on it
-- (a full re-sync that recreates the table would be blocked by a dependent view). Search runs over
-- a plain table that the refresh task rebuilds from it, with the tsvector column BM25 needs.
-- The schema the synced table lands in is shown on its Overview tab; "kb" is assumed here.
CREATE TABLE IF NOT EXISTS kb_search (
  chunk_id    text PRIMARY KEY,
  source      text NOT NULL,
  collection  text NOT NULL,
  chunk_index int,
  context     text,
  text        text,
  tier        int,
  embedding   vector(1024),          -- AGENT_EMBEDDING_DIM
  body_tsv    tsvector
);
CREATE INDEX IF NOT EXISTS kb_search_ann  ON kb_search USING lakebase_ann (embedding vector_cosine_ops);
CREATE INDEX IF NOT EXISTS kb_search_bm25 ON kb_search USING lakebase_bm25 (body_tsv);
CREATE INDEX IF NOT EXISTS kb_search_coll ON kb_search (collection);

-- Refresh (refresh.py runs exactly this after each sync). One transaction: TRUNCATE locks the table,
-- so a search during the rebuild waits a moment and then sees the new rows. It never sees an empty table.
BEGIN;
TRUNCATE kb_search;
INSERT INTO kb_search
SELECT chunk_id, source, collection, chunk_index, context, text, tier, embedding,
       to_tsvector('english', coalesce(context, '') || ' ' || coalesce(text, ''))
FROM kb.chunks_pg
WHERE NOT retired;
COMMIT;

-- The app's service principal reads; nobody but the refresh role writes.
-- GRANT SELECT ON kb_search TO "<app service principal client id>";

-- Dense list. The query vector is a bound parameter ($1), never a value computed inside the
-- query. Module 5's lesson: when the planner cannot treat the vector as a constant, it scans.
PREPARE dense_ids(vector, text, int) AS
SELECT chunk_id FROM kb_search
WHERE collection = $2
ORDER BY embedding <=> $1
LIMIT $3;

-- Lexical list. BM25 via the <@> operator: lower score = more relevant, so ORDER BY ascending.
PREPARE lexical_ids(text, text, int) AS
SELECT chunk_id FROM kb_search
WHERE collection = $2
ORDER BY body_tsv <@> to_bm25query(to_tsvector('english', $1), 'kb_search_bm25')
LIMIT $3;

-- Prove the indexes are used (look for kb_search_ann / kb_search_bm25, not "Seq Scan"):
-- EXPLAIN EXECUTE dense_ids('[0.01, ...]'::vector, 'policy', 20);
-- EXPLAIN EXECUTE lexical_ids('lodging cap', 'policy', 20);
src/retrieval/refresh.py · compiles
"""The last ingest task: make the chosen search backend see the new chunks.

TRIGGERED pipelines never update on their own. After ingest has merged new chunks into Delta:
  ai_search  start the index sync
  lakebase   start the synced table's pipeline update, wait for it, then rebuild kb_search
             (the same TRUNCATE + INSERT as lakebase_search.sql, in one transaction)

  python refresh.py --backend lakebase --synced-table agentlab.kb.chunks_pg
"""
from __future__ import annotations

import argparse
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402

REBUILD = """
TRUNCATE kb_search;
INSERT INTO kb_search
SELECT chunk_id, source, collection, chunk_index, context, text, tier, embedding,
       to_tsvector('english', coalesce(context, '') || ' ' || coalesce(text, ''))
FROM kb.chunks_pg WHERE NOT retired;
"""


def _pipeline_id(st) -> str:
    """The synced table's pipeline id. Read defensively: the attribute path differs between SDK versions."""
    for path in (("data_synchronization_status", "pipeline_id"), ("status", "pipeline_id"), ("pipeline_id",)):
        obj = st
        for attr in path:
            obj = getattr(obj, attr, None)
        if obj:
            return str(obj)
    raise RuntimeError("no pipeline id on the synced table; trigger the sync from its Overview tab")


def lakebase(cfg: Config, synced_table: str, timeout_s: int = 1800) -> None:  # pragma: no cover
    from databricks.sdk import WorkspaceClient

    from common.pg import pool

    w = WorkspaceClient()
    pid = _pipeline_id(w.postgres.get_synced_table(name=synced_table))
    update = w.pipelines.start_update(pipeline_id=pid).update_id
    t0 = time.time()
    while time.time() - t0 < timeout_s:
        state = str(w.pipelines.get_update(pipeline_id=pid, update_id=update).update.state)
        if state.endswith(("COMPLETED", "FAILED", "CANCELED")):
            break
        time.sleep(15)
    print("synced table update:", state)
    if not state.endswith("COMPLETED"):
        raise SystemExit("sync did not complete; kb_search left unchanged")
    with pool().connection() as conn:          # psycopg runs this in one transaction, committed on exit
        conn.execute(REBUILD)
        n = conn.execute("SELECT count(*) FROM kb_search").fetchone()[0]
    print("kb_search rows:", n)


def main(argv: list) -> None:  # pragma: no cover
    ap = argparse.ArgumentParser()
    ap.add_argument("--backend", default=None)
    ap.add_argument("--synced-table", default=None)
    a = ap.parse_args(argv)
    if a.backend:
        os.environ["AGENT_RETRIEVAL"] = a.backend
    cfg = Config()
    if cfg.retrieval == "ai_search":
        from retrieval.ai_search_index import sync
        sync(cfg)
    else:
        lakebase(cfg, a.synced_table or cfg.table(cfg.kb_schema, "chunks_pg"))


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])

How to read the result如何解读结果

  • EXPLAIN must name kb_search_ann for the dense query and kb_search_bm25 for the lexical one. `Seq Scan on kb_search` means the index is not used: check that the vector is a parameter, not an expression, which is exactly the module 5 lesson.EXPLAIN 必须显示稠密查询使用了 kb_search_ann,词法查询使用了 kb_search_bm25。出现 `Seq Scan on kb_search` 说明没用上索引:检查向量是否作为参数传入,而不是一个表达式,这正是第 5 模块的教训。
  • BM25 scores from `<@>` are lower-is-better, so the lexical list orders ascending. If the top lexical hit is obviously irrelevant, the order is reversed somewhere.`<@>` 返回的 BM25 分数越低越相关,所以词法列表按升序排列。如果词法第一名明显不相关,说明某处排序方向反了。
  • refresh.py prints `synced table update: ...COMPLETED` and `kb_search rows: N`. N must equal the chunks in service in Delta. Fewer means the sync ran before ingest finished, or a row has a null key.refresh.py 会打印 `synced table update: ...COMPLETED` 和 `kb_search rows: N`。N 必须等于 Delta 中在服务的文本块数。如果更少,说明同步在 ingest 完成之前就运行了,或者某行的主键为空。

Troubleshooting排障

You see现象Why原因Do this处理
embedding arrives as double precision[] instead of vectorembedding 列变成了 double precision[] 而不是 vectorThe synced table was created without the type override.创建同步表时没有带类型覆盖。The primary key and types cannot be changed in place: delete the synced table and create it again with `type_overrides`.主键和类型无法就地修改:删除同步表,带上 `type_overrides` 重新创建。
A full re-sync of the synced table fails: other objects depend on it同步表全量重同步失败:有其他对象依赖它Something (a view, a foreign key) was built on the synced table.有东西(视图、外键)建在了同步表上。Build nothing on it. That is why kb_search is a separate table rebuilt by refresh.py.不要在它上面建任何东西。这正是 kb_search 被做成一张由 refresh.py 重建的独立表的原因。
refresh.py: no pipeline id on the synced tablerefresh.py 报:同步表上找不到 pipeline idThe SDK version names the status field differently.该 SDK 版本中状态字段的名字不同。Print the object returned by get_synced_table once and add its path to _pipeline_id, or trigger the sync from the table's Overview tab.把 get_synced_table 返回的对象打印一次,把对应的字段路径加到 _pipeline_id 中;或者在该表的 Overview 标签页手动触发同步。
Sync pipeline fails: duplicate primary key同步管道失败:主键重复chunk_id repeated in the source.源表中 chunk_id 重复了。Fix the source (step 7's MERGE prevents this); never set a timeseries key to hide it, because that silently keeps only one row.修正源表(第 7 步的 MERGE 可防止这种情况);绝不要用 timeseries key 来掩盖,因为那样会悄悄地只保留一行。
Password authentication failed after about an hour大约一小时后密码认证失败Database credentials expire after 60 minutes.数据库凭证 60 分钟后过期。Use common/pg.py: it mints a credential per connection and recycles connections at 45 minutes.使用 common/pg.py:它为每个连接生成凭证,并在 45 分钟时回收连接。
Done when完成标准Both EXPLAIN plans use their index, and kb_search has one row per chunk in service.两条 EXPLAIN 都用上了各自的索引,且 kb_search 中每个在服务的文本块各有一行。
Not confirmed on a vendor page未在厂商页面上确认Not confirmed: the `type_overrides` attribute name in the Python SDK (the CLI JSON form is from the vendor page), `w.postgres.get_synced_table` and where it reports the pipeline id. Triggering the pipeline with `w.pipelines.start_update` is the general SDK call for pipelines. The fallbacks are in the troubleshooting lines.未确认:Python SDK 中 `type_overrides` 属性的名字(CLI 的 JSON 写法来自厂商页面)、`w.postgres.get_synced_table` 以及它在哪个字段报告 pipeline id。用 `w.pipelines.start_update` 触发管道是 SDK 中针对管道的通用调用。替代方案见排障部分。
12The search tool: fusion, authority, dedup, graph, diagnostic检索工具:融合、权威、去重、图扩展、诊断

Why this step, and why here为什么要做这一步,为什么在这里

Managed indexes return candidates. Turning candidates into the five passages a model should read is where the local build earned its accuracy, and none of it is a platform feature. Keeping it as one portable module (ranking.py, tested here) means the Databricks agent and the local agent rank identically, so a difference in answers points at data or models, not at code drift.托管索引返回的只是候选。把候选变成模型该读的那五段,才是本地构建准确率的来源,而这些都不是平台功能。把它保留为一个可移植的模块(ranking.py,在这里经过测试),意味着 Databricks 智能体和本地智能体的排序完全一致;答案出现差异时,原因就指向数据或模型,而不是代码漂移。

What it does它做什么

search_kb gets two lists from the chosen backend, fuses them with RRF, adds the tier bonus, collapses copies of a paragraph to its most authoritative source, expands through the edges table, and returns a trace. An empty result carries a diagnostic naming the likely cause.search_kb 从所选后端取回两个列表,用 RRF 融合,加上等级加分,把同一段落的多个副本合并为最权威的来源,通过边表扩展,并返回追踪信息。空结果会带上指出可能原因的诊断信息。

How to do it怎么做

  1. Set DATABRICKS_WAREHOUSE_ID for the edges lookup. In the app it comes from the sql_warehouse resource (step 18); without it, expansion is skipped and the trace says so.为边表查询设置 DATABRICKS_WAREHOUSE_ID。在 App 中它来自 sql_warehouse 资源(第 18 步);没有它时,图扩展会被跳过,追踪信息里会注明。
  2. Run `python search_tool.py what does approving official mean` and read the JSON.运行 `python search_tool.py what does approving official mean`,阅读输出的 JSON。
  3. Run `python replicate/databricks/check.py`: the ranking tests run without a workspace.运行 `python replicate/databricks/check.py`:排序相关的测试不需要工作区也能跑。
  4. Flip RAG_AUTHORITY, RAG_DEDUP, RAG_GRAPH to 0 one at a time when you run step 13, to see what each feature is worth here.做第 13 步时,逐个把 RAG_AUTHORITY、RAG_DEDUP、RAG_GRAPH 设为 0,看看每个功能在这里的价值。

Scripts脚本

src/retrieval/ranking.py · compiles
"""Ranking that runs after either backend returns candidates. Pure Python, no platform calls.

This is the part of the local search tool (module 5) that no managed index does for you:
fusing two ranked lists by position, a small authority nudge, collapsing copies of one
paragraph to its most authoritative source, and a diagnostic instead of a silent empty list.
It is tested in this repository by tests/test_portable.py.
"""
from __future__ import annotations

from typing import Iterable, Optional


def rrf(lists: Iterable[list], k: int = 60) -> dict:
    """Reciprocal rank fusion. Positions only, so a cosine score and a BM25 score never meet."""
    score: dict = {}
    for ranked in lists:
        for rank, chunk_id in enumerate(ranked, start=1):
            score[chunk_id] = score.get(chunk_id, 0.0) + 1.0 / (k + rank)
    return score


def _norm(text: str) -> str:
    return " ".join(text.lower().split())


def rank(rows: dict, dense: list, lexical: list, *, k: int = 60, authority_weight: float = 0.0004,
         authority: bool = True, dedup: bool = True, top_k: int = 5) -> list:
    """rows: chunk_id -> {"chunk_id","source","text","tier",...}. dense/lexical: ranked chunk ids.

    Tier 1 is the most authoritative. The bonus is sized to one rank step near the top
    (1/61 - 1/62 = 0.00026), so it decides near ties and never jumps several ranks.
    """
    fused = rrf([dense, lexical], k)
    out = []
    for chunk_id, score in fused.items():
        row = rows.get(chunk_id)
        if not row:
            continue                                    # retired or filtered out after retrieval
        if authority:
            score += authority_weight * (3 - int(row.get("tier", 3)))
        out.append({**row, "score": round(score, 5),
                    "dense_rank": dense.index(chunk_id) + 1 if chunk_id in dense else None,
                    "lexical_rank": lexical.index(chunk_id) + 1 if chunk_id in lexical else None})
    out.sort(key=lambda r: (-r["score"], r.get("tier", 3), r["chunk_id"]))
    if dedup:
        best: dict = {}
        for r in out:
            key = _norm(r["text"])
            if key not in best or r.get("tier", 3) < best[key].get("tier", 3):
                best[key] = r
        seen, unique = set(), []
        for r in out:                                   # keep the best position, show the best source
            key = _norm(r["text"])
            if key not in seen:
                seen.add(key)
                unique.append({**best[key], "score": r["score"]})
        out = unique
    return out[:top_k]


def diagnose(hits: list, collection: Optional[str], known_collections: list) -> Optional[str]:
    """An empty result must say why, or the model fills the gap with a guess."""
    if hits:
        return None
    if collection and known_collections and collection not in known_collections:
        return f"collection '{collection}' has no chunks; known collections: {sorted(known_collections)}"
    return "no chunk shares a word or a vector direction with the query; try different terms"
src/retrieval/search_tool.py · compiles
"""Step 12. The knowledge-base search tool the agent calls. Same contract as the local tool (module 5/6).

  search_kb(query, collection, top_k) -> {"results": [...], "trace": {...}, "diagnostic"?: str}

Two candidate lists from whichever backend you chose (Lakebase or AI Search), then the
portable ranking (ranking.py), then graph expansion from the edges table. Every answer
carries a trace, so a wrong answer can be traced to the retrieval that fed it.
"""
from __future__ import annotations

import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402
from retrieval.ranking import diagnose, rank  # noqa: E402

COLS = ("chunk_id", "source", "collection", "context", "text", "tier")
DEFINE_Q = re.compile(r"\b(what is|what does|define|definition|mean)\b", re.I)


def _embed(cfg: Config, text: str) -> list:
    from databricks_openai import DatabricksOpenAI
    return DatabricksOpenAI().embeddings.create(model=cfg.embedding, input=[text]).data[0].embedding


def _lakebase(cfg: Config, query: str, collection: str) -> tuple:
    from common.pg import pool

    vec = "[" + ",".join(f"{x:.6f}" for x in _embed(cfg, query)) + "]"
    with pool().connection() as conn, conn.cursor() as cur:
        cur.execute("SELECT chunk_id FROM kb_search WHERE collection = %s ORDER BY embedding <=> %s::vector LIMIT %s",
                    (collection, vec, cfg.candidates))
        dense = [r[0] for r in cur.fetchall()]
        lexical = []
        if cfg.flags["RAG_HYBRID"]:
            cur.execute("SELECT chunk_id FROM kb_search WHERE collection = %s "
                        "ORDER BY body_tsv <@> to_bm25query(to_tsvector('english', %s), 'kb_search_bm25') LIMIT %s",
                        (collection, query, cfg.candidates))
            lexical = [r[0] for r in cur.fetchall()]
        ids = list(dict.fromkeys(dense + lexical))
        rows = {}
        if ids:
            cur.execute(f"SELECT {', '.join(COLS)} FROM kb_search WHERE chunk_id = ANY(%s)", (ids,))
            rows = {r[0]: dict(zip(COLS, r)) for r in cur.fetchall()}
        cur.execute("SELECT DISTINCT collection FROM kb_search")
        known = [r[0] for r in cur.fetchall()]
    return dense, lexical, rows, known


def _ai_search(cfg: Config, query: str, collection: str) -> tuple:
    from retrieval.ai_search_index import two_lists

    d, l = two_lists(cfg, query, cfg.candidates, collection)  # filtered in the index, not after
    rows, lists = {}, []
    for res in (d, l):
        cols = [c["name"] for c in res.get("manifest", {}).get("columns", [])]
        ranked = []
        for row in res.get("result", {}).get("data_array", []):
            r = dict(zip(cols, row))
            rows[r["chunk_id"]] = {k: r.get(k) for k in COLS}
            ranked.append(r["chunk_id"])
        lists.append(ranked)
    return lists[0], (lists[1] if cfg.flags["RAG_HYBRID"] else []), rows, _known_collections(cfg)


def _sql_conn():
    """A SQL warehouse connection, or None when no warehouse is configured (the app gets the id from
    its sql_warehouse resource as DATABRICKS_WAREHOUSE_ID)."""
    wh = os.environ.get("DATABRICKS_WAREHOUSE_ID")
    if not wh:
        return None
    from databricks import sql
    from databricks.sdk.core import Config as SdkConfig

    sdk = SdkConfig()
    return sql.connect(server_hostname=sdk.host.replace("https://", ""), http_path=f"/sql/1.0/warehouses/{wh}",
                       credentials_provider=lambda: sdk.authenticate)


def _known_collections(cfg: Config) -> list:
    """For the diagnostic only. An empty list makes the diagnostic generic instead of wrong."""
    conn = _sql_conn()
    if conn is None:
        return []
    with conn, conn.cursor() as cur:
        cur.execute(f"SELECT DISTINCT collection FROM {cfg.chunks} WHERE NOT retired")
        return [r[0] for r in cur.fetchall()]


def _expand(cfg: Config, query: str, hits: list, limit: int = 3):
    """Graph expansion from the Delta edges table, through a SQL warehouse (databricks-sql-connector).
    Returns None when no warehouse is configured, so the trace can say expansion was skipped."""
    conn = _sql_conn()
    if conn is None:
        return None
    added, have = [], {h["chunk_id"] for h in hits}
    with conn, conn.cursor() as cur:
        targets = []
        if DEFINE_Q.search(query):
            cur.execute(f"SELECT from_key, to_chunk FROM {cfg.edges} WHERE relation = 'defines'")
            targets += [(c, f"defines:{t}") for t, c in cur.fetchall() if t in query.lower()]
        top = [h["chunk_id"] for h in hits[:3]]
        if top:
            cur.execute(f"""SELECT c.from_key, s.to_chunk FROM {cfg.edges} c
                            JOIN {cfg.edges} s ON s.relation = 'section' AND s.from_key = c.to_chunk
                            WHERE c.relation = 'cites' AND c.from_key IN ({', '.join(['?'] * len(top))})""", top)
            targets += [(c, f"cited-by:{f}") for f, c in cur.fetchall()]
        for chunk_id, via in targets:
            if chunk_id in have or len(added) >= limit:
                continue
            cur.execute(f"SELECT {', '.join(COLS)} FROM {cfg.chunks} WHERE chunk_id = ? AND NOT retired", [chunk_id])
            r = cur.fetchone()
            if r:
                added.append({**dict(zip(COLS, r)), "via": via})
                have.add(chunk_id)
    return added


def search_kb(query: str, collection: str = "policy", top_k: int = 5) -> dict:
    cfg = Config()
    backend = _lakebase if cfg.retrieval == "lakebase" else _ai_search
    dense, lexical, rows, known = backend(cfg, query, collection)
    hits = rank(rows, dense, lexical, k=cfg.rrf_k, authority_weight=cfg.authority_weight,
                authority=cfg.flags["RAG_AUTHORITY"], dedup=cfg.flags["RAG_DEDUP"], top_k=top_k)
    extra = _expand(cfg, query, hits) if cfg.flags["RAG_GRAPH"] and hits else []
    graph = "skipped: no DATABRICKS_WAREHOUSE_ID" if extra is None else len(extra)
    extra = extra or []
    out = {"query": query, "collection": collection, "results": hits + extra,
           "trace": {"backend": cfg.retrieval, "dense": len(dense), "lexical": len(lexical), "expanded": graph}}
    why = diagnose(hits, collection, known)
    if why:
        out["diagnostic"] = why
    return out


if __name__ == "__main__":
    import json
    print(json.dumps(search_kb(" ".join(sys.argv[1:]) or "lodging cap"), indent=2)[:4000])

How to read the result如何解读结果

  • Each result shows dense_rank and lexical_rank. A top hit with lexical_rank only is a keyword win (a code or a name); dense_rank only is a meaning win. Both null is a graph expansion, and `via` says which edge.每条结果都显示 dense_rank 和 lexical_rank。只有 lexical_rank 的首条结果是关键词胜出(编码或名称);只有 dense_rank 的是语义胜出。两者都为 null 的是图扩展结果,`via` 会说明是哪条边。
  • `trace` counts are the first thing to read on a bad answer: dense 20, lexical 0 means BM25 found nothing, which is a tokenization or index problem, not a model problem.答案不对时,最先看 `trace` 里的计数:dense 20、lexical 0 说明 BM25 什么也没找到,这是分词或索引的问题,不是模型的问题。
  • `diagnostic: collection 'hr' has no chunks; known collections: [...]` is the tool telling the model its own parameter was wrong. The model can correct it in the next round; that is module 6's design rule working.`diagnostic: collection 'hr' has no chunks; known collections: [...]` 是工具在告诉模型它自己的参数错了。模型可以在下一轮纠正;这就是第 6 模块的设计规则在起作用。

Troubleshooting排障

You see现象Why原因Do this处理
trace says `expanded: skipped: no DATABRICKS_WAREHOUSE_ID`追踪信息显示 `expanded: skipped: no DATABRICKS_WAREHOUSE_ID`Graph expansion needs a warehouse to read the edges table, and none is configured.图扩展需要 warehouse 来读取边表,而当前没有配置。Set the warehouse id (locally) or add the sql_warehouse resource and its valueFrom entry (in the app).在本地设置 warehouse id,或者在 App 中添加 sql_warehouse 资源及其 valueFrom 配置。
The same paragraph appears twice with different sources同一段落以不同来源出现了两次Whitespace or punctuation differs between the copies, so the normalized text differs.副本之间空白或标点不同,所以规范化后的文本不同。Strengthen _norm (strip punctuation) in ranking.py and add a test with your two strings.加强 ranking.py 中的 _norm(去掉标点),并用你这两段文字添加一个测试。
Done when完成标准The approving-official question returns the defining chunk with via `defines:approving official`, and the portable tests pass.“approving official”的问题返回了定义它的文本块,via 为 `defines:approving official`,并且可移植测试全部通过。
Not confirmed on a vendor page未在厂商页面上确认The SQL connector's `?` parameter markers and `credentials_provider=lambda: cfg.authenticate` follow the connector's documented app pattern; not run here.SQL connector 的 `?` 参数占位符和 `credentials_provider=lambda: cfg.authenticate` 用的是该连接器文档中针对 App 的写法;这里没有实际运行。
13Prove retrieval parity with the local gold set用本地标准集证明检索效果一致
Replaces替代nightly/retrieval_eval.py: hit rate and MRR on the hand-written gold set.nightly/retrieval_eval.py:在人工编写的标准集上计算命中率和 MRR。

Why this step, and why here为什么要做这一步,为什么在这里

A migration that changes retrieval quality silently changes every answer. The gold set already exists, was written by a person, and was sealed before anything learned from it, so it is the fair judge. Running it now, before the agent exists, isolates retrieval: if the agent is worse later and retrieval matched here, the cause is elsewhere.如果迁移悄悄改变了检索质量,那么每一个答案都会悄悄改变。标准集已经存在,由人编写,并且在任何学习发生之前就已封存,所以它是公正的裁判。在智能体还不存在的时候就跑它,能把检索单独隔离出来:如果之后智能体变差了,而这里的检索结果是一致的,那原因就在别处。

What it does它做什么

Runs every gold question through search_kb, finds the rank of the gold chunk, and prints hit@1, hit@5 and MRR, for the full ranking and with each feature switched off.把每个标准问题都送进 search_kb,找出标准答案文本块的名次,打印 hit@1、hit@5 和 MRR,分别对应完整排序以及逐个关闭各功能的情况。

How to do it怎么做

  1. Copy the local gold file (the module 11 format: q, gold chunk id) next to the script.把本地标准文件(第 11 模块的格式:问题、标准文本块 id)复制到脚本旁边。
  2. Run the snippet with each flag combination.用每种开关组合运行这段代码。
  3. Put the local numbers from your last nightly run beside these.把你最近一次夜间运行得到的本地数据放在旁边对比。

Scripts脚本

parity.py
import json, os, sys
sys.path.insert(0, "replicate/databricks/src")
from retrieval.search_tool import search_kb

gold = json.load(open("gold_v1.json"))["items"]          # [{"q": ..., "gold": "policy/x.md::3"}, ...]
def run(label):
    ranks = []
    for g in gold:
        ids = [r["chunk_id"] for r in search_kb(g["q"], g.get("collection", "policy"), top_k=10)["results"]]
        ranks.append(ids.index(g["gold"]) + 1 if g["gold"] in ids else None)
    n = len(ranks)
    hit = lambda k: sum(1 for r in ranks if r and r <= k) / n
    mrr = sum(1 / r for r in ranks if r) / n
    print(f"{label:14} n={n}  hit@1 {hit(1):.3f}  hit@5 {hit(5):.3f}  mrr {mrr:.3f}")

run("full")
for flag in ("RAG_HYBRID", "RAG_AUTHORITY", "RAG_DEDUP", "RAG_GRAPH"):
    os.environ[flag] = "0"; run("no-" + flag[4:].lower()); os.environ[flag] = "1"

How to read the result如何解读结果

  • Read it like the module 11 table: `full 15 0.667 1.000 1.000` locally. A replica within one question of that on hit@5 is at parity; with 15 questions, one question is 0.067, so smaller differences are noise.像读第 11 模块那张表一样读它:本地是 `full 15 0.667 1.000 1.000`。副本在 hit@5 上与之相差不超过一道题,就算一致;只有 15 道题时,一道题就是 0.067,比这更小的差异属于噪声。
  • If `no-hybrid` equals `full`, keyword search contributes nothing on your questions; if it drops, BM25 is earning its cost. The local build saw dense-only lose on exact tokens.如果 `no-hybrid` 与 `full` 相同,说明在你的问题上关键词检索没有贡献;如果下降了,说明 BM25 物有所值。本地构建中,只用稠密检索在精确词上会输。
  • A large drop in hit@1 with hit@5 unchanged usually means the authority nudge or dedup is not working: the right passage is retrieved but a copy from a lower tier sits above it.hit@1 大幅下降而 hit@5 不变,通常说明权威加权或去重没起作用:正确的段落找到了,但一个来自较低等级的副本排在了它前面。
  • Gold chunk ids include the path. If every rank is None, the paths differ between the local bank and the volume (for example a different root folder); fix the ids, not the search.标准文本块 id 包含路径。如果所有名次都是 None,说明本地知识库与 volume 之间路径不同(例如根目录不同);要改的是 id,而不是检索。

Troubleshooting排障

You see现象Why原因Do this处理
Numbers are much lower than locally数据比本地低很多Different embedding model, or context not embedded with the text.embedding 模型不同,或者没有把上下文和文本一起嵌入。Confirm the index embeds `embed_text` (context + text). Then accept that a different embedding model is a different system and re-tune only after measuring.确认索引嵌入的是 `embed_text`(上下文加文本)。然后要接受:不同的 embedding 模型就是一个不同的系统,先测量再调参。
Results vary between runs每次运行结果都不同A sync or refresh happened between runs.两次运行之间发生了同步或刷新。Pause the ingest job while you measure, or record the Delta version you measured against.测量期间暂停 ingest job,或者记录你测量时所用的 Delta 版本。
Done when完成标准A written comparison: local and replica hit@1, hit@5, MRR side by side, with each difference explained or within one question.一份书面对比:本地与副本的 hit@1、hit@5、MRR 并排列出,每个差异要么有解释,要么在一道题以内。

5 The agent: tools, prompts, memory, harness智能体:工具、提示词、记忆、Harness

The pieces the agent loop calls are built first, each tested on its own, so that when the loop is assembled every failure has one place to be. This is the same order as the curriculum: tools before the harness, the guard inside the harness, memory behind a partition argument.先构建智能体循环要调用的各个部件,并逐一单独测试,这样循环组装起来之后,每种失败都只有一个可能的出处。这与课程的顺序相同:工具先于 Harness,护栏在 Harness 内部,记忆藏在分区参数之后。

14Data tools as Unity Catalog functions, exposed through managed MCP把数据工具做成 Unity Catalog 函数,并通过托管 MCP 暴露
Replaces替代The tool registry with typed schemas, row limits and diagnostics, and the brainbank MCP server.带类型化 schema、行数上限和诊断信息的工具注册表,以及 brainbank MCP 服务。

Why this step, and why here为什么要做这一步,为什么在这里

A tool that reads company data is a permission boundary. As a Unity Catalog function it is governed like a table: who may EXECUTE it is a grant, its description is the COMMENT, and the same function serves your agent, a notebook, and any MCP client through the managed endpoint. Writing it in SQL keeps the query inside the governed engine; the caller never holds a warehouse token.读取公司数据的工具就是一道权限边界。作为 Unity Catalog 函数,它像表一样被治理:谁能 EXECUTE 是一条授权,它的说明就是 COMMENT,同一个函数可以同时服务你的智能体、notebook,以及通过托管端点接入的任何 MCP 客户端。用 SQL 编写,让查询留在受治理的引擎内部;调用方从不持有 warehouse 令牌。

What it does它做什么

query_expenses.sql creates agentlab.tools.query_expenses(employee_id, claim_month) returning JSON with rows, count, total, and a diagnostic that says which filter emptied the result. claim_month has a DEFAULT, so it can be left out, which is what lets the learner prove a month filter emptied a result. uc_tools.py calls it twice through unitycatalog-ai and checks the module 6 contract.query_expenses.sql 创建 agentlab.tools.query_expenses(employee_id, claim_month),返回包含 rows、count、total 的 JSON,以及一个说明是哪个过滤条件导致结果为空的诊断字段。claim_month 带有默认值,可以省略,学习器正是靠这一点来证明是月份过滤导致了空结果。uc_tools.py 通过 unitycatalog-ai 调用它两次,检查第 6 模块定下的工具契约。

How to do it怎么做

  1. Point the function at your table (agentlab.finance.expenses is a placeholder) and run the SQL file.把函数指向你自己的表(agentlab.finance.expenses 只是占位名),然后运行 SQL 文件。
  2. Run `python uc_tools.py`. Both lines must print PASS.运行 `python uc_tools.py`。两行都必须打印 PASS。
  3. For MCP clients, use the managed endpoint `https://<workspace-host>/api/2.0/mcp/functions/agentlab/tools/query_expenses`. The vendor page recommends the Unity Gateway MCP pattern for new connections.MCP 客户端使用托管端点 `https://<workspace-host>/api/2.0/mcp/functions/agentlab/tools/query_expenses`。厂商页面建议新连接采用 Unity Gateway 的 MCP 方式。
  4. Grant EXECUTE to the app's service principal after step 18 creates it.在第 18 步创建好 App 的服务主体后,向它授予 EXECUTE。

Scripts脚本

src/tools/query_expenses.sql · read only
-- Step 14. A data tool as a Unity Catalog SQL function.
-- Local build (module 6): query_expenses with a typed schema, a row limit, and a diagnostic
-- when a filter matches nothing. A SQL function keeps the query inside the governed engine:
-- the caller needs EXECUTE on the function, and the function reads the table with UC permissions.
-- The COMMENT on the function and on each parameter is what the model sees as the tool description.
-- claim_month has a DEFAULT, so the learner (step 21) can re-run a call without it to prove that the
-- month filter, not the employee, emptied a result. employee_id has none: it is never relaxed.

CREATE SCHEMA IF NOT EXISTS agentlab.tools COMMENT 'Functions agents may call';

CREATE OR REPLACE FUNCTION agentlab.tools.query_expenses(
  employee_id STRING COMMENT 'Employee id, for example E-1042',
  claim_month STRING DEFAULT NULL COMMENT 'Month as YYYY-MM, for example 2026-03. Leave out for all months.'
)
RETURNS STRING
COMMENT 'Approved expenses for one employee in one month. Returns JSON with rows, count, total. When nothing matches, the diagnostic field says which filter emptied the result.'
RETURN
  SELECT to_json(named_struct(
    'count', m.n,
    'total', m.total,
    'rows',  m.rows,
    'diagnostic', CASE
      WHEN m.n > 0 THEN NULL
      WHEN a.n > 0 THEN concat('employee ', employee_id, ' has ', a.n, ' claims in other months; the month filter emptied this result')
      ELSE concat('no claims at all for employee ', employee_id, '; check the id')
    END))
  FROM (
    SELECT count(*) AS n,
           round(coalesce(sum(amount), 0), 2) AS total,
           slice(collect_list(named_struct('claim_id', claim_id, 'amount', amount)), 1, 200) AS rows
    FROM agentlab.finance.expenses
    WHERE employee = employee_id
      AND (claim_month IS NULL OR date_format(claim_date, 'yyyy-MM') = claim_month)
      AND status = 'approved'
  ) m,
  (SELECT count(*) AS n FROM agentlab.finance.expenses WHERE employee = employee_id) a;

GRANT EXECUTE ON FUNCTION agentlab.tools.query_expenses TO `agent-builders`;

-- Try it. The second call must return a diagnostic, not a bare zero.
SELECT agentlab.tools.query_expenses('E-1042', '2026-03');
SELECT agentlab.tools.query_expenses('E-1042', '1999-01');
src/tools/uc_tools.py · compiles
"""Step 14. Call the Unity Catalog tools the way an agent will, and check the tool contract.

Create the function first (query_expenses.sql). Then:
  pip install unitycatalog-ai databricks-sdk
  python uc_tools.py
The managed MCP endpoint that exposes the same function to any MCP client is:
  https://<workspace-host>/api/2.0/mcp/functions/<catalog>/<schema>/<function_name>
"""
from __future__ import annotations

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402


def contract_ok(raw: str, expect_rows: bool) -> tuple:
    """The two rules from module 6: a result is JSON, and an empty result carries a diagnostic."""
    try:
        out = json.loads(raw)
    except (TypeError, ValueError):
        return False, f"not JSON: {str(raw)[:80]}"
    if expect_rows and not out.get("count"):
        return False, "expected rows, got none"
    if not out.get("count") and not out.get("diagnostic"):
        return False, "empty result without a diagnostic"
    return True, out.get("diagnostic") or f"{out['count']} rows, total {out['total']}"


def main() -> None:  # pragma: no cover
    from unitycatalog.ai.core.databricks import DatabricksFunctionClient

    cfg = Config()
    fn = f"{cfg.catalog}.tools.query_expenses"
    client = DatabricksFunctionClient()            # serverless execution; local mode does not run SQL functions
    for args, expect in (({"employee_id": "E-1042", "claim_month": "2026-03"}, True),
                         ({"employee_id": "E-1042", "claim_month": "1999-01"}, False)):
        res = client.execute_function(fn, args)
        raw = getattr(res, "value", res)
        ok, detail = contract_ok(raw, expect)
        print(f"{'PASS' if ok else 'FAIL'} {args} -> {detail}")


if __name__ == "__main__":  # pragma: no cover
    main()

How to read the result如何解读结果

  • `PASS {... '2026-03'} -> 4 rows, total 219.0` is a working tool. `PASS {... '1999-01'} -> employee E-1042 has 12 claims in other months; the month filter emptied this result` is the more important line: the empty case explains itself.`PASS {... '2026-03'} -> 4 rows, total 219.0` 表示工具正常工作。`PASS {... '1999-01'} -> employee E-1042 has 12 claims in other months; the month filter emptied this result` 这一行更重要:空结果自己说明了原因。
  • `FAIL ... empty result without a diagnostic` means a model will read `count 0` and report zero spending as a fact. That is the module 6 failure story; do not ship the tool until it passes.`FAIL ... empty result without a diagnostic` 意味着模型会读到 `count 0`,并把“零支出”当作事实报告出去。这就是第 6 模块的失败案例;在它通过之前,不要上线这个工具。
  • The parameter COMMENTs become the tool's argument descriptions. If the model passes '03/2026', the format in the COMMENT was not specific enough.参数的 COMMENT 会成为工具参数的说明。如果模型传入了 '03/2026',说明 COMMENT 里对格式的描述还不够具体。

Troubleshooting排障

You see现象Why原因Do this处理
`execute_function` fails in local mode`execute_function` 在 local 模式下失败Local execution does not run SQL functions.本地执行模式不运行 SQL 函数。Use the default (serverless) client, as the script does.像脚本那样使用默认的(serverless)客户端。
The agent gets PERMISSION_DENIED calling the tool智能体调用工具时报 PERMISSION_DENIEDThe app's service principal lacks EXECUTE on the function, or SELECT on the table it reads.App 的服务主体对该函数没有 EXECUTE 权限,或者对它所读取的表没有 SELECT 权限。Grant both, to the app principal, not to your user.把这两项权限都授予 App 的服务主体,而不是你自己的用户。
Totals differ from the local tool合计数与本地工具不一致Status or date logic differs (for example time zones on claim_date).状态或日期逻辑不同(例如 claim_date 的时区)。Compare on one employee and one month; the function must match the local query row for row.拿一个员工、一个月份来对比;函数结果必须与本地查询逐行一致。
Done when完成标准Both calls PASS and the function is visible in Catalog with its COMMENT.两次调用都 PASS,并且能在 Catalog 中看到该函数及其 COMMENT。
Not confirmed on a vendor page未在厂商页面上确认The `.value` attribute on the execution result and the `replace` behavior come from the unitycatalog-ai client; the script reads the value defensively.执行结果上的 `.value` 属性以及替换行为来自 unitycatalog-ai 客户端;脚本读取时做了防御处理。
15Base prompt and skills as versioned prompts把基础提示词和技能做成带版本的提示词

Why this step, and why here为什么要做这一步,为什么在这里

On the Mac a prompt change was a file edit and a restart, and rollback was git. In a deployed app a redeploy is slower and riskier than the change. A prompt registry gives each prompt versions and an alias: the agent loads `@production`, you register a new version, evaluate it, and move the alias. Rollback becomes moving the alias back, in seconds, with no deploy.在 Mac 上,改提示词就是改文件再重启,回滚靠 git。在已部署的 App 里,重新部署比改动本身更慢、风险更大。提示词注册表为每个提示词提供版本和别名:智能体加载 `@production`,你注册一个新版本、评估它、再移动别名。回滚就是把别名移回去,几秒钟完成,不需要部署。

What it does它做什么

Reads AGENT.md and every skills/*/SKILL.md, converts {name} placeholders to the registry's {{name}} syntax, and registers each as agentlab.skills.<name>. Skill matching stays in harness.py, tested here.读取 AGENT.md 和每个 skills/*/SKILL.md,把 {name} 占位符转成注册表使用的 {{name}} 语法,并把每一个注册为 agentlab.skills.<name>。技能匹配仍在 harness.py 中完成,并在这里经过测试。

How to do it怎么做

  1. `CREATE SCHEMA IF NOT EXISTS agentlab.skills`, then `python register_prompts.py /path/to/agent-server`.执行 `CREATE SCHEMA IF NOT EXISTS agentlab.skills`,然后运行 `python register_prompts.py /path/to/agent-server`。
  2. For each prompt, set alias `production` on version 1 with mlflow.genai.set_prompt_alias.对每个提示词,用 mlflow.genai.set_prompt_alias 在版本 1 上设置别名 `production`。
  3. Update the SKILLS trigger words in agent.py to match your skill folders.更新 agent.py 中 SKILLS 的触发词,使之与你的技能目录一致。
  4. From now on: new version, run step 19, then move the alias. Never edit production in place.从现在起:新建版本,运行第 19 步,再移动别名。绝不在 production 上就地修改。

Scripts脚本

src/skills/register_prompts.py · compiles
"""Step 15. The base prompt and the skills, as versioned prompts in Unity Catalog.

Local build (module 8): AGENT.md is the base prompt; each skill is a folder with SKILL.md,
matched to a request and injected into the prompt. Here each of those files becomes a
registered prompt with versions and an alias. The agent loads "@production"; a change is a
new version, evaluated, then the alias moves. Rolling back is moving the alias back.

  python register_prompts.py /path/to/agent-server     # reads AGENT.md and skills/*/SKILL.md
"""
from __future__ import annotations

import os
import re
import sys
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402


def to_double_brace(text: str) -> str:
    """MLflow prompt templates use {{name}}. Turn single-brace {name} placeholders into double braces,
    leaving braces that are already doubled, and JSON-looking braces, alone."""
    return re.sub(r"(?<!\{)\{([a-z_][a-z0-9_]*)\}(?!\})", r"{{\1}}", text)


def collect(root: Path) -> dict:
    found = {}
    base = root / "AGENT.md"
    if base.exists():
        found["agent_base"] = base.read_text()
    for skill in sorted((root / "skills").glob("*/SKILL.md")):
        found["skill_" + re.sub(r"[^a-z0-9_]", "_", skill.parent.name.lower())] = skill.read_text()
    return found


def main(argv: list) -> None:  # pragma: no cover
    import mlflow

    cfg = Config()
    root = Path(argv[0] if argv else ".")
    prompts = collect(root)
    if not prompts:
        raise SystemExit(f"no AGENT.md or skills/*/SKILL.md under {root}")
    for name, text in prompts.items():
        full = f"{cfg.catalog}.skills.{name}"
        p = mlflow.genai.register_prompt(name=full, template=to_double_brace(text),
                                         commit_message=f"import from local build ({len(text)} chars)")
        print(f"{full} -> version {p.version}")
    print("Evaluate, then: mlflow.genai.set_prompt_alias(name=..., alias='production', version=N)")


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])
python
import mlflow
mlflow.genai.set_prompt_alias(name="agentlab.skills.agent_base", alias="production", version=1)
p = mlflow.genai.load_prompt(name_or_uri="prompts:/agentlab.skills.agent_base@production")
print(p.version, len(p.template))

How to read the result如何解读结果

  • `agentlab.skills.skill_expense -> version 3` on a rerun means the registry kept the old versions; nothing was overwritten. That history is what makes rollback possible.重跑时出现 `agentlab.skills.skill_expense -> version 3`,说明注册表保留了旧版本,没有任何内容被覆盖。正是这段历史让回滚成为可能。
  • If a loaded prompt shows literal `{{name}}` in an answer, the template has a variable the agent never fills. Either fill it with format() or remove the braces.如果答案里出现了字面上的 `{{name}}`,说明模板里有一个智能体从未填充的变量。要么用 format() 填上,要么去掉花括号。

Troubleshooting排障

You see现象Why原因Do this处理
register_prompt fails: schema not foundregister_prompt 失败:找不到 schemaagentlab.skills does not exist.agentlab.skills 不存在。Create the schema and grant CREATE FUNCTION or the prompt privileges your workspace requires to the registering user.创建该 schema,并给执行注册的用户授予 CREATE FUNCTION 或你工作区要求的提示词相关权限。
The agent answers with an old prompt after you moved the alias移动别名后,智能体仍在使用旧提示词The app cached the prompt at startup.App 在启动时缓存了提示词。Load per request (as agent.py does) or with a short time-based cache.按请求加载(agent.py 就是这样做的),或者使用很短的基于时间的缓存。
Done when完成标准Every local prompt exists in the registry with a production alias, and load_prompt returns it.每个本地提示词都已在注册表中,并带有 production 别名,load_prompt 能取回它。
16Memory in Lakebase, partitioned by the signed-in user把记忆放进 Lakebase,按登录用户分区

Why this step, and why here为什么要做这一步,为什么在这里

Memory is many small writes and reads by key, on every turn, which is what Postgres is for and what Delta is not. The partition is the safety property: every function takes the user, and the user comes from the request headers the app receives after sign-in, never from model output. A model that is tricked into naming another user still reads only its own partition.记忆就是每一轮都发生的大量按键的小读写,这正是 Postgres 擅长而 Delta 不擅长的。分区是安全属性:每个函数都接收用户参数,而用户来自 App 在登录后收到的请求头,绝不来自模型输出。即使模型被诱导说出另一个用户的名字,它读到的仍然只是自己的分区。

What it does它做什么

common/pg.py opens a pool that mints a fresh OAuth database credential per connection. memory/store.py creates two tables, writes facts with an upsert, builds a short briefing, recalls past turns by vector similarity inside the partition with a floor, and runs extraction after the answer on a background thread.common/pg.py 建立一个连接池,每个连接都生成新的 OAuth 数据库凭证。memory/store.py 创建两张表,用 upsert 写入事实,生成简短的用户简报,在分区内按向量相似度回忆过去的对话(带相似度下限),并在回答之后用后台线程执行信息提取。

How to do it怎么做

  1. Use the Lakebase project from step 10, or create one if you chose AI Search.使用第 10 步的 Lakebase 项目;如果你选的是 AI Search,就新建一个。
  2. Set ENDPOINT_NAME, PGHOST, PGDATABASE, PGUSER for a service principal, then `Memory(pool(), embed).init()` once.为服务主体设置 ENDPOINT_NAME、PGHOST、PGDATABASE、PGUSER,然后执行一次 `Memory(pool(), embed).init()`。
  3. In the app, read the user from the forwarded identity header and pass it as the partition.在 App 中,从转发的身份请求头读取用户,并把它作为分区传入。
  4. Test the boundary: write a fact as user A, then call recall and briefing as user B.测试边界:以用户 A 写入一条事实,再以用户 B 调用 recall 和 briefing。

Scripts脚本

src/common/pg.py · compiles
"""Lakebase connection pool with OAuth credentials (pattern from the vendor's "connect an external app" page).

Both the workspace OAuth token and the database credential expire after 60 minutes. The pool
asks for a fresh credential each time it opens a connection and recycles connections at
45 minutes, so no connection outlives its password.

  pip install "psycopg[binary,pool]" databricks-sdk
Environment: DATABRICKS_HOST, DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET (a service principal),
             ENDPOINT_NAME, PGHOST, PGDATABASE, PGUSER (= the service principal's client ID).
Inside a Databricks App with a Lakebase resource attached, the platform sets the PG* variables.
"""
from __future__ import annotations

import os
import sys
from functools import lru_cache

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402


@lru_cache(maxsize=1)
def _workspace():
    from databricks.sdk import WorkspaceClient
    return WorkspaceClient()        # reads DATABRICKS_HOST / CLIENT_ID / CLIENT_SECRET, or the CLI profile


@lru_cache(maxsize=1)
def pool():
    import psycopg
    from psycopg_pool import ConnectionPool

    cfg = Config()
    if not (cfg.pg_endpoint and cfg.pg_host and cfg.pg_user):
        raise RuntimeError("Lakebase is not configured: set ENDPOINT_NAME, PGHOST and PGUSER")

    class OAuthConnection(psycopg.Connection):
        @classmethod
        def connect(cls, conninfo="", **kwargs):
            cred = _workspace().postgres.generate_database_credential(endpoint=cfg.pg_endpoint)
            kwargs["password"] = cred.token
            return super().connect(conninfo, **kwargs)

    conninfo = (f"dbname={cfg.pg_database} user={cfg.pg_user} host={cfg.pg_host} "
                f"port={os.environ.get('PGPORT', '5432')} sslmode={os.environ.get('PGSSLMODE', 'require')}")
    return ConnectionPool(conninfo, connection_class=OAuthConnection, min_size=1, max_size=10,
                          max_lifetime=45 * 60, open=True)
src/memory/store.py · compiles
"""Step 16. Memory in Lakebase Postgres: facts per user (the briefing) and turns (recall).

Local build (module 9): memory_store.py with a partition argument on every read and write,
a short briefing in every prompt, recall as a tool, and extraction after the answer in the
background. Same here. The partition is the signed-in user's identity, taken from the request
headers the app receives, never from anything the model says.
"""
from __future__ import annotations

import os
import sys
import threading

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

SCHEMA = """
CREATE TABLE IF NOT EXISTS mem_facts (
  partition  text NOT NULL,
  key        text NOT NULL,
  value      text NOT NULL,
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (partition, key)
);
CREATE TABLE IF NOT EXISTS mem_turns (
  id         bigserial PRIMARY KEY,
  partition  text NOT NULL,
  role       text NOT NULL,
  content    text NOT NULL,
  embedding  vector(%(dim)s),
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS mem_turns_partition ON mem_turns (partition, created_at DESC);
"""
# Run init() as the role the app connects as (its service principal), so the app owns its tables.
# If an admin runs it instead: GRANT SELECT, INSERT, UPDATE ON mem_facts, mem_turns TO "<app client id>";
#                              GRANT USAGE ON SEQUENCE mem_turns_id_seq TO "<app client id>";
RECALL_FLOOR = 0.25          # below this similarity say nothing, rather than guess (same as module 9)


class Memory:
    def __init__(self, pool, embed=None, dim: int = 1024):
        self.pool, self.embed, self.dim = pool, embed, dim

    def init(self) -> None:
        with self.pool.connection() as c:
            c.execute("CREATE EXTENSION IF NOT EXISTS vector")
            c.execute(SCHEMA % {"dim": self.dim})

    def remember(self, partition: str, key: str, value: str) -> None:
        with self.pool.connection() as c:
            c.execute("INSERT INTO mem_facts (partition, key, value) VALUES (%s, %s, %s) "
                      "ON CONFLICT (partition, key) DO UPDATE SET value = excluded.value, updated_at = now()",
                      (partition, key, value))

    def briefing(self, partition: str, limit: int = 8) -> str:
        """A few lines for the system prompt. Short on purpose: it is paid for on every turn."""
        with self.pool.connection() as c:
            rows = c.execute("SELECT key, value FROM mem_facts WHERE partition = %s ORDER BY updated_at DESC LIMIT %s",
                             (partition, limit)).fetchall()
        return "\n".join(f"- {k}: {v}" for k, v in rows)

    def log_turn(self, partition: str, role: str, content: str) -> None:
        vec = self.embed(content) if self.embed else None
        with self.pool.connection() as c:
            c.execute("INSERT INTO mem_turns (partition, role, content, embedding) VALUES (%s, %s, %s, %s::vector)",
                      (partition, role, content, None if vec is None else "[" + ",".join(map(str, vec)) + "]"))

    def recall(self, partition: str, query: str, k: int = 3) -> list:
        """Past turns of THIS user only. The WHERE partition clause is the boundary; keep it first."""
        vec = "[" + ",".join(map(str, self.embed(query))) + "]"
        with self.pool.connection() as c:
            rows = c.execute("SELECT content, 1 - (embedding <=> %s::vector) AS sim FROM mem_turns "
                             "WHERE partition = %s AND embedding IS NOT NULL ORDER BY embedding <=> %s::vector LIMIT %s",
                             (vec, partition, vec, k)).fetchall()
        return [{"content": r[0], "similarity": round(float(r[1]), 3)} for r in rows if r[1] >= RECALL_FLOOR]

    def after_answer(self, partition: str, user_text: str, answer: str, extract) -> threading.Thread:
        """Runs after the response is sent. A failure here is logged and never reaches the user."""
        def job():
            try:
                self.log_turn(partition, "user", user_text)
                self.log_turn(partition, "assistant", answer)
                for key, value in extract(user_text):
                    self.remember(partition, key, value)
            except Exception as e:                     # noqa: BLE001
                print("memory pipeline failed:", type(e).__name__, str(e)[:200])
        t = threading.Thread(target=job, daemon=True)
        t.start()
        return t
python
from common.pg import pool
from memory.store import Memory
from databricks_openai import DatabricksOpenAI

oa = DatabricksOpenAI()
embed = lambda s: oa.embeddings.create(model="databricks-qwen3-embedding-0-6b", input=[s]).data[0].embedding
m = Memory(pool(), embed)
m.init()
m.remember("user-a@example.com", "cost_center", "CC-77")
print(repr(m.briefing("user-a@example.com")))   # '- cost_center: CC-77'
print(repr(m.briefing("user-b@example.com")))   # ''   <- the boundary holds

How to read the result如何解读结果

  • An empty briefing for user B is the test passing. Anything else is a data leak, and it is a stop-the-line bug.用户 B 的简报为空,说明测试通过。其他任何结果都是数据泄露,必须立刻停下来修复。
  • recall returns similarities. Values just above the 0.25 floor are weak matches; if most recalls sit there, the model is being handed noise, so raise the floor rather than the count.recall 会返回相似度。刚过 0.25 下限的值是弱匹配;如果大多数回忆结果都落在这附近,说明模型拿到的是噪声,应该提高下限,而不是增加数量。
  • `memory pipeline failed:` in the app logs with the answer still delivered is the design working: memory is never allowed to break a response.App 日志里出现 `memory pipeline failed:`,而回答照常送达,说明设计在起作用:记忆永远不允许破坏一次回答。

Troubleshooting排障

You see现象Why原因Do this处理
`Lakebase is not configured`报 `Lakebase is not configured`ENDPOINT_NAME, PGHOST or PGUSER is empty.ENDPOINT_NAME、PGHOST 或 PGUSER 为空。Take them from the Lakebase console Connect dialog; PGUSER is the service principal's client ID.从 Lakebase 控制台的 Connect 对话框中获取;PGUSER 是服务主体的 client ID。
type "vector" does not exist报 type "vector" does not existThe extension is not installed in this database.该数据库中没有安装这个扩展。init() runs CREATE EXTENSION vector; the user needs permission to create extensions, or an admin runs it once.init() 会执行 CREATE EXTENSION vector;用户需要有创建扩展的权限,或者由管理员执行一次。
Connections fail after about an hour大约一小时后连接失败Credentials expire at 60 minutes.凭证在 60 分钟时过期。The pool recycles at 45 minutes; if you wrote your own connection code, do the same.连接池会在 45 分钟时回收连接;如果你自己写连接代码,也要这样做。
Done when完成标准Facts round-trip for one user, the second user sees nothing, and a forced pipeline error does not affect the answer.单个用户的事实能写入和读回,第二个用户什么也看不到,人为制造的管道错误不影响回答。
Not confirmed on a vendor page未在厂商页面上确认The exact forwarded identity header names the app receives were not read on a vendor page for this guide; print the request headers once in the app to find them.本指南没有在厂商页面上查到 App 收到的转发身份请求头的确切名称;在 App 中把请求头打印一次即可找到。
17Assemble the agent in the app template with the guard inside在应用模板中组装智能体,并把护栏放在里面

Why this step, and why here为什么要做这一步,为什么在这里

The template gives you the server, the Responses API surface, streaming and tracing; module 14 showed what an SDK provides. What it does not give you is the part that made the local agent trustworthy: triage before the big model, a prompt composed in a fixed order, a turn budget, and a guard that stops any money figure the evidence does not contain. Those are 60 lines of portable code, so they come with you.模板为你提供了服务器、Responses API 接口、流式输出和追踪;第 14 模块讲过 SDK 提供了什么。它没有提供的,正是让本地智能体值得信赖的那部分:调用大模型前的分流、按固定顺序组装的提示词、轮次预算,以及拦下证据中不存在的金额数字的护栏。这些是 60 行可移植的代码,所以要随身带走。

What it does它做什么

agent.py sets the Databricks client with the gateway, defines search_kb and query_expenses as function tools, and implements answer(): triage, skill match, compose, run with max_turns, then harness.guarded() which checks the draft, retries once with a corrective note, and returns the fallback text rather than an unsupported answer. With memory, a recall tool is added whose user is bound in code, not passed by the model.agent.py 配置经由网关的 Databricks 客户端,把 search_kb 和 query_expenses 定义为函数工具,并实现 answer():分流、技能匹配、组装提示词、带 max_turns 运行,然后调用 harness.guarded():检查草稿,带纠正提示重试一次,如果仍不通过,返回兜底文本而不是没有依据的答案。有记忆时会再加一个回忆工具,其用户在代码里绑定,而不是由模型传入。

How to do it怎么做

  1. Clone the vendor app templates, enter agent-openai-agents-sdk, run `uv run quickstart`.克隆厂商的应用模板,进入 agent-openai-agents-sdk,运行 `uv run quickstart`。
  2. Copy this repository's replicate/databricks/src/ folder into the template, and add databricks-openai, unitycatalog-ai[databricks], psycopg[binary,pool], databricks-sql-connector, and databricks-ai-search (AI Search backend only) to its dependencies.把本仓库的 replicate/databricks/src/ 目录复制进模板,并把 databricks-openai、unitycatalog-ai[databricks]、psycopg[binary,pool]、databricks-sql-connector,以及(仅 AI Search 后端需要的)databricks-ai-search 加入它的依赖。
  3. In the template's invoke and stream handlers, call `answer(messages, user_id, memory)` and put its tools and evidence in the response's custom_outputs (the eval reads them). For streaming, buffer the draft, run the guard, then emit: the stream gate from module 7.在模板的 invoke 和 stream 处理函数中调用 `answer(messages, user_id, memory)`,并把它返回的 tools 和 evidence 放进响应的 custom_outputs(评估会读取它们)。流式输出时,先缓冲草稿、运行护栏,再发出:这就是第 7 模块的流式闸门。
  4. `uv run start-app`, open localhost:8000, ask a policy question, an expense question, and 'hi'.运行 `uv run start-app`,打开 localhost:8000,分别问一个政策问题、一个报销问题,以及说一声“hi”。
  5. Run `python replicate/databricks/check.py` before every deploy: the harness and guard tests run in seconds.每次部署前运行 `python replicate/databricks/check.py`:Harness 和护栏的测试几秒钟就能跑完。

Scripts脚本

src/agent/agent.py · compiles
"""Step 17. The agent, written for the vendor's OpenAI Agents SDK app template.

How to use this file:
  git clone https://github.com/databricks/app-templates.git
  cd app-templates/agent-openai-agents-sdk && uv run quickstart
  copy this repository's src/ folder next to the template's agent code, then make the template's
  invoke/stream handlers call `answer()` below (the template's own agent file shows where).
  uv run start-app          # local, then open http://localhost:8000

What maps to what (local build -> here):
  agent_loop.py planner + tools        -> Agent(...) + Runner.run(max_turns=...)
  model_router.py                      -> the model name per task; the gateway handles availability
  tools/knowledge_base.py              -> search_kb (retrieval/search_tool.py)
  query_expenses in the registry       -> Unity Catalog function, called through unitycatalog-ai
  answer_guard.py                      -> guard/answer_guard.py inside harness.guarded()
  memory_store.py + conversation recall -> memory/store.py on Lakebase
"""
from __future__ import annotations

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from agents import Agent, Runner, function_tool, set_default_openai_api, set_default_openai_client  # noqa: E402
from databricks_openai import AsyncDatabricksOpenAI  # noqa: E402

from agent.harness import compose, guarded, match_skill, triage  # noqa: E402
from common.config import Config  # noqa: E402
from guard.answer_guard import FALLBACK, check  # noqa: E402

set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True))
set_default_openai_api("chat_completions")

CFG = Config()
MAX_TURNS = 6                     # the round budget from module 7: a loop that cannot finish stops, and says so
SKILLS = {                        # trigger words per skill; the text comes from the prompt registry
    "skill_expense": ["expense", "expenses", "claim", "claims", "reimbursement", "total", "spent"],
    "skill_policy": ["policy", "allowed", "cap", "limit", "rule", "approval", "approving"],
}


@function_tool
def search_kb(query: str, collection: str = "policy") -> str:
    """Search the knowledge base. Returns passages with source, tier and a trace. If nothing matches,
    the result has a 'diagnostic' field: read it and adjust the query instead of answering from memory."""
    from retrieval.search_tool import search_kb as _search
    return json.dumps(_search(query, collection), default=str)[:12000]


@function_tool
def query_expenses(employee_id: str, claim_month: str) -> str:
    """Approved expenses for one employee (E-1234) in one month (YYYY-MM). Returns JSON with rows, count,
    total, and a 'diagnostic' when a filter emptied the result."""
    from unitycatalog.ai.core.databricks import DatabricksFunctionClient
    res = DatabricksFunctionClient().execute_function(f"{CFG.catalog}.tools.query_expenses",
                                                      {"employee_id": employee_id, "claim_month": claim_month})
    return str(getattr(res, "value", res))


def load_prompt(name: str, default: str = "") -> str:
    """The production alias of a registered prompt. Falls back to `default` so a registry outage is visible
    in the logs, not fatal to every request."""
    try:
        import mlflow
        return mlflow.genai.load_prompt(name_or_uri=f"prompts:/{CFG.catalog}.skills.{name}@production").template
    except Exception as e:                                          # noqa: BLE001
        print("prompt load failed:", name, type(e).__name__)
        return default


async def answer(messages: list, user_id: str, memory=None) -> dict:
    """messages: OpenAI-style chat history. user_id: the signed-in identity from the app's request headers."""
    text = next((m["content"] for m in reversed(messages) if m.get("role") == "user"), "")
    if triage(text) == "chat":
        agent = Agent(name="chat", instructions="Reply briefly and warmly.", model=CFG.chat_fast)
        r = await Runner.run(agent, messages, max_turns=1)
        return {"answer": r.final_output, "route": "chat"}

    skill = match_skill(text, SKILLS)
    instructions = compose(load_prompt("agent_base", "You answer from tool results only."),
                           memory.briefing(user_id) if memory else "",
                           load_prompt(skill) if skill else "")
    tools = [search_kb, query_expenses]
    if memory:
        @function_tool
        def recall_conversations(query: str) -> str:
            """Search this user's own past conversations. Returns at most 3 turns above a similarity floor;
            an empty list means nothing relevant was said before."""
            return json.dumps(memory.recall(user_id, query))          # user_id is bound here, never a model argument
        tools.append(recall_conversations)
    agent = Agent(name="powerhouse", instructions=instructions, model=CFG.chat_default, tools=tools)
    used, evidence = [], []

    async def run(msgs: list) -> tuple:
        r = await Runner.run(agent, msgs, max_turns=MAX_TURNS)
        for i in r.new_items:
            kind = getattr(i, "type", "")
            if kind == "tool_call_item":
                used.append(getattr(getattr(i, "raw_item", None), "name", "") or "")
            elif kind == "tool_call_output_item":
                evidence.append(str(getattr(i, "output", "")))
        outs = [{"role": "tool", "content": e} for e in evidence]
        return str(r.final_output), outs

    out = await guarded(run, messages, check, FALLBACK)
    # tools and evidence go back to the caller (put them in the response's custom_outputs in the template's
    # handler) so the eval in step 19 can score tool use and grounding on the deployed app.
    out.update({"route": "work", "skill": skill, "tools": used, "evidence": evidence[-20:]})
    if memory:
        memory.after_answer(user_id, text, out["answer"], extract=lambda _t: [])   # plug your extractor in here
    return out
src/agent/harness.py · compiles
"""The harness rules that do not depend on any SDK. Pure Python, tested by tests/test_portable.py.

  triage       answer greetings and chit-chat without tools or the big model (module 7)
  match_skill  pick at most one skill for a request, or none (module 8)
  compose      base prompt + briefing + skill, in a fixed order with fixed headings (module 7)
  guarded      the guard loop: check, one corrective retry with the majority rule, then fallback (module 10)
"""
from __future__ import annotations

import re
from typing import Awaitable, Callable, Optional

SMALL_TALK = re.compile(r"^\s*(hi|hello|hey|thanks|thank you|good (morning|afternoon|evening)|ok|okay)( there| all)?\b[\s!.?]*$", re.I)


def triage(text: str) -> str:
    """'chat' for small talk, 'work' for everything else. Cheap, and wrong only in the safe direction."""
    return "chat" if SMALL_TALK.match(text or "") else "work"


def match_skill(text: str, skills: dict, floor: int = 2) -> Optional[str]:
    """skills: name -> list of trigger words. The skill with the most distinct hits wins, if it reaches the floor.
    A request that matches nothing gets no skill: a wrong skill is worse than none."""
    words = set(re.findall(r"[a-z0-9\-]+", (text or "").lower()))
    best, score = None, 0
    for name, triggers in sorted(skills.items()):
        hits = len(words & {t.lower() for t in triggers})
        if hits > score:
            best, score = name, hits
    return best if score >= floor else None


def compose(base: str, briefing: str = "", skill_text: str = "") -> str:
    parts = [base.strip()]
    if briefing.strip():
        parts.append("## What you know about this user\n" + briefing.strip())
    if skill_text.strip():
        parts.append("## Skill for this request\n" + skill_text.strip())
    return "\n\n".join(parts)


async def guarded(run: Callable[[list], Awaitable[tuple]], messages: list, check: Callable, fallback: str) -> dict:
    """run(messages) -> (answer, tool_messages). check(answer, evidence, strict) -> {"ok", "corrective", ...}.

    1. run once, check strictly
    2. if it fails, run again with the corrective note, check with the majority rule
    3. if it still fails, return the fallback text, never the unsupported draft
    """
    answer, tools = await run(messages)
    verdict = check(answer, messages + tools, True)
    if verdict["ok"]:
        return {"answer": answer, "attempts": 1, "guard": "pass"}
    retry_msgs = messages + [{"role": "user", "content": "[harness] " + verdict["corrective"]}]
    answer2, tools2 = await run(retry_msgs)
    verdict2 = check(answer2, messages + tools + tools2, False)
    if verdict2["ok"]:
        return {"answer": answer2, "attempts": 2, "guard": "pass after retry"}
    return {"answer": fallback, "attempts": 2, "guard": "fallback", "unsupported": verdict2.get("unsupported")}
src/guard/answer_guard.py · compiles
"""Answer guard, ported from the local build (module 10). Pure Python, no platform calls.

A draft may not state a money figure the evidence of this conversation does not contain.
Evidence is tool output and what the user said, never the assistant's own earlier words.
Deterministic, milliseconds, no model call, so it can sit in front of every response.
"""
from __future__ import annotations

import re

MONEY = re.compile(r"(?:\$\s?([\d,]+(?:\.\d+)?))|(?:([\d,]+(?:\.\d+)?)\s*(?:dollars|usd)\b)", re.I)
NUMBER = re.compile(r"\d[\d,]*(?:\.\d+)?")
CORRECTIVE = ("These figures are not in the evidence of this conversation: {figures}. "
              "Rewrite the answer using only numbers the tools returned. If the tools did not return a number, say so.")
FALLBACK = ("I ran the lookups but could not produce an answer whose figures all match the tool results. "
            "Please ask again or narrow the question.")


def _num(s: str) -> float:
    return float(s.replace(",", ""))


def claims(answer: str) -> list:
    return [_num(a or b) for a, b in MONEY.findall(answer)]


def evidence(messages: list) -> list:
    out = []
    for m in messages:
        if m.get("role") in ("tool", "user"):
            out += [_num(x) for x in NUMBER.findall(str(m.get("content") or ""))]
    return out


def grounded(value: float, ev: list) -> bool:
    """In the evidence as is, or the sum or difference of two evidence numbers."""
    near = lambda a, b: abs(a - b) <= 0.005 * max(1.0, abs(b))  # noqa: E731
    if any(near(value, e) for e in ev):
        return True
    small = sorted(set(ev))[:400]
    return any(near(value, a + b) or near(value, abs(a - b)) for i, a in enumerate(small) for b in small[i:])


def check(answer: str, messages: list, strict: bool = True) -> dict:
    ev = evidence(messages)
    stated = claims(answer)
    bad = [v for v in stated if not grounded(v, ev)]
    ok = not bad if strict else len(bad) * 2 <= len(stated)
    return {"ok": ok, "stated": stated, "unsupported": bad,
            "corrective": CORRECTIVE.format(figures=", ".join(f"{v:,.2f}" for v in bad))}

How to read the result如何解读结果

  • 'hi' must return route `chat` with no tool calls in the trace. If it calls search_kb, triage is not running first, and every greeting costs a big-model call plus a search.“hi”必须返回 route `chat`,追踪中没有任何工具调用。如果它调用了 search_kb,说明分流没有最先运行,每一句问候都要付出一次大模型调用加一次检索的代价。
  • `guard: pass after retry` on an expense question means the first draft stated a figure the tools did not return, and the corrective note fixed it. A few of these are normal. Many mean the skill prompt invites arithmetic the model gets wrong.报销问题出现 `guard: pass after retry`,说明第一版草稿给出了工具没返回的数字,纠正提示把它修正了。偶尔出现属于正常。频繁出现说明技能提示词在诱导模型做它会算错的算术。
  • `guard: fallback` is the system refusing to ship an unsupported number. It is a correct outcome, and every one is worth reading: it is either a tool gap or a prompt problem.`guard: fallback` 是系统拒绝发出没有依据的数字。这是正确的结果,而且每一条都值得细看:要么是工具有缺口,要么是提示词有问题。
  • The MLflow trace shows every model call and tool span. Compare one trace with the local request log for the same question: the shape (rounds, tools) should match.MLflow 追踪会显示每一次模型调用和工具 span。把同一个问题的追踪与本地请求日志对比:结构(轮次、工具)应当一致。

Troubleshooting排障

You see现象Why原因Do this处理
MaxTurnsExceeded报 MaxTurnsExceededThe model kept calling tools without finishing, usually because a tool keeps returning nothing useful.模型一直在调用工具而没有结束,通常是因为某个工具一直返回不了有用的信息。Read the trace: if the same tool repeats with the same arguments, fix the tool's diagnostic so the model can change course. Do not just raise MAX_TURNS.查看追踪:如果同一个工具以同样的参数反复调用,就修正该工具的诊断信息,让模型能调整方向。不要只是调大 MAX_TURNS。
Tools are never called工具从未被调用The endpoint does not support tool calling through chat completions, or the API mode is not set.该端点不支持通过 chat completions 进行工具调用,或者没有设置 API 模式。Keep set_default_openai_api("chat_completions") and pick a chat model that supports tools; test with a one-tool agent.保留 set_default_openai_api("chat_completions"),并选择支持工具调用的对话模型;用只有一个工具的智能体先测试。
The guard blocks correct answers that quote a policy threshold护栏拦下了引用政策阈值的正确回答The threshold came from search_kb output, which must count as evidence.阈值来自 search_kb 的输出,而它必须算作证据。agent.py adds every tool output to the evidence; check that search_kb results reach `tools` (tool_call_output_item).agent.py 会把每个工具的输出都加入证据;检查 search_kb 的结果是否进入了 `tools`(tool_call_output_item)。
Done when完成标准Locally: 'hi' takes the chat route, a policy question cites a passage, an expense question returns a figure that the guard passes, and the portable tests pass.在本地:“hi”走闲聊路线,政策问题引用了某个段落,报销问题返回的数字通过了护栏,可移植测试全部通过。
Not confirmed on a vendor page未在厂商页面上确认The template's handler names and file layout change between template versions; the guide does not reproduce them. `new_items` item type `tool_call_output_item` is from the OpenAI Agents SDK.模板中处理函数的名字和文件布局会随模板版本变化;本指南不复述它们。`new_items` 中的条目类型 `tool_call_output_item` 来自 OpenAI Agents SDK。

6 Ship and evaluate上线与评估

Deploy the agent as an app, then evaluate the deployed app, not a notebook copy of it. The seal and the spread carry over unchanged: a sealed question set nobody can edit, several runs, and a change counts only if it is larger than the spread.把智能体部署为 App,然后评估已部署的 App,而不是它在 notebook 里的副本。封存和波动范围原样沿用:一个没人能修改的封存问题集,多次运行,只有大于波动范围的变化才算数。

18Deploy the app with a bundle用 bundle 部署 App
Replaces替代Install-Autostart and the supervised agent-server behind the Tailscale funnel.Install-Autostart,以及位于 Tailscale funnel 之后、受守护的 agent-server。

Why this step, and why here为什么要做这一步,为什么在这里

A bundle makes the deployment a file in git: the app, its resources and their permissions, and the jobs. Redeploying is one command, and dev and prod differ only by target. The app gets its own service principal, which replaces the long-lived key the funnel needed: callers sign in, and the app acts with grants you can read.bundle 把部署变成 git 里的一个文件:App、它的资源及其权限,以及各个 job。重新部署只需一条命令,开发和生产环境只是 target 不同。App 会获得自己的服务主体,取代 funnel 所需要的长期密钥:调用方登录,App 凭着你能看得到的授权来执行操作。

What it does它做什么

databricks.yml declares variables and the dev and prod targets; resources/app.yml declares the agent app with its resources: the experiment (CAN_EDIT), every model endpoint the code calls (default, fast, embedding, each CAN_QUERY) and a SQL warehouse (CAN_USE). Deploy uploads the code and starts the app.databricks.yml 声明变量以及 dev 和 prod 两个 target;resources/app.yml 声明智能体 App,及其资源:实验(CAN_EDIT)、代码会调用的每一个模型端点(默认、快速、embedding,均为 CAN_QUERY)以及一个 SQL warehouse(CAN_USE)。部署会上传代码并启动 App。

How to do it怎么做

  1. Put the template folder at replicate/databricks/agent_app (or change source_code_path). Compare app.yml with the template's own databricks.yml and keep the template's version where they differ.把模板目录放到 replicate/databricks/agent_app(或者修改 source_code_path)。把 app.yml 与模板自带的 databricks.yml 对比,两者不同的地方以模板为准。
  2. `databricks bundle validate -t dev`, then `databricks bundle deploy -t dev`, then `databricks bundle run agent_powerhouse -t dev`.依次执行 `databricks bundle validate -t dev`、`databricks bundle deploy -t dev`、`databricks bundle run agent_powerhouse -t dev`。
  3. Add the Lakebase database as an app resource (Apps UI), then grant the app's service principal: EXECUTE on the tools, USE SCHEMA and SELECT on kb, SELECT on kb_search in Postgres, READ on the secret scope if used.在 Apps 界面把 Lakebase 数据库添加为 App 资源,然后给 App 的服务主体授权:工具的 EXECUTE、kb 的 USE SCHEMA 和 SELECT、Postgres 中 kb_search 的 SELECT,如有使用则还需 secret scope 的 READ。
  4. Query it with an OAuth token. Personal access tokens are refused.用 OAuth 令牌调用它。个人访问令牌会被拒绝。

Scripts脚本

databricks.yml · yaml parses
# Step 18. One bundle for everything that runs on a schedule, plus the agent app.
# databricks bundle validate -t dev && databricks bundle deploy -t dev
# The agent app's own databricks.yml in the vendor template is authoritative for the app block;
# copy its `resources.apps` entry here (or keep it there) rather than trusting this one blindly.
bundle:
  name: agent-replica

variables:
  catalog:
    default: agentlab
  experiment_id:
    description: MLflow experiment that holds the agent's traces
  chat_endpoint:
    default: databricks-qwen35-122b-a10b
  chat_fast_endpoint:
    default: databricks-qwen3-next-80b-a3b-instruct
  embedding_endpoint:
    default: databricks-qwen3-embedding-0-6b
  retrieval:
    description: lakebase or ai_search (step 9)
    default: lakebase
  eval_experiment_id:
    description: MLflow experiment for evaluation runs (keep it separate from the app's traces)
  app_url:
    description: URL of the deployed agent app (shown by `databricks apps get agent-powerhouse`)
  warehouse_id:
    description: SQL warehouse the app uses for graph expansion

include:
  - resources/*.yml

targets:
  dev:
    mode: development          # resources get a [dev <user>] prefix and schedules are paused
    default: true
  prod:
    mode: production
resources/app.yml · yaml parses
# The agent as a Databricks App. Names starting with "agent-" appear in the workspace agents list.
# Confirmed on the vendor's author-an-agent page: an experiment resource with CAN_EDIT and a serving
# endpoint resource with CAN_QUERY. The others follow the same shape; compare with the template's
# databricks.yml and the Apps resources page, and keep theirs where they differ.
# Every endpoint the code calls needs its own resource, or that call fails with 403 at runtime:
# the default chat model, the fast model (small-talk route), and the embedding model (search, memory).
resources:
  apps:
    agent_powerhouse:
      name: agent-powerhouse
      description: Replica of the local agent, served from the OpenAI Agents SDK template
      source_code_path: ../agent_app             # the cloned template folder, with src/ copied in
      resources:
        - name: experiment
          experiment:
            experiment_id: ${var.experiment_id}
            permission: CAN_EDIT
        - name: model
          serving_endpoint:
            name: ${var.chat_endpoint}
            permission: CAN_QUERY
        - name: model-fast
          serving_endpoint:
            name: ${var.chat_fast_endpoint}
            permission: CAN_QUERY
        - name: embedding
          serving_endpoint:
            name: ${var.embedding_endpoint}
            permission: CAN_QUERY
        - name: sql_warehouse                    # graph expansion and the diagnostic's collection list
          sql_warehouse:
            id: ${var.warehouse_id}
            permission: CAN_USE
        # Lakebase (memory, and retrieval if AGENT_RETRIEVAL=lakebase): add the database resource in the
        # Apps UI or here as the vendor's resources page shows (key "postgres", permission
        # CAN_CONNECT_AND_CREATE). The platform then sets the PG* variables for the app.
# In the template's app config (env section), map resources to the variables the code reads:
#   - name: DATABRICKS_WAREHOUSE_ID
#     valueFrom: sql_warehouse
bash
APP_URL=$(databricks apps get agent-powerhouse -o json | python3 -c 'import json,sys; print(json.load(sys.stdin)["url"])')
curl -sS -X POST "$APP_URL/responses" \
  -H "Authorization: Bearer $(databricks auth token -o json | python3 -c 'import json,sys; print(json.load(sys.stdin)["access_token"])')" \
  -H "Content-Type: application/json" \
  -d '{"input": [{"role": "user", "content": "What is the nightly lodging cap?"}]}'

How to read the result如何解读结果

  • `bundle validate` prints the resolved configuration. Read the app's resources there: a missing serving_endpoint resource means the app cannot call the model at runtime, even if your user can.`bundle validate` 会打印解析后的配置。在那里查看 App 的资源:缺少 serving_endpoint 资源,意味着 App 在运行时无法调用模型,哪怕你自己的用户可以。
  • In dev mode resources are prefixed with your name and schedules are paused. That is intended: dev deploys never run nightly jobs against production data.在 dev 模式下,资源会带上你名字的前缀,调度也处于暂停状态。这是有意为之:开发部署永远不会针对生产数据运行夜间任务。
  • The deployed answer to the lodging question should match the local one. If it differs, compare traces before changing anything: retrieval, tool, or model.已部署 App 对住宿上限问题的回答应当与本地一致。如果不同,先对比追踪再做任何改动:检索、工具,还是模型。

Troubleshooting排障

You see现象Why原因Do this处理
401 or 403 from the app URL访问 App URL 返回 401 或 403A personal access token, or your user lacks CAN_USE on the app.用了个人访问令牌,或者你的用户对 App 没有 CAN_USE 权限。Use `databricks auth token`; grant CAN_USE on the app to the users or group.使用 `databricks auth token`;向用户或用户组授予 App 的 CAN_USE 权限。
App starts, then crashes on the first requestApp 启动后,在第一个请求时崩溃A dependency missing from the template's dependency file, or an environment variable not set in the app config.模板的依赖文件里缺少某个依赖,或者 App 配置中没有设置某个环境变量。Read the app logs in the Apps UI. Add packages to the template's dependency file and env entries (valueFrom for resources) to its app config.在 Apps 界面查看 App 日志。把缺的包加入模板的依赖文件,把环境变量(资源用 valueFrom)加入它的 App 配置。
403 on the small-talk route or on every search闲聊路线或每次检索都返回 403The fast model or the embedding endpoint is not an app resource, so the app's principal cannot query it.快速模型或 embedding 端点不是 App 的资源,所以 App 的服务主体无法调用它。Every endpoint the code calls must be listed in app.yml; redeploy after adding it.代码会调用的每一个端点都必须列在 app.yml 中;添加后重新部署。
The app is not listed among workspace agentsApp 没有出现在工作区的智能体列表里The name must start with `agent-`.名字必须以 `agent-` 开头。Rename the app in app.yml and redeploy; bind the existing app if the vendor's bind command applies.在 app.yml 中改名并重新部署;如果适用,用厂商的 bind 命令绑定现有 App。
Done when完成标准The deployed URL answers the lodging question with an OAuth token, and the app's service principal has exactly the grants listed above.已部署的 URL 能在 OAuth 令牌下回答住宿上限问题,App 的服务主体恰好拥有上面列出的那些授权。
Not confirmed on a vendor page未在厂商页面上确认The JSON field names `url` from `apps get` and `access_token` from `auth token -o json` are what the CLI prints today; check once and adjust the one-liners.`apps get` 输出的 `url` 字段和 `auth token -o json` 输出的 `access_token` 字段是 CLI 目前的输出;检查一次,必要时调整这两行命令。
19Seal the questions and evaluate the deployed agent, several times封存问题集,对已部署的智能体多次评估

Why this step, and why here为什么要做这一步,为什么在这里

Without a fixed exam, every improvement is a story. The frozen questions were written by a person before anything learned, and the seal makes sure nothing learns from them. Repetition is the other half: module 11 showed one configuration scoring 5 of 6 on one run and 2 of 6 on another. One run cannot tell a change from noise.没有固定的考题,每一次“改进”都只是一个故事。冻结问题集在任何学习发生之前由人写成,封存保证没有任何东西能从中学习。重复是另一半:第 11 模块展示过,同一配置在一次运行中得 6 分之 5,另一次只得 6 分之 2。只跑一次,无法区分变化和噪声。

What it does它做什么

`build` converts the local frozen_questions.json to MLflow records (inputs, expectations), creates the dataset as a Unity Catalog table, and stores a digest in agentlab.evals.seal. `run` checks the digest, then runs mlflow.genai.evaluate N times against the deployed app with three code scorers, and prints mean and spread per scorer.`build` 把本地的 frozen_questions.json 转成 MLflow 记录(inputs、expectations),以 Unity Catalog 表的形式创建数据集,并把摘要存入 agentlab.evals.seal。`run` 先校验摘要,再针对已部署的 App 用三个代码 scorer 运行 mlflow.genai.evaluate N 次,并打印每个 scorer 的均值和波动范围。

How to do it怎么做

  1. Once, as the eval owner: `python run_eval.py build frozen_questions.json`.以评估负责人身份执行一次:`python run_eval.py build frozen_questions.json`。
  2. Confirm builders have no MODIFY on agentlab.evals (step 2).确认开发者对 agentlab.evals 没有 MODIFY 权限(第 2 步)。
  3. Check that the app returns tools and evidence in custom_outputs (step 17); predict() reads them from there. Create a separate MLflow experiment for eval runs and pass it as --experiment-id.检查 App 是否在 custom_outputs 中返回了 tools 和 evidence(第 17 步);predict() 从那里读取。为评估运行单独建一个 MLflow 实验,并通过 --experiment-id 传入。
  4. `python run_eval.py run --app-url $APP_URL --repeats 5` before and after every change.每次改动前后都运行 `python run_eval.py run --app-url $APP_URL --repeats 5`。

Scripts脚本

src/evals/scorers.py · compiles
"""Step 19. Scorers. The checks are plain functions (tested here); MLflow wraps them at run time.

  must_contain     every required string appears in the answer (the frozen questions, module 11)
  used_tool        the tool the question needs was actually called
  figures_grounded every money figure in the answer is in the evidence (the guard, as a metric)
  seal_digest      a hash of the dataset rows: a changed row means a broken seal, and the run stops
"""
from __future__ import annotations

import hashlib
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from guard.answer_guard import check  # noqa: E402


def must_contain(answer: str, required: list) -> bool:
    low = (answer or "").lower()
    return all(str(r).lower() in low for r in required or [])


def used_tool(tool_names: list, needed: str | None) -> bool:
    return True if not needed else needed in (tool_names or [])


def figures_grounded(answer: str, evidence_texts: list) -> bool:
    msgs = [{"role": "tool", "content": t} for t in evidence_texts or []]
    return check(answer or "", msgs, True)["ok"]


def seal_digest(records: list) -> str:
    """Order-independent digest of the questions and expectations."""
    rows = sorted(json.dumps({"inputs": r["inputs"], "expectations": r.get("expectations", {})}, sort_keys=True)
                  for r in records)
    return hashlib.sha256("\n".join(rows).encode()).hexdigest()


def to_records(frozen: dict) -> list:
    """Local frozen_questions.json -> MLflow evaluation records (inputs + expectations)."""
    out = []
    for item in frozen["items"]:
        out.append({"inputs": {"messages": [{"role": "user", "content": item["q"]}]},
                    "expectations": {"must_contain": item.get("must_contain", []),
                                     "needs_tool": item.get("needs_tool")}})
    return out


def mlflow_scorers() -> list:  # pragma: no cover - needs mlflow
    """The same checks as MLflow code-based scorers. `outputs` is what predict_fn returned."""
    from mlflow.genai.scorers import scorer

    @scorer
    def contains_required(outputs: dict, expectations: dict) -> bool:
        return must_contain(outputs.get("answer", ""), expectations.get("must_contain", []))

    @scorer
    def called_needed_tool(outputs: dict, expectations: dict) -> bool:
        return used_tool(outputs.get("tools", []), expectations.get("needs_tool"))

    @scorer
    def grounded_figures(outputs: dict) -> bool:
        return figures_grounded(outputs.get("answer", ""), outputs.get("evidence", []))

    return [contains_required, called_needed_tool, grounded_figures]
src/evals/run_eval.py · compiles
"""Step 19. Build the sealed dataset once, then evaluate the deployed agent, several times.

  python run_eval.py build  frozen_questions.json   # once: creates <catalog>.evals.frozen_questions + its digest
  python run_eval.py run    --repeats 5              # every change, and nightly

predict_fn calls the DEPLOYED app over HTTP with an OAuth token, so the eval measures what
users get, not a notebook copy of it. The app returns answer, tools and evidence in its
response's custom_outputs (agent.py returns them; the template's handler must pass them on).
If yours does not, read them from the trace instead.
"""
from __future__ import annotations

import argparse
import json
import os
import statistics
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402
from evals.scorers import mlflow_scorers, seal_digest, to_records  # noqa: E402


def dataset_name(cfg: Config) -> str:
    return cfg.table(cfg.eval_schema, "frozen_questions")


def build(cfg: Config, path: str) -> None:  # pragma: no cover
    import mlflow
    from pyspark.sql import SparkSession

    records = to_records(json.load(open(path)))
    ds = mlflow.genai.datasets.create_dataset(uc_table_name=dataset_name(cfg))
    ds.merge_records(records)
    digest = seal_digest(records)
    spark = SparkSession.builder.getOrCreate()
    spark.sql(f"CREATE TABLE IF NOT EXISTS {cfg.table(cfg.eval_schema, 'seal')} (dataset STRING, digest STRING, n INT, sealed_at TIMESTAMP)")
    spark.sql(f"INSERT INTO {cfg.table(cfg.eval_schema, 'seal')} VALUES ('{dataset_name(cfg)}', '{digest}', {len(records)}, current_timestamp())")
    print(f"sealed {len(records)} records, digest {digest[:16]}")
    print("Now restrict MODIFY on the evals schema to the eval owner (01_catalog.sql).")


def verify_seal(cfg: Config, records: list) -> None:  # pragma: no cover
    from pyspark.sql import SparkSession

    spark = SparkSession.builder.getOrCreate()
    row = spark.sql(f"SELECT digest FROM {cfg.table(cfg.eval_schema, 'seal')} WHERE dataset = '{dataset_name(cfg)}' "
                    "ORDER BY sealed_at LIMIT 1").collect()
    if not row or row[0]["digest"] != seal_digest(records):
        raise SystemExit("SEAL BROKEN: the evaluation dataset changed after it was sealed. Refusing to score.")


def predict_fn_for(app_url: str):  # pragma: no cover
    import requests
    from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()

    def predict(messages: list) -> dict:
        token = w.config.authenticate()["Authorization"]          # OAuth; the app rejects personal access tokens
        r = requests.post(f"{app_url.rstrip('/')}/responses", headers={"Authorization": token},
                          json={"input": messages}, timeout=120)
        r.raise_for_status()
        body = r.json()
        text = "".join(c.get("text", "") for item in body.get("output", []) for c in item.get("content", []) or [])
        meta = body.get("custom_outputs") or body.get("metadata") or {}   # where the handler put answer()'s extras
        return {"answer": text, "tools": meta.get("tools", []), "evidence": meta.get("evidence", [])}

    return predict


def run(cfg: Config, app_url: str, repeats: int, experiment_id: str = "") -> None:  # pragma: no cover
    import mlflow

    if experiment_id:
        mlflow.set_experiment(experiment_id=experiment_id)        # a job task has no notebook experiment

    ds = mlflow.genai.datasets.get_dataset(uc_table_name=dataset_name(cfg))
    records = ds.to_df()[["inputs", "expectations"]].to_dict("records")
    verify_seal(cfg, records)
    rates = {}
    for i in range(repeats):
        with mlflow.start_run(run_name=f"frozen-{i + 1}"):
            res = mlflow.genai.evaluate(data=ds, predict_fn=predict_fn_for(app_url), scorers=mlflow_scorers())
        for k, v in res.metrics.items():
            if k.endswith("/mean"):
                rates.setdefault(k, []).append(v)
    for k, vals in sorted(rates.items()):
        print(f"{k:40} mean {statistics.mean(vals):.3f}  spread ({min(vals):.3f}, {max(vals):.3f})  runs {len(vals)}")
    print("Report the spread. A change smaller than the spread is not a change.")


if __name__ == "__main__":  # pragma: no cover
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["build", "run"])
    ap.add_argument("path", nargs="?")
    ap.add_argument("--app-url", default=os.environ.get("AGENT_APP_URL", ""))
    ap.add_argument("--repeats", type=int, default=5)
    ap.add_argument("--experiment-id", default=os.environ.get("AGENT_EVAL_EXPERIMENT_ID", ""))
    a = ap.parse_args()
    c = Config()
    build(c, a.path) if a.cmd == "build" else run(c, a.app_url, a.repeats, a.experiment_id)

How to read the result如何解读结果

  • `contains_required/mean 0.833 spread (0.667, 1.000) runs 5`: the agent answers about five of six right on average, and a single run could have shown anything from four to six. A change that moves the mean from 0.833 to 0.867 is inside that spread, so it is not evidence.`contains_required/mean 0.833 spread (0.667, 1.000) runs 5`:智能体平均答对约六分之五,而单次运行可能显示四到六题中的任何一个。如果某个改动把均值从 0.833 提到 0.867,仍在这个波动范围之内,所以不能算证据。
  • `grounded_figures` below 1.0 on the deployed app means the guard let an unsupported figure through, or was bypassed. Find that question first; it outranks every other score.已部署 App 的 `grounded_figures` 低于 1.0,说明护栏放过了没有依据的数字,或者被绕过了。先找出这道题;它比其他任何分数都更重要。
  • `called_needed_tool` low with `contains_required` high means answers come from the model's memory, right by luck. It will fail on the next policy change.`called_needed_tool` 很低而 `contains_required` 很高,说明答案来自模型的记忆,碰巧答对了。下一次政策变更时它就会出错。
  • `SEAL BROKEN` stops the run. Do not reseal to get past it: find who changed the dataset and why, then create a new versioned set if the change was legitimate.出现 `SEAL BROKEN` 会终止运行。不要为了绕过它而重新封存:查清是谁、为什么改了数据集;如果改动合理,就新建一个带版本号的问题集。

Troubleshooting排障

You see现象Why原因Do this处理
Scorers all fail with missing keys所有 scorer 都因缺少键而失败predict() returns a different shape from what the scorers read (answer, tools, evidence).predict() 返回的结构与 scorer 读取的结构(answer、tools、evidence)不一致。Print one predict() result and align the keys. The vendor page notes scorers must also handle a missing expectations field.打印一次 predict() 的结果,把键对齐。厂商页面提到,scorer 还必须能处理缺少 expectations 字段的情况。
Every run scores 0每次运行都得 0 分The app returned errors (401) that predict() turned into empty answers.App 返回了错误(401),而 predict() 把它们变成了空答案。raise_for_status() is in predict(); if you removed it, put it back. An eval must fail loudly when the target is down.predict() 中有 raise_for_status();如果你删掉了,请加回来。目标不可用时,评估必须明确地报错。
Done when完成标准Five runs of the frozen set against the deployed app, with mean and spread recorded next to the local history.针对已部署 App 跑了五次冻结问题集,均值和波动范围已记录在本地历史数据旁边。
Not confirmed on a vendor page未在厂商页面上确认`mlflow.genai.datasets.get_dataset(uc_table_name=...)`, `to_df()` and the `/mean` metric key suffix are from MLflow 3's evaluation API; the create and merge calls are from the vendor tutorial.`mlflow.genai.datasets.get_dataset(uc_table_name=...)`、`to_df()` 以及指标键的 `/mean` 后缀来自 MLflow 3 的评估 API;create 和 merge 调用来自厂商教程。
20Schedule ingest, edges, evals and the learner as jobs把 ingest、边、评估和学习器排成定时 job

Why this step, and why here为什么要做这一步,为什么在这里

On the Mac, background work competed with the user for one GPU, so a scheduler had to yield. Serverless jobs run on their own compute, so the duty cycle disappears and only two rules remain: order (edges after ingest, learner after eval) and cost. A job file in the bundle is reviewed like code, which a launchd plist rarely was.在 Mac 上,后台任务和用户争用同一块 GPU,所以调度器必须让步。serverless job 在自己的计算资源上运行,占空比因此不复存在,只剩两条规则:顺序(边在 ingest 之后,学习器在评估之后)和成本。bundle 里的 job 文件会像代码一样被审查,而 launchd plist 很少如此。

What it does它做什么

resources/jobs.yml defines three jobs on serverless environments: hourly ingest followed by two dependent tasks (graph edges, and the search refresh for your backend), the nightly eval at 02:30, and the learner at 04:00, created paused.resources/jobs.yml 在 serverless 环境上定义了三个 job:每小时运行的 ingest 及其后的两个依赖任务(图的边,以及针对所选后端的检索刷新),02:30 的夜间评估,以及 04:00 的学习器(创建时处于暂停状态)。

How to do it怎么做

  1. Set the variables (retrieval, experiment_id, eval_experiment_id, app_url, warehouse_id) in the target or with --var.在 target 中或用 --var 设置变量(retrieval、experiment_id、eval_experiment_id、app_url、warehouse_id)。
  2. `databricks bundle deploy -t prod` once dev runs are clean.dev 环境运行无误后,执行 `databricks bundle deploy -t prod`。
  3. Trigger each job once by hand from the Jobs UI and read its output before trusting the schedule.在 Jobs 界面中手动触发每个 job 一次,阅读它的输出,然后再信任定时调度。
  4. Check the refresh_search task's output after each ingest: it is what makes new chunks searchable.每次 ingest 之后检查 refresh_search 任务的输出:正是它让新文本块变得可检索。

Scripts脚本

resources/jobs.yml · yaml parses
# Jobs. Local build (module 15): launchd/systemd timers and a duty-cycle scheduler.
# Here each schedule is a Lakeflow job on serverless compute; the platform supplies the machine,
# so there is no duty cycle to manage, only a cost to watch.
resources:
  jobs:
    ingest:
      name: agent-ingest
      schedule:
        quartz_cron_expression: "0 15 * * * ?"     # hourly at :15
        timezone_id: UTC
        pause_status: UNPAUSED
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies:
              - databricks-openai
              - databricks-sdk
              - databricks-ai-search
              - psycopg[binary,pool]
      tasks:
        - task_key: ingest
          environment_key: default
          spark_python_task:
            python_file: ../src/knowledge/ingest.py
            parameters: ["--catalog", "${var.catalog}", "--backend", "${var.retrieval}"]
        - task_key: edges
          depends_on:
            - task_key: ingest
          environment_key: default
          spark_python_task:
            python_file: ../src/graph/edges.py
            parameters: ["--catalog", "${var.catalog}"]
        - task_key: refresh_search                 # TRIGGERED syncs never run by themselves
          depends_on:
            - task_key: ingest
          environment_key: default
          spark_python_task:
            python_file: ../src/retrieval/refresh.py
            parameters: ["--backend", "${var.retrieval}"]

    nightly_eval:
      name: agent-nightly-eval
      schedule:
        quartz_cron_expression: "0 30 2 * * ?"     # 02:30 every night
        timezone_id: UTC
        pause_status: UNPAUSED
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies:
              - mlflow[databricks]
              - databricks-sdk
              - requests
      tasks:
        - task_key: frozen_questions
          environment_key: default
          spark_python_task:
            python_file: ../src/evals/run_eval.py
            parameters: ["run", "--repeats", "3", "--app-url", "${var.app_url}", "--experiment-id", "${var.eval_experiment_id}"]

    learner:
      name: agent-learner-report
      schedule:
        quartz_cron_expression: "0 0 4 * * ?"      # 04:00, after the eval
        timezone_id: UTC
        pause_status: PAUSED                        # unpause after you have read a week of manual runs
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies:
              - mlflow[databricks]
              - unitycatalog-ai[databricks]
      tasks:
        - task_key: observe
          environment_key: default
          spark_python_task:
            python_file: ../src/learner/nightly.py
            parameters: ["--experiment-id", "${var.experiment_id}", "--catalog", "${var.catalog}"]

How to read the result如何解读结果

  • A green run is not a correct run. Read the ingest task's `changed N` line: an hourly job that always says changed 0 is healthy only if nobody uploaded anything.运行成功(绿色)不等于运行正确。看 ingest 任务的 `changed N` 这一行:一个每小时都显示 changed 0 的 job,只有在确实没人上传文件时才算健康。
  • The eval job's printed spread is the number to put in the morning summary, not only the mean.早上的汇总里应该写评估 job 打印出的波动范围,而不只是均值。
  • A failed edges task with a successful ingest leaves old edges in place, which is safe; the reverse cannot happen because of depends_on.ingest 成功而 edges 任务失败,会保留旧的边,这是安全的;反过来的情况不会发生,因为有 depends_on。

Troubleshooting排障

You see现象Why原因Do this处理
ModuleNotFoundError in a job taskjob 任务中报 ModuleNotFoundErrorA package missing from the environment's dependencies, or src/ not synced.环境依赖中缺少某个包,或者 src/ 没有同步。Add the package under environments.spec.dependencies. The bundle syncs the folder containing databricks.yml, so keep src/ beneath it.把包加到 environments.spec.dependencies 下。bundle 会同步 databricks.yml 所在的目录,所以要把 src/ 放在它下面。
Schedules never fire in dev在 dev 中调度从不触发Development mode pauses schedules.开发模式会暂停调度。Intended. Run by hand in dev, schedule in prod.这是有意为之。在 dev 中手动运行,在 prod 中定时运行。
environment_version rejectedenvironment_version 被拒绝The vendor example shows '2'; newer versions exist and old ones retire.厂商示例里写的是 '2';已有更新的版本,旧版本会被淘汰。Use the current serverless environment version listed in your workspace.使用你工作区中列出的当前 serverless 环境版本。
Done when完成标准Each job has one manual run you have read, and prod schedules are visible in the Jobs UI with the learner paused.每个 job 都有一次你读过输出的手动运行,prod 的调度在 Jobs 界面中可见,学习器处于暂停状态。

7 Learn and operate学习与运维

The learning loop and the status screen come last because they read what everything else writes. They carry over with the same discipline as on the Mac: observe in report mode, prove before proposing, and let a person apply a change as a commit.学习循环和状态面板放在最后,因为它们读取的是其他所有部分写下的东西。它们沿用与 Mac 上相同的纪律:以报告模式观察,先证明再提议,由人把改动以提交的形式应用。

21Self-observation over traces, in report mode基于追踪的自我观察,采用报告模式

Why this step, and why here为什么要做这一步,为什么在这里

The failures that matter return success codes: a tool that returned nothing and an agent that reported zero. The learner finds them mechanically and proves each one by re-running the call with one filter removed. It writes findings and changes nothing, because module 13 showed what an unsupervised learner does to its own eval.真正要紧的失败返回的都是成功状态码:工具什么也没返回,智能体就报告了零。学习器以机械的方式找出它们,并通过去掉一个过滤条件重新调用来证明每一条。它只写下发现,不做任何改动,因为第 13 模块已经展示过无人监督的学习器会对它自己的评估做什么。

What it does它做什么

Reads MLflow traces newer than the cursor, inspects tool spans for query_expenses, re-runs empty calls with one optional argument dropped (never the employee id), counts turn-budget exhaustion, appends findings to agentlab.ops.findings, and only then moves the cursor.读取比游标更新的 MLflow 追踪,检查 query_expenses 的工具 span,对空结果的调用去掉一个可选参数(绝不去掉员工 id)后重跑,统计轮次预算耗尽的次数,把发现追加到 agentlab.ops.findings,然后才移动游标。

How to do it怎么做

  1. Run the learner job by hand for a week while it is paused on schedule.在定时调度保持暂停期间,手动运行学习器 job 一周。
  2. Each morning read the findings query from step 22.每天早上查看第 22 步中的 findings 查询。
  3. For each finding, open a pull request that fixes the tool, the prompt or a skill; run step 19 on the branch.对每条发现,提交一个修正工具、提示词或技能的 pull request;在该分支上运行第 19 步。
  4. Unpause the schedule only when the findings have been useful for a week.只有当这些发现连续一周都有用时,才取消调度暂停。

Scripts脚本

src/learner/nightly.py · compiles
"""Step 21. The self-observation job, in report mode. Runs nightly as a Lakeflow job.

Local build (module 13): self_observe.py reads new log lines past a cursor, finds failures that
return success codes, proves them by re-running, and writes a report. Nothing changes itself.
Here the log is the MLflow traces of the deployed agent, and the cursor is a row in a Delta table.

  python nightly.py --experiment-id <id> [--catalog agentlab]
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.config import Config  # noqa: E402


KEEP = {"query_expenses": {"employee_id"}}      # identity arguments: never relaxed, or every finding is noise


def findings_from_tool_call(name: str, args, output: str, rerun) -> list:
    """Pure rule, tested here. An empty result that has rows once one filter is dropped is a
    parameter problem, provable by the re-run. rerun(name, args) -> output string.
    Only arguments with a default in the tool can be dropped; identity arguments are kept."""
    if isinstance(args, str):                    # span inputs may arrive as a JSON string
        try:
            args = json.loads(args)
        except ValueError:
            return []
    if not isinstance(args, dict):
        return []
    try:
        out = json.loads(output)
    except (TypeError, ValueError):
        return []
    if out.get("count") or out.get("results"):
        return []
    for drop in [a for a in args if a not in KEEP.get(name, set())]:
        relaxed = {k: v for k, v in args.items() if k != drop}
        if not relaxed:
            continue
        try:
            again = json.loads(rerun(name, relaxed))
        except Exception:                                   # noqa: BLE001 - a failed re-run proves nothing
            continue
        n = again.get("count") or len(again.get("results", []))
        if n:
            return [{"signal": "recoverable_empty", "key": f"{name}.relax_{drop}",
                     "proof": f"{args} -> 0 rows; without {drop} -> {n} rows"}]
    return []


def main(argv: list) -> None:  # pragma: no cover
    import mlflow
    from mlflow.entities import SpanType
    from pyspark.sql import SparkSession

    ap = argparse.ArgumentParser()
    ap.add_argument("--experiment-id", required=True)
    ap.add_argument("--catalog", default=None)
    a = ap.parse_args(argv)
    if a.catalog:
        os.environ["AGENT_CATALOG"] = a.catalog
    cfg = Config()
    spark = SparkSession.builder.getOrCreate()
    cur_t = cfg.table(cfg.ops_schema, "cursors")
    spark.sql(f"CREATE TABLE IF NOT EXISTS {cur_t} (name STRING, value BIGINT)")
    row = spark.sql(f"SELECT max(value) v FROM {cur_t} WHERE name = 'observe:traces'").collect()
    since = int(row[0]["v"] or 0)

    traces = mlflow.search_traces(experiment_ids=[a.experiment_id], filter_string=f"timestamp_ms > {since}",
                                  return_type="list", max_results=5000)
    from unitycatalog.ai.core.databricks import DatabricksFunctionClient
    uc = DatabricksFunctionClient()

    def rerun(name, args):
        return str(getattr(uc.execute_function(f"{cfg.catalog}.tools.{name}", args), "value", ""))

    findings, newest, budget_hits = [], since, 0
    for tr in traces:
        newest = max(newest, int(tr.info.timestamp_ms))
        for span in tr.search_spans(span_type=SpanType.TOOL):
            name = span.name.split(".")[-1]
            if name != "query_expenses":
                continue                                   # only re-run tools that are safe to re-run
            findings += findings_from_tool_call(name, span.inputs or {}, str(span.outputs or ""), rerun)
        if "max_turns" in str(getattr(tr.info, "state", "")) or "MaxTurnsExceeded" in str(tr.data.response or ""):
            budget_hits += 1
    day = time.strftime("%Y-%m-%d")
    rows = [(day, f["signal"], f["key"], f["proof"]) for f in findings]
    if budget_hits:
        rows.append((day, "budget_exhaustion", "rounds", f"{budget_hits} traces hit the turn budget"))
    if rows:
        spark.createDataFrame(rows, "day string, signal string, key string, proof string") \
            .selectExpr("*", "current_timestamp() AS created_at").write.mode("append").saveAsTable(cfg.table(cfg.ops_schema, "findings"))
    # Move the cursor only after the findings are written: a crash re-reads, it never skips.
    spark.sql(f"INSERT INTO {cur_t} VALUES ('observe:traces', {newest})")
    print(f"traces read {len(traces)}, findings {len(rows)}, cursor {since} -> {newest}")
    print("REPORT MODE: nothing was changed. A person reads agentlab.ops.findings and opens a pull request.")


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])

How to read the result如何解读结果

  • `recoverable_empty query_expenses.relax_claim_month` with proof `... -> 0 rows; without claim_month -> 12 rows` means users ask for months that have no data and the agent reports nothing instead of saying which months exist. The fix belongs in the tool's diagnostic or the skill, not in the model.`recoverable_empty query_expenses.relax_claim_month`,证据为 `... -> 0 rows; without claim_month -> 12 rows`,意味着用户问的月份没有数据,而智能体什么也没说,也没指出哪些月份有数据。修正应该放在工具的诊断信息或技能里,而不是模型里。
  • `budget_exhaustion` counts that rise after a deploy point at a prompt or tool change that made the model loop.部署后 `budget_exhaustion` 数量上升,指向某次提示词或工具改动让模型陷入了循环。
  • `cursor 1730000000000 -> 1730086400000` moving forward each night is the job's heartbeat. A cursor that stops moving with traces still arriving means the job fails before the last line.游标每晚向前推进(例如 `cursor 1730000000000 -> 1730086400000`)是这个 job 的心跳。如果追踪还在持续产生而游标不再移动,说明 job 在最后一行之前就失败了。

Troubleshooting排障

You see现象Why原因Do this处理
No traces found找不到任何追踪Wrong experiment id, or the app logs traces to a different experiment.实验 id 不对,或者 App 把追踪记录到了另一个实验。Use the experiment the app resource points to (app.yml).使用 App 资源所指向的那个实验(app.yml)。
Findings repeat every night for the same calls同样的调用每晚都重复出现在发现里The cursor was not saved, so old traces are re-read.游标没有保存,所以旧的追踪被重复读取。Check the cursors table has a new row per run; the INSERT must come after findings are written.检查游标表每次运行都有一行新记录;INSERT 必须在写入发现之后执行。
Done when完成标准A week of findings, each with a proof line, and at least one acted on through a reviewed pull request with an eval run.积累了一周的发现,每条都带有证据行,并且至少有一条已通过经过审查、附带评估运行的 pull request 得到处理。
Not confirmed on a vendor page未在厂商页面上确认`mlflow.search_traces(..., return_type="list")`, `Trace.search_spans(span_type=SpanType.TOOL)` and the filter string on timestamp_ms are MLflow 3 tracing APIs; how the template names tool spans was not checked, so the script matches on the last dotted segment of the span name.`mlflow.search_traces(..., return_type="list")`、`Trace.search_spans(span_type=SpanType.TOOL)` 以及基于 timestamp_ms 的过滤字符串都是 MLflow 3 的追踪 API;模板如何命名工具 span 未经核实,所以脚本按 span 名称中最后一个点号之后的部分来匹配。
22One-screen status and cost一屏状态与成本

Why this step, and why here为什么要做这一步,为什么在这里

On the Mac, cost was electricity and the risk was a full disk. On Databricks cost is per token, per DBU and per app hour, and it grows quietly. The status screen answers four questions every morning: did the jobs run, is the knowledge fresh, is anything failing silently, and what did yesterday cost.在 Mac 上,成本是电费,风险是磁盘写满。在 Databricks 上,成本按 token、按 DBU、按 App 运行小时计算,而且会悄悄增长。状态面板每天早上回答四个问题:job 跑了吗?知识是新鲜的吗?有没有什么在悄悄失败?昨天花了多少钱?

What it does它做什么

Five queries: spend by product from system.billing.usage, knowledge freshness from the ledger, chunks in service per collection, findings per night, and recent job runs from the Lakeflow system tables.五条查询:来自 system.billing.usage 的按产品花费、来自台账的知识新鲜度、每个集合在服务中的文本块数、每晚的发现数,以及来自 Lakeflow 系统表的近期 job 运行情况。

How to do it怎么做

  1. Run each query once and adjust names: billing product values and system.lakeflow table names vary by account.每条查询运行一次并调整名称:计费产品的取值和 system.lakeflow 的表名因账号而异。
  2. Save them on one dashboard; add SQL alerts on queries 3, 4 and 5.把它们保存在同一个仪表盘上;为第 3、4、5 条查询添加 SQL 告警。
  3. Set a budget alert at the account level for model serving.在账号层面为模型服务设置预算告警。
  4. Backups: Delta keeps history (time travel) for the tables; Lakebase branches give point-in-time copies. Test a restore once, as module 15 requires.备份:Delta 为表保留历史(time travel);Lakebase 的分支提供时间点副本。像第 15 模块要求的那样,做一次恢复测试。

Scripts脚本

src/ops/monitor.sql · read only
-- Step 22. The one-screen status, as SQL. Save these as queries on a dashboard; alert on the last three.
-- Local build (module 15): Check-All-LLM-Status prints every service and model on one screen.

-- 1. Spend by product, last 14 days. system.billing.usage is the account-wide billing system table.
SELECT usage_date, billing_origin_product, sku_name, round(sum(usage_quantity), 2) AS dbus
FROM system.billing.usage
WHERE usage_date >= current_date() - INTERVAL 14 DAYS
  AND billing_origin_product IN ('MODEL_SERVING', 'VECTOR_SEARCH', 'APPS', 'JOBS', 'DATABASE', 'SQL')
GROUP BY ALL
ORDER BY usage_date DESC, dbus DESC;
-- Product names in this column change as products are renamed. Run
--   SELECT DISTINCT billing_origin_product FROM system.billing.usage
-- once and adjust the IN list to what your account reports.

-- 2. Knowledge freshness: how old is the newest accepted document, and how many were rejected this week?
SELECT max(updated_at) AS newest_document,
       count_if(status = 'rejected' AND updated_at >= current_timestamp() - INTERVAL 7 DAYS) AS rejected_7d,
       count_if(status = 'accepted') AS accepted_total
FROM agentlab.kb.ledger;

-- 3. Chunks in service versus retired. A sudden drop in service means an ingest retired too much.
SELECT collection, count_if(NOT retired) AS in_service, count_if(retired) AS retired
FROM agentlab.kb.chunks GROUP BY collection ORDER BY collection;

-- 4. Self-observation findings per night. A rising line is the first sign of a broken tool or prompt.
SELECT day, signal, count(*) AS n FROM agentlab.ops.findings
WHERE day >= date_format(current_date() - INTERVAL 14 DAYS, 'yyyy-MM-dd')
GROUP BY ALL ORDER BY day DESC, n DESC;

-- 5. Did last night's jobs run? Lakeflow job runs live in the system.lakeflow schema (check the table
--    names your account exposes with SHOW TABLES IN system.lakeflow).
SELECT job_id, result_state, period_start_time, period_end_time
FROM system.lakeflow.job_run_timeline
WHERE period_start_time >= current_timestamp() - INTERVAL 2 DAYS
ORDER BY period_start_time DESC;
sql
-- restore test for the chunk table: read yesterday's version, compare counts
SELECT count(*) FROM agentlab.kb.chunks TIMESTAMP AS OF date_sub(current_date(), 1);
DESCRIBE HISTORY agentlab.kb.chunks LIMIT 5;

How to read the result如何解读结果

  • Spend that grows while query count is flat means tokens per request grew: a longer prompt, more retrieved text, or more tool rounds. Check the agent's prompt size before anything else.如果花费在增长而请求数持平,说明每个请求的 token 数增加了:提示词变长、检索的文本变多,或者工具轮次变多。先检查智能体的提示词大小。
  • `in_service` dropping sharply for one collection after an ingest run is the retire step removing more than it should, usually a renamed folder. Restore with time travel, then fix the paths.某次 ingest 后某个集合的 `in_service` 急剧下降,说明停用步骤移除得太多了,通常是因为目录改了名。用 time travel 恢复,然后修正路径。
  • No row for last night in the job query means it did not run at all; a FAILED row means it ran and stopped. They have different fixes: schedule and permissions versus code.job 查询里没有昨晚的记录,说明它根本没跑;有一条 FAILED 记录,说明它跑了但中途停止了。两者的修法不同:前者是调度和权限问题,后者是代码问题。

Troubleshooting排障

You see现象Why原因Do this处理
PERMISSION_DENIED on system tables访问系统表时报 PERMISSION_DENIEDSystem schemas must be enabled and granted by an account admin.系统 schema 需要账号管理员启用并授权。Ask for SELECT on system.billing and system.lakeflow for the dashboard's owner.为仪表盘所有者申请 system.billing 和 system.lakeflow 的 SELECT 权限。
Query 1 returns nothing第 1 条查询没有返回任何结果The product names in the IN list do not match your account's values.IN 列表中的产品名与你账号中的取值不匹配。Run the DISTINCT query in the file comment and replace the list.运行文件注释中的 DISTINCT 查询,替换这个列表。
Done when完成标准One dashboard answers the four morning questions, alerts exist on the last three queries, and one restore has been tested.一个仪表盘能回答早上的四个问题,后三条查询都配置了告警,并且做过一次恢复测试。
Not confirmed on a vendor page未在厂商页面上确认system.lakeflow.job_run_timeline and the billing_origin_product values are written from general knowledge of the system tables, not from a page read for this guide.system.lakeflow.job_run_timeline 以及 billing_origin_product 的取值来自对系统表的一般了解,并非出自本指南参考的页面。
23Decide where the public tutor lives决定公开教程站放在哪里
Replaces替代This site and the datamatter site on Vercel, calling the Mac through the funnel with a local-first chain.本站和 Vercel 上的 datamatter 站点,通过 funnel 以“本地优先”的链路调用 Mac。

Why this step, and why here为什么要做这一步,为什么在这里

A Databricks App requires a workspace sign-in. That is right for the agent, which reads company data, and wrong for a public tutor that anyone may use. So the public front end stays outside, and it reaches models through the gateway with its own service principal, its own rate limit, and no access to any data.Databricks App 需要登录工作区。这对读取公司数据的智能体来说是对的,但对任何人都可以使用的公开教程站来说就不对了。所以公开前端留在外部,它通过网关访问模型,使用自己的服务主体和自己的限流,不能访问任何数据。

What it does它做什么

Keeps the site on Vercel and adds Databricks as one more link in the tutor's chain, using machine-to-machine OAuth: the function exchanges a client ID and secret for a token valid for an hour and calls the gateway's OpenAI-compatible endpoint.把站点留在 Vercel 上,并把 Databricks 作为教程站链路中的又一个环节,使用机器对机器 OAuth:函数用 client ID 和 secret 换取一个有效期一小时的令牌,再调用网关的 OpenAI 兼容端点。

How to do it怎么做

  1. Create a service principal `tutor-public` with CAN_QUERY on one fast model endpoint only, and a strict gateway rate limit.创建一个服务主体 `tutor-public`,只给它一个快速模型端点的 CAN_QUERY 权限,并设置严格的网关限流。
  2. Store its client ID and secret as Vercel environment variables (never in the repo).把它的 client ID 和 secret 存为 Vercel 的环境变量(绝不放进仓库)。
  3. In api/tutor.py, mint a token with the snippet below, cache it for 50 minutes, and call the chat endpoint with it.在 api/tutor.py 中用下面的代码片段生成令牌,缓存 50 分钟,再用它调用对话端点。

Scripts脚本

api/tutor.py (addition)
import base64, json, os, time, urllib.request

_tok = {"v": None, "exp": 0}
def databricks_token():
    if _tok["v"] and time.time() < _tok["exp"]:
        return _tok["v"]
    host = os.environ["DATABRICKS_HOST"].rstrip("/")
    cred = base64.b64encode(f'{os.environ["DATABRICKS_CLIENT_ID"]}:{os.environ["DATABRICKS_CLIENT_SECRET"]}'.encode()).decode()
    req = urllib.request.Request(f"{host}/oidc/v1/token", data=b"grant_type=client_credentials&scope=all-apis",
                                 headers={"Authorization": f"Basic {cred}", "Content-Type": "application/x-www-form-urlencoded"})
    body = json.load(urllib.request.urlopen(req, timeout=10))
    _tok.update(v=body["access_token"], exp=time.time() + min(body.get("expires_in", 3600), 3000))
    return _tok["v"]

# then, as one more link in links():  base = f"{host}/serving-endpoints", key = databricks_token(),
# model = "databricks-qwen3-next-80b-a3b-instruct"

How to read the result如何解读结果

  • The tutor's answer footer will read `answered by cloud · databricks-...` when this link answers. If it never does, the earlier links answered first, which is the intended order.当这个环节作答时,教程站回答底部会显示 `answered by cloud · databricks-...`。如果从来不显示,说明前面的环节先作答了,这正是预期的顺序。
  • A 401 after about an hour means the token was cached longer than it lives. The snippet caps the cache at 50 minutes.大约一小时后出现 401,说明令牌缓存的时间超过了它的有效期。代码片段把缓存上限设为 50 分钟。

Troubleshooting排障

You see现象Why原因Do this处理
400 invalid_client from the token endpoint令牌端点返回 400 invalid_clientWrong client secret, or the secret belongs to another workspace's principal.client secret 错了,或者这个 secret 属于另一个工作区的服务主体。Generate a new OAuth secret for the principal and update both Vercel variables.为该服务主体生成新的 OAuth secret,并更新两个 Vercel 变量。
403 when calling the model调用模型时返回 403The principal lacks CAN_QUERY on that endpoint.该服务主体对那个端点没有 CAN_QUERY 权限。Grant it on that one endpoint, nothing more.只授予它对那一个端点的权限,不要更多。
Done when完成标准The public tutor answers through the Databricks link when the local links are down, and the principal can reach nothing except that one endpoint.本地环节不可用时,公开教程站能通过 Databricks 环节作答,并且该服务主体除了那一个端点之外什么都访问不到。
Not confirmed on a vendor page未在厂商页面上确认The `/oidc/v1/token` client-credentials flow and the `/serving-endpoints` OpenAI base path are the platform's documented M2M and serving patterns, but neither page was read for this guide; the vendor's query page also shows an `/ai-gateway/mlflow/v1` base URL for gateway access.`/oidc/v1/token` 的 client-credentials 流程和 `/serving-endpoints` 这个 OpenAI 基础路径是平台文档中的 M2M 和模型服务用法,但本指南没有参考这两个页面;厂商的查询页面还给出了一个用于网关访问的 `/ai-gateway/mlflow/v1` 基础 URL。

Playbook: running it on Databricks操作手册:在 Databricks 上运行它

Every morning (10 minutes)每天早上(10 分钟)

Before anyone relies on the agent that day.在当天有人依赖这个智能体之前。

  1. Open the status dashboard. Did ingest, eval and learner each run last night? (query 5)打开状态仪表盘。昨晚 ingest、评估和学习器是否都跑了?(第 5 条查询)
  2. Read the eval job's output: mean and spread per scorer. grounded_figures must be 1.0.查看评估 job 的输出:每个 scorer 的均值和波动范围。grounded_figures 必须是 1.0。
  3. Read new findings (query 4). Each one is a proof line; open a ticket for any new key.查看新的发现(第 4 条查询)。每一条都是一行证据;对任何新出现的键开一个工单。
  4. Check yesterday's spend against the budget (query 1). A jump with flat traffic means larger prompts or more rounds.对照预算检查昨天的花费(第 1 条查询)。流量持平而花费跳升,说明提示词变大了或轮次变多了。

Every change (prompt, skill, tool, model, ranking)每次改动(提示词、技能、工具、模型、排序)

Before anything reaches production users.在任何东西到达生产用户之前。

  1. Branch. Run `python replicate/databricks/check.py`: portable tests must pass.开分支。运行 `python replicate/databricks/check.py`:可移植测试必须全部通过。
  2. `databricks bundle deploy -t dev`, then the frozen eval with --repeats 5 against the dev app.执行 `databricks bundle deploy -t dev`,然后针对 dev App 用 --repeats 5 跑冻结评估。
  3. Compare with the last production run. Keep the change only if it beats the spread, or is neutral and fixes a finding.与最近一次生产运行对比。只有当改动超出波动范围,或者效果持平但修复了某条发现时,才保留这个改动。
  4. For prompts: register a new version and move @production. For code: merge and `bundle deploy -t prod`.提示词:注册新版本并移动 @production。代码:合并后执行 `bundle deploy -t prod`。
  5. Write one line in the change log: what, why, the eval numbers before and after.在变更日志里写一行:改了什么、为什么改、改动前后的评估数据。

Every week每周

A fixed slot, so it happens.固定一个时间段,确保它会发生。

  1. Read the week's findings as a whole: what keeps recurring is a design problem, not a bug.把一周的发现放在一起看:反复出现的是设计问题,而不是 bug。
  2. Review rejected files in the ledger and fix the sources.检查台账中被拒绝的文件,修正源文件。
  3. Run the retrieval parity script (step 13) to catch drift from new documents.运行检索一致性脚本(第 13 步),发现新文档带来的漂移。
  4. Run bench.py at a busy hour; if first-token time grew, reconsider the lineup.在繁忙时段运行 bench.py;如果首 token 时间变长了,重新考虑模型阵容。
  5. Once a month: restore yesterday's chunk table into a scratch table and compare counts.每月一次:把昨天的文本块表恢复到一张临时表中,比较行数。

When something breaks出问题时

You see现象First check先检查Do this处理
Answers suddenly wrong, no errors anywhere答案突然出错,到处都没有报错Ledger query 2 and chunks query 3: did an ingest retire a collection? Then the prompt alias history.台账查询(第 2 条)和文本块查询(第 3 条):是不是某次 ingest 停用了一整个集合?然后查看提示词别名的历史。Time-travel the chunk table back, or move the prompt alias back. Then find the cause.用 time travel 把文本块表恢复回去,或者把提示词别名移回去。然后再查原因。
Users get 429用户收到 429Gateway usage for the endpoint: per-user limit or endpoint limit?查看该端点的网关用量:是每用户限流还是端点限流?Raise the per-user limit, route chat turns to the fast model, or move to provisioned throughput.调高每用户限额、把闲聊轮次路由到快速模型,或者改用预置吞吐量。
App returns 401 for everyone所有人访问 App 都返回 401Was the app redeployed or renamed? Are clients sending OAuth tokens?App 是否被重新部署或改名了?客户端发送的是 OAuth 令牌吗?Restore CAN_USE grants; personal access tokens are not accepted.恢复 CAN_USE 授权;个人访问令牌不被接受。
New documents never show up in answers新文档从不出现在答案里Ingest printed changed N? Did refresh_search run after it and print COMPLETED?ingest 是否打印了 changed N?之后 refresh_search 是否运行并打印了 COMPLETED?Rerun refresh_search; TRIGGERED pipelines and indexes never update on their own.重跑 refresh_search;TRIGGERED 模式的管道和索引不会自行更新。
Eval job stops with SEAL BROKEN评估 job 因 SEAL BROKEN 而终止DESCRIBE HISTORY on the dataset table: who wrote, when.对数据集表执行 DESCRIBE HISTORY:谁写入的、什么时候。Revoke that write path. Never reseal to continue; version a new set if the change was legitimate.撤销那条写入途径。绝不为了继续而重新封存;如果改动合理,就新建一个带版本号的问题集。
Memory or Lakebase retrieval fails after about an hour记忆或 Lakebase 检索大约一小时后失败Is any code holding a connection longer than 60 minutes?是否有代码持有连接超过 60 分钟?Use common/pg.py's pool (fresh credential per connection, 45-minute recycle).使用 common/pg.py 中的连接池(每个连接都用新凭证,45 分钟回收)。
Spend doubled overnight花费一夜之间翻倍Billing query by product, then tokens per request in the inference table.按产品查询计费,再查看推理表中每个请求的 token 数。Usually a loop (budget_exhaustion findings), a prompt that grew, or a job that runs far more often than intended.通常是陷入循环(会有 budget_exhaustion 发现)、提示词变大了,或者某个 job 运行得远比预期频繁。

Cost levers成本杠杆

  • Triage first: greetings and chit-chat go to the fast model with no tools. On the local build this removed most model calls from small talk.先分流:问候和闲聊交给不带工具的快速模型。在本地构建中,这样做去掉了闲聊中的大部分模型调用。
  • Keep the briefing and the skill text short; they are paid for on every turn.让用户简报和技能文本保持简短;每一轮都要为它们付费。
  • Retrieve 5 passages, not 20. Candidates are cheap; text in the prompt is not.检索 5 段,而不是 20 段。候选很便宜,放进提示词的文本却不便宜。
  • Hourly ingest that finds nothing changed costs one listing and one hash pass; keep it hourly only if documents really change that often.每小时运行一次、却没发现任何变化的 ingest,代价是一次列目录和一轮哈希计算;只有文档真的变得这么频繁,才保持每小时一次。
  • Evals with --repeats 5 cost five times one run. Use 3 nightly and 5 for decisions.--repeats 5 的评估花费是单次运行的五倍。夜间用 3 次,做决定时用 5 次。
  • Stop dev apps you are not using; apps bill per hour of provisioned compute.停掉不用的 dev App;App 按预置计算资源的运行小时计费。

What does not carry over哪些无法沿用

  • Local-first privacy does not carry over. On the Mac nothing left the machine; here documents, prompts and answers live in the workspace's cloud account. Decide what may move before step 6, not after.“本地优先”的隐私保障无法沿用。在 Mac 上没有任何东西离开本机;而在这里,文档、提示词和答案都存放在工作区所在的云账号中。在第 6 步之前就决定哪些可以迁移,而不是之后。
  • Serving knobs disappear: context length, keep-alive, parallelism and quantization were yours to set in ollama-env.sh. Hosted endpoints decide them. If an answer depended on a long context, test it again.服务参数不复存在:上下文长度、keep-alive、并发数和量化方式原本由你在 ollama-env.sh 中设置。托管端点会自己决定这些。如果某个答案依赖长上下文,请重新测试。
  • Exact local models may not exist. qwen3.8:27b and qwen3.6:35b-a3b are stood in for by the nearest hosted Qwen endpoints; answers will differ. That is why step 19 compares against local history rather than assuming parity.确切的本地模型可能并不存在。qwen3.8:27b 和 qwen3.6:35b-a3b 由最接近的托管 Qwen 端点替代;答案会有差异。这就是为什么第 19 步要与本地历史数据对比,而不是假定两者一致。
  • The coding-client translation proxy (claude-code-gateway) has no counterpart here, and needs none: coding agents can call the workspace's endpoints directly.编程客户端的协议转换代理(claude-code-gateway)在这里没有对应物,也不需要:编程智能体可以直接调用工作区的端点。
  • A public, sign-in-free page cannot be a Databricks App. The public tutor stays on Vercel (step 23).无需登录的公开页面不能做成 Databricks App。公开教程站留在 Vercel 上(第 23 步)。
  • Agent Bricks can build some of this (a knowledge assistant, a supervisor) without code. It was not used here, because it replaces the parts this curriculum teaches you to own; evaluate it against the same frozen set if you try it.Agent Bricks 可以无需代码地构建其中一部分(知识助手、主管智能体)。这里没有使用它,因为它替代的正是本课程教你自己掌握的那些部分;如果你要尝试,请用同一套冻结问题集来评估它。

Sources来源

Platforms各平台: Databricks · Harness engineeringHarness 工程