AI 翻译。由人工以英文核验。 阅读原文

基于智能体的商业智能

教学套件

来自版次 2026.11.19,即本书当前版次。本书变更时,此版次随之变更。可自由使用和改编,但须注明出处。

教学大纲

阅读时长仅针对本章正文。学生还可在实验环境或自己的机器上运行其中的示例。

每周一章:11周

5 周后

学习目标与大纲

每章的学习目标即其第一句。每份大纲依循该章的节,列出该章定义的术语、运行示例前要求做出的预测,以及每节结尾的规则。 其关键术语和待提问的预测内容采用英文版次,与测验题库的设置一致。

1. 端到端的数据智能体

阅读约 68 分钟,6个示例。

读完本章,你可以构建商店的数据仓库,让一个已录制的模型针对业务问题编写 SQL,运行这段 SQL 并发现它返回的错误数字,用一个已定义的指标回答同一个问题,并在五个黄金问题上给两种做法打分。

讲义大纲:8节
  1. 认识这家商店及其数据仓库
    • 运行 load-the-warehouse.py
    • 工作准则 请针对一个包含你真实陷阱的数据仓库来构建智能体:测试行、已取消订单、多种货币、当地营业日、财年日历,以及至少一张名字很有诱惑力的遗留表。无法共享生产数据时,可以用随机种子生成数据,使任何人都能重新构建。过于干净的演示模式,恰恰会掩盖你需要看到的那些失误。
  2. 提出问题,由模型生成 SQL
    • 运行 first-question-to-sql.py
    • 工作准则 把仅依据表结构的文本到 SQL 当作需要超越的基线,而不是最终产品。在你自己的数据仓库上运行一次,并保留它的回复,因为这能让你看到表结构没有承载你的哪些定义。把测试所依赖的每一条模型回复都录制下来,并固定到某个模型文件、某个提示词哈希和固定的采样设置上,这样你发现的失败就能被他人复现。
  3. Run the SQL and check the number
    • 运行 run-the-model-sql.py
    • 工作准则 Never accept an agent's number because its SQL looks right. Check it against a golden result before anyone relies on it, and when the two differ, find the rows that explain the difference before you change anything. Expect the difference to be a definition, such as which orders count, more often than a syntax mistake.
  4. Answer from one defined metric
    • 运行 one-metric-answer.py
    • 工作准则 Route a question to a defined metric before you let a model write SQL. Give the model the metric's description and its dimensions, and let it return a request, which your code validates and compiles. Write SQL from a model only for questions no metric covers, and only behind guards.
  5. Score both on five golden questions
    • 运行 score-five-golden.py
    • 工作准则 Score every change on golden questions written from your own work, and report correct, wrong, error and declined separately. Include questions that should be declined from the start, or an agent that never declines will look perfect. Use a handful of questions as a smoke test while you build, and a larger set with a held-out split before you claim anything.
  6. 阅读一次运行的轨迹
    • 运行 print-one-trace.py
    • 工作准则 不要只看分数,也要阅读轨迹,并且先阅读拒答的部分。检查每次拒答的理由说的是否是智能体所获得的内容,例如“没有任何指标统计客户数”,而不是对它从未见过的数据下断言。拒答的理由为假时,即使评分把它算作已拒答,也应将其视为缺陷。
  7. What goes wrong in production
    • 工作准则 Before anyone outside your team uses the agent, make every failure above visible: score on golden questions in CI, show provenance and data freshness with each answer, review declines in traces, replay recorded replies by message hash, and run model-written SQL only on a read-only connection. Start with golden scoring, because it is the only one of these checks that catches a plausible wrong number.
  8. 本章做出的决定

2. 原始文本到 SQL 在哪里算错数字

阅读约 71 分钟,7个示例。

读完本章,你将能够说出在真实数据仓库上,仅依据表结构的文本到 SQL 会返回看似合理却错误的数字的五种情形,在商店的数据仓库上逐一演示,在一组黄金问题中统计它们,并判断哪些可以靠更好的提示词修复,哪些需要表结构中没有的定义。

讲义大纲:8节
  1. Joins that fan out and inflate a sum
    • 运行 tent-orders-fan-out.py
    • 运行 figure-lines-per-order.py
    • 工作准则 When a query joins tables of different grains, check the grain of every column it sums. Aggregate the finer table to the coarser grain before joining, or filter with IN or EXISTS, and compare the row count after the join with the count of distinct keys. Expect a model given only the schema to miss this, because the schema names columns, not grains.
  2. 数据库模式中没有的定义
    • 运行 gross-or-net-revenue.py
    • 工作准则 把问题中的每个业务词都当作需要查证的定义,而不是需要匹配的列。写明每项定义由谁负责,并把定义本身交给智能体,形式可以是受治理的指标,至少也应是术语表条目,切不可只给出可用来计算它的那些列。如果某个词没有书面定义,就让智能体提问或拒绝回答,而不是自行选择。
  3. 时区与财年日历
    • 运行 fiscal-year-and-local-day.py
    • 工作准则 不要只把列告诉代理,还要把你的日历告诉它:哪个时间戳是 UTC,哪个日期是营业日,财年从何时开始,又如何命名。要在边界处测试每一个涉及时期的问题,例如某月的第一天或某财年的第一个月,因为在这些地方 UTC 日与本地日、日历年与财年会不一致。优先使用代理可以联接的日期维度表,而不是由它自己编写的日期运算。
  4. The table with the tempting name
    • 运行 legacy-table-answer.py
    • 工作准则 List the tables an agent may read, and leave legacy and staging tables off the list even when they have the friendliest names. Check every model-written query's tables against the list before it runs. When an agent never chooses a tempting table in your tests, keep the check anyway: a new question, a larger schema or a retrieved example can change that.
  5. Filters nobody wrote down
    • 运行 cancelled-lines-counted.py
    • 工作准则 Move every rule about which rows count into the marts where you can, so no query can forget it. Where a mart has to keep the rows, as with cancelled orders, write the rule into the definition the agent uses, and add a golden question that fails when the rule is left out. Read the gold for the same rules, because the person who wrote it can miss them as readily as the model can.
  6. Count the failures by kind
    • 运行 classify-schema-only-errors.py
    • 工作准则 Count failures by kind on your own golden questions before you choose a fix, and keep errors that fail loudly apart from wrong numbers that don't. Label kinds by comparing each query with its golden SQL, with rules you can read, and read the wrong answers no rule labels. Fix the most common kind of wrong number first, and expect it to be a definition, a calendar or a filter more often than a syntax mistake.
  7. 生产环境中会出什么问题
    • 工作准则 在智能体给出的数字送到任何人手中之前,用黄金结果为每个答案评分,在周期边界处以及针对每个定义保留黄金问题,列出智能体可以读取的表,并人工阅读一批错误答案。按类型统计错误数字,任何一类的计数上升都应视为警报。
  8. 本章的决定

3. 从你自己的工作中构建黄金问题

阅读约 66 分钟,9个示例。

读完本章,你将能够根据业务中人们提出的问题编写黄金问题,并为每个问题给出对应的黄金 SQL、提问的角色以及所需的答案类型。

讲义大纲:9节
  1. 为什么公开基准不等于你自己的测试
    • 运行 public-vs-own-score.py
    • 工作准则 公开基准用于在共同任务上比较模型,绝不能作为智能体在你的数据仓库上可用的证据。引用分数时要同时给出基准的版本,因为标准答案集会被修正。应当用根据你自己的工作、按你自己的定义编写的黄金问题来测量你的智能体,并预期两个分数会不一致。
  2. Write questions from the work people do
    • 运行 load-golden-questions.py
    • 工作准则 Collect golden questions from real requests, keep the asker's wording, and give each one a role, a kind and a note that names the definition its gold follows. Write the golden SQL against the marts the agent will use, and have the person who owns the definition read the note. Expect to spend more time on the definitions than on the SQL.
  3. Compare results, not SQL text
    • 运行 results-match-rules.py
    • 工作准则 Score an agent by comparing its result with the golden result, never by comparing SQL text, normalized or not. Keep one comparison function for every score you report, so a change in the score is a change in the agent. When a match surprises you, read the agent's SQL, because a result can match by coincidence.
  4. 顺序、舍入与列名
    • 运行 tolerant-comparison.py
    • 工作准则 忽略行顺序、列顺序和列名,允许有额外的列,并要求行数相同,数值在较小的相对容差以内。将每个标准答案舍入到明确规定的位数,并在此基础上允许该位的半个单位。仅当问题要求排名或序列时才设置order_matters。在问题或其附注中固定单位和量级,并把使用其他单位的答案视为错误,因为读者无从分辨。
  5. Check the gold before you trust it
    • 运行 gold-runs-and-agrees.py
    • 运行 gold-fan-out-audit.py
    • 运行 reworded-golden-question.py
    • 工作准则 Before a golden question scores anything, run its SQL, reject empty and NULL results, compare it with an independent query where you can, and have the definition's owner read its note. Read the agent's wrong answers for unclear questions, and fix the question, not the score. When a question can be read two ways, name the reading in its text, or make it a decline.
  6. 覆盖拒答与角色,而不只是回答
    • 运行 golden-coverage.py
    • 工作准则 从一开始就包含拒答和被禁止的问题,并把拒答分为含糊和无法回答两类,因为正确答案不同。为每个问题标注它所测试的陷阱,并在评分之前按划分统计各类问题、角色和陷阱。弥补缺口的办法是编写新问题,而不是在看到智能体对现有问题的表现之后,把它们在划分之间移动。
  7. 留出测试集
    • 运行 baseline-on-both-splits.py
    • 工作准则 在调优任何东西之前,一次性划分好你的标准问题,并且只在 dev 上调优。只在报告结果时才对测试划分打分,并且并排报告两个划分。当测试问题被看得太频繁,以至于人们开始针对它们调优时,就编写新的测试问题,并把旧的退回 dev。
  8. 生产环境中会出什么问题
    • 工作准则 把黄金问题集当作代码对待:与定义放在一起,在 CI 中运行其校验,在评分时计算黄金结果,将真实流量中的问题加入开发集,并保护测试集。得分变化时,先阅读发生变化的答案,再去修改问题集或比较方式。
  9. 本章做出的决定

4. 为智能体提供分层上下文

阅读约 81 分钟,10个示例。

读完本章,你可以为编写 SQL 的模型提供比表结构更多的信息,并按层组织:针对名称容易误导的列写下的说明、店铺业务术语的术语表,以及为每个问题检索出的已验证查询。

讲义大纲:9节
  1. 模式说明了什么,又没说明什么
    • 运行 schema-digest.py
    • 工作准则 模式放得下时,就把完整的模式保留在上下文中,并为它补充含义,而不是删去表。在编写其他任何层之前,先取一个真实的问题,列出模式中所有能回答它的解读。模式没有排除的每一种解读,都是某个其他层必须明确写出的规则。
  2. Describe columns where names mislead
    • 运行 column-descriptions.py
    • 工作准则 Write notes only for tables and columns whose names mislead: deprecated tables, amounts with a sign or unit you wouldn't guess, timestamps in a time zone other than the business's, and columns whose values include a placeholder such as (none). Write them as facts about the column, not as instructions for one question. Expect a note to fix many questions and occasionally mislead on one, and keep the questions it broke in the golden set so you see it happen.
  3. 加入业务术语表
    • 运行 glossary-context.py
    • 工作准则 为每个含义由某人选定的业务词写一个术语表条目,并用表和列来表述。每条规则最好只放在一处,要么在列说明里,要么在术语表条目里;商店的文件把取消订单的规则两处都写了,而 gq-002 上的遗漏表明,说两遍并不能让它被记住。在信任术语表之前,先在你的开发集问题上度量它;只有当它在开发集上有帮助,或者下一层依赖它时,才保留它。
  4. 检索已验证查询作为示例
    • 运行 retrieve-similar-queries.py
    • 工作准则 每个问题检索少量已验证查询,按屏蔽后问题的相似度选取,并把每个查询以其问题和 SQL 的形式呈现。设定最低得分,并用数据仓库无法回答的问题来检验它,因为词法检索总会返回一些结果。绝不要让标准问题进入已验证集合。只有当你自己的测量表明词法检索漏掉了人会认为相似的查询时,才转向嵌入。
  5. 让上下文适配预算
    • 运行 context-token-budget.py
    • 工作准则 把词元预算设定在模型窗口之内并留有充分余量,按你测得的优先级而不是按你编写各层的顺序,让每个问题的上下文适配预算。模式能放得下时,绝不舍弃。无论舍弃了什么,都先渲染稳定的层,最后渲染问题。把你的词元估计值与模型的真实计数核对一次,并让估计值保持偏高。
  6. Measure what each layer adds
    • 运行 layer-ablation-dev.py
    • 运行 figure-layers-correct-and-tokens.py
    • 运行 missing-columns-schema-only.py
    • 运行 what-stays-wrong.py
    • 工作准则 Measure context one layer at a time on the dev split, with the same questions, comparison rule and model, and keep the outcomes per question, not only the totals. Treat a difference of one or two questions on a set this size as noise until repeated runs say otherwise. Read the queries that fail, because each one names a layer you don't have yet or a rule the model still skips.
  7. 在测试集上检验所选的层
    • 运行 best-layers-on-test.py
    • 工作准则 在开发集上选定组合,然后在测试集上与基线并列只评分一次,并报告测试集的数字。记下在看过开发集结果之后对上下文所做的每一处修改,因为每一处都可能使开发集得分偏高。当开发集与测试集的结果不一致时,先检查可以测量的内容,例如每个数据集与你的示例有多接近,然后再解释这一差距。
  8. What goes wrong in production
    • 工作准则 Version the context with the warehouse: keep it beside the marts, checked in CI against the tables it names, scored on golden questions with every change, and logged per answer with the verified queries it used. Move any rule that must always hold out of the context and into a definition the model can't skip.
  9. Decisions this chapter made

5. 在语义层中一次定义指标

阅读约 68 分钟,9个示例。

读完本章,你将能够用 MetricFlow 的 YAML 规范编写商店的语义模型和指标,用本书自带的编译器把指标请求编译为 SQL,证明其实体连接不会造成行数膨胀,按财年日历分组,并确认 MetricFlow 会把同样的定义编译成同样的结果。

讲义大纲:9节
  1. 将每张表描述为一个语义模型
    • 运行 load-semantic-models.py
    • 工作准则 每张表声明一个语义模型,仅在实体唯一时才将其标为主实体,并且在数据仓库或 YAML 发生变化时,对照数据检查这些声明。编写简单指标时不使用度量,只指明其模型和聚合,除非你的 MetricFlow 版本或 dbt 项目仍然要求使用度量。
  2. Compile a metric request to SQL
    • 运行 compile-net-revenue.py
    • 工作准则 Let the agent, and every other client, send metric requests, never SQL fragments. Resolve every name in a request against the definitions, build the query as a tree with values as literals, and show the SQL with every answer so a person can read what ran. Accept a raw SQL filter only from the people who maintain the layer, never from a model.
  3. Join through entities so sums can't fan out
    • 运行 entity-join-no-fanout.py
    • 运行 figure-entity-graph.py
    • 工作准则 Declare entities so that every join the layer makes is many rows to one, and let the layer refuse the rest. When a question needs a number on a finer table, such as revenue by product, define the metric on that table rather than reaching it through a join. Check that primary entities are unique in the data, because a wrong declaration turns the protection off.
  4. 由简单指标构建比率指标和派生指标
    • 运行 refund-rate-metric.py
    • 工作准则 把每个比率都定义为两个指标之比,使两边各自聚合,再按分组相除。写明每一边按哪个时间维度计数,并确保每一边都应用自己的过滤条件,无论是写在自身定义中还是作为输入过滤条件,而不是指望读者自己知道。当表达式不止一次除法时,使用派生指标,并让它的输入保持为可单独查询的简单指标。
  5. 把财年日历放进时间主表
    • 运行 fiscal-quarter-grain.py
    • 工作准则 把所有财年日历和业务日历作为自定义粒度放进时间主表,使每个值各自指明一个期间,并让请求按它们分组。本地营业日要在指标层之前的数据集市中构建。需要跨财务期间比较时,每个期间发一次请求,再在代码中比较结果,直到你的指标层支持自定义粒度上的偏移为止。
  6. 对照 MetricFlow 检查定义
    • 运行 metricflow-agrees.py
    • 运行 metricflow-needs-a-date.py
    • 工作准则 对于你所依赖的每一种请求形态,都要拿你的层与 MetricFlow(或在生产环境中为它提供服务的任何工具)进行比较,并且在任何一方发生变化时重新运行比较。请精确锁定 MetricFlow 的版本,并把它的引擎隔离在一个模块之后,因为它的 Python API 可能在任何一个版本中发生变化。
  7. 一份定义,适配任意数据仓库的方言
    • 运行 transpile-metric-sql.py
    • 工作准则 只维护一份定义并对其转译,但在每种方言的 SQL 于对应数据仓库上运行并与已知答案比对之前,都应视其为未经测试。在编译器中对日期和除法显式做类型转换,让转译需要猜测的地方更少。
  8. 生产环境中会出什么问题
    • 工作准则 像测试代码一样测试语义层:对照数据检查实体的唯一性,在 CI 中运行每个指标的 SQL,每次变更时与 MetricFlow 和黄金问题进行比较,并且对于任何不是语义层维护人员的来源,只接受结构化请求。
  9. 本章做出的决定

6. 优先将问题路由到受治理的指标

阅读约 79 分钟,7个示例。

学完本章,你可以把语义层的指标而不是数据仓库的表作为工具提供给智能体,让它返回结构化的指标请求,并在任何内容运行之前先对该请求进行验证;当一个问题可能对应多个指标时,让它向提问的人反问;并在黄金问题上衡量这一改变带来的效果。

讲义大纲:8节
  1. 给智能体指标,而不是表
    • 运行 metric-tools.py
    • 工作准则 给智能体指标、指标的描述以及每个指标可用的维度,在问题需要之前,不要让表进入它的工具。目录能放进提示词时就放在提示词里,这样一次运行就不必花一次调用去列出指标,并让描述工具从仓库返回维度取值。目录大到提示词容纳不下时,在提示词中保留名称和描述,把维度移到描述工具之后。
  2. Ask for a request, not SQL
    • 运行 model-returns-a-request.py
    • 工作准则 Have the model return a metric request as structured arguments to a tool, and parse it into a typed request before anything else happens. Keep the reply format simple enough for your own code to parse, and keep that parser in one place. Accept SQL from a model only on a separate, guarded path, for questions no metric covers.
  3. Validate the request against the layer
    • 运行 reject-unknown-dimension.py
    • 工作准则 Validate every request before it compiles: names against the layer, categorical values against the warehouse, dates against their grain. Refuse with a message that names the allowed alternatives, and send it back to the model, which can usually correct itself in one call. Treat any request that would compile into an empty or partial result as invalid, not as an answer of zero.
  4. Ask back when a question is ambiguous
    • 运行 clarify-best-customers.py
    • 工作准则 Give the agent a tool to ask back, with options that name the layer's metrics, and show the person each option's definition. Ask back only when every option leads to a request the layer can answer; when none does, decline instead. Read clarifications in traces as you read declines, because a score counts a useless question as correct.
  5. 在黄金问题上衡量指标优先方法
    • 运行 metrics-first-score.py
    • 运行 figure-outcomes-by-approach.py
    • 工作准则 在相同的黄金问题上,将指标优先方法与你的基线并列打分,并且只在 dev 上调优。说明调优期间对 dev 划分记录了多少次,并在此之后只记录一次 test 划分。将正确、错误、报错、拒答以及因步数上限而结束的运行分别报告,同时统计澄清和被拒绝的请求,因为它们显示了调用花在哪里。
  6. 阅读不正确的运行
    • 运行 metrics-first-misses.py
    • 工作准则 逐次、逐个调用地阅读每一次不正确的运行,并按其所需分类:近似命中的指标意味着需要打磨描述或向用户反问,缺失的指标意味着语义层需要补充一个,或者该问题需要受保护的 SQL;依赖角色的答案则需要访问规则,而不是提示词。
  7. What goes wrong in production
    • 工作准则 Before you widen the agent's audience, keep one metric per business term with descriptions that say when not to use it, review validation messages as you review prompts, read dimension values when requests run, enforce roles below the agent, and count clarifications and refusals beside the score. Start with the near-duplicate metrics, because they produce valid requests that return wrong numbers.
  8. 本章的决定

7. 让智能体在防护之内编写 SQL

阅读约 102 分钟,12个示例。

读完本章,你将能够处理没有任何指标覆盖的问题:让智能体编写 SQL,并让这些 SQL 在只读模式下运行,所用数据库只包含其角色可以读取的行和列。

讲义大纲:12节
  1. Give the agent a database with only what it may read
    • 运行 agent-warehouse.py
    • 工作准则 Run the agent's SQL on a connection that can reach only what the agent may query: a role with only those grants, or, in DuckDB, a read-only database file that holds only the allowed tables, with file access and extension loading off and its settings locked. Name the allowed tables one by one. Then list what the database can't hide, such as its catalog, and refuse those reads in the guard.
  2. 为每个角色提供一个由视图组成的数据库
    • 运行 role-database.py
    • 工作准则 把数据库作为边界:以只读方式连接智能体,使用的角色只能读取视图,这些视图限制该角色可以看到的行和列;在数据仓库提供安全视图、行访问策略和掩码策略的地方,通过它们来实现。在 DuckDB 中,为每个角色提供各自的、由这些视图组成的只读数据库。用你的技术栈其余部分所用的同一份策略生成这些视图,并用解析器接受的查询来测试它们。
  3. 在运行之前解析 SQL
    • 运行 parse-agent-sql.py
    • 工作准则 在任何内容运行之前,先按将要运行它的数据仓库的方言,把智能体的 SQL 解析成树,并且只接受恰好一条语句。检查节点,不要检查文本。能够解析的查询,只是形状可以检查的查询,并不等于有效的查询;在把它发送给数据仓库之前,要对照它可能读取的表来确定(限定)其中的列。
  4. Allow only read-only queries on known tables
    • 运行 block-a-delete.py
    • 运行 block-raw-tables.py
    • 工作准则 Accept only a query at the root, walk every node for a statement that writes, and allowlist tables by schema and name, with nothing but tables and subqueries in FROM. Resolve a name without a schema as a CTE only where a CTE of that name is visible, refuse the database's catalog by name, and allow only the functions your analytics need. Check the same list the agent's database holds. When a golden question needs a table off the list, give it a mart or a metric, not a wider list.
  5. 限制行数与代价
    • 运行 explain-before-running.py
    • 运行 figure-plan-row-estimates.py
    • 工作准则 从四个方面限制每个查询:保留智能体所写较小值的行数限制、对结果大小的限制、在查询运行之前依据 EXPLAIN 检查的计划规模限制,以及覆盖守卫每一步(包括规划)的同一个截止时间。对超过任一限制的结果,应拒绝而不是截断;对含有没有估计值的步骤的计划,也应拒绝。依据你自己已知良好的查询来设定计划限制。切勿使用会运行查询的 EXPLAIN ANALYZE,并且要依靠截止时间和结果限制,而不是依靠估计值。
  6. Enforce the deadline by killing a process
    • 运行 stop-a-slow-plan.py
    • 工作准则 Start the deadline when the agent's SQL arrives, and run EXPLAIN under it as well as the query. Enforce it by killing a separate process with its own read-only connection, not with an interrupt. Check on your own database that a stopped plan and a stopped query really stop.
  7. 对守卫重放攻击
    • 运行 replay-guard-bypasses.py
    • 工作准则 依靠数据库的限制,把解析器视为纵深防御。把任何人发现的每个攻击都保留为测试:分别单独对智能体的数据库和通过守卫重放,并检查每个攻击是否都由你预期的那一层拒绝。当攻击绕过解析器时,先问数据库为何让它触及了任何内容,然后再修复解析器。
  8. Repair once from the error
    • 运行 repair-from-error.py
    • 工作准则 Repair at most once, and only from an outside signal: the guard's refusal or the warehouse's error, passed to the model with its own SQL and a prompt that doesn't assume the SQL is wrong. Let the model decline in the repair. Score repaired answers on their own, apart from first-time answers, and if your golden questions show they are rarely right, decline on a refusal instead of repairing.
  9. Transpile to the warehouse's dialect
    • 运行 transpile-to-snowflake.py
    • 工作准则 Let the agent write the dialect your golden questions are checked in, guard that SQL, and transpile the guard's output, not the agent's text, with errors raised for what the transpiler knows it can't translate. Drop the guard's quotes for warehouses that fold unquoted names to upper case, refuse functions the transpiler passed through, and run the golden questions on the target warehouse before you trust a transpiled answer, because a function with the same name can return different values.
  10. When to prefer a new metric over SQL
    • 运行 long-tail-score.py
    • 工作准则 Send a question to guarded SQL only when no metric covers it, and score that path on its own long tail of golden questions. Promote a question to the semantic layer when it recurs, when its answer goes into a report, or when guarded SQL gets it wrong on a definition, as with what counts as an order. Leave one-off lookups on the guarded path. When a question needs a table off the allowlist, build the mart and its metric rather than widening the list.
  11. 生产环境中会出什么问题
    • 工作准则 把角色的只读视图数据库当作真正的控制手段,把防护视为把错误变成拒绝、并限定成本的一层。检查智能体的授权,测试每个角色的视图,在 CI 中让每条黄金查询都通过防护,在防护和数仓两处设定时间限制,记录每一次拒绝、估算和修复及其对应的答案,并在每次变更之后,用该路径自己的黄金问题长尾为其打分。
  12. 本章做出的决定

8. 无法回答时要明确说明

阅读约 72 分钟,6个示例。

读完本章,你可以把“拒答”做成一种正式的回答:区分数据仓库能回答的问题和不能回答的问题,以已知类别的理由拒答,检查所问时间段的数据是否已经到达,为每个回答展示其出处,并用精确率和召回率衡量拒答,使智能体既不乱猜,也不过于频繁地拒绝。

讲义大纲:7节
  1. 仓库无法回答的几类问题
    • 运行 unanswerable-cases.py
    • 工作准则 把黄金集中标为拒答的每个问题归入有歧义或无法回答,并写明其类别,以便知道它需要哪种回复。只有当每种理解都可以回答时,才对有歧义的问题反问;对无法回答的问题则拒答,并说明缺少什么。对每个无法回答的问题,找出附近可能被模型误当作答案的列或值,因为那正是你要防范的错误数字。
  2. Decline with a reason
    • 运行 cannot-answer-tool.py
    • 工作准则 Make declining a tool that ends the run with a kind from a fixed list and a sentence for the person. Let the model choose among the kinds it can judge, such as missing data, a forecast or an undefined term, and let code decide the kinds code can check, such as stale data or a forbidden role. Count declines by kind, and read the reasons in traces, because a decline of the right kind can still give the wrong reason.
  3. 回答之前先检查数据新鲜度
    • 运行 stale-refunds.py
    • 运行 figure-refund-settling.py
    • 工作准则 在每个涉及某个周期的回答之前,用代码检查新鲜度:把答案所读取的每个数据源的最新加载时间,与周期结束时间加上指标的沉降窗口进行比较,当数据源不足时,无论是因为行尚未加载还是事件尚未发生,都以过期为由拒答。根据自己的数据测量每个窗口,取能覆盖已见事件的延迟。从自己的加载列或加载日志读取加载时间,绝不使用表元数据,并把每张表映射到决定其新鲜度的数据源。对没有周期的问题照常回答,并在出处中显示其数据截至时间。
  4. Show the provenance with every answer
    • 运行 answer-with-provenance.py
    • 工作准则 Show every answer with its provenance, and put the metric's name and definition first, since that's where a near-miss metric shows. Then show the filters, the period, the role and the data as of, and keep the SQL one step away for the people who check it. Show declines the same way, with their kind, reason and role.
  5. Measure declines, not only accuracy
    • 运行 decline-precision-recall.py
    • 工作准则 Score an agent on declines as well as answers: report decline precision and recall, coverage and selective risk, and a penalty score with a c your stakeholders agree to, stated as a judgement. Compare agents on the same questions, and list the wrong numbers each gave, because a change that removes one wrong number can add another. When the decline questions number in single digits, read the runs, not only the rates.
  6. 生产中会出什么问题
    • 工作准则 在更多人使用该智能体之前,为新鲜度检查配备加载日志,按计划重新测量每个指标的沉淀窗口,检查每个时间序列的最后一个周期,按类别和数据源统计拒答,并读一批理由和反问的样本。先从对可回答问题的 not_in_data 拒答入手,因为每一条都指向一个待编写的指标。
  7. 本章做出的决定

9. 让智能体只能看到被允许看的内容

阅读约 67 分钟,8个示例。

读完本章,你将能够在智能体之下、在各角色自己的数据库中,强制执行每个角色的行过滤、列掩码和最小分组规模,并以语义层中的查询改写和防护层作为纵深防御,使任何提示词都无法扩大访问范围。

讲义大纲:10节
  1. 提示词中的规则不是控制
    • 运行 prompt-rule-bypassed.py
    • 工作准则 永远不要在提示词中执行访问控制。在代码中决定某个角色可以看到什么,依据登录系统给出的角色,并将其应用到实际运行的 SQL 上。让访问规则远离提示词,以免有人把它误当作控制;并用尝试各种绕过方式的问题来测试控制:按名称点名其他区域、总计、排名,以及声称有例外的问题。
  2. Apply row filters in the compiler
    • 运行 regional-lead-revenue.py
    • 工作准则 Attach row filters to tables, not to questions, and apply them by replacing each table a query reads with a filtered subquery, after the semantic layer compiles and after the guard checks. Write a filter for every table a filtered role can reach, reach the filter's column through a key where a table has none, and refuse tables with no filter. Refuse a filter value outside the role's rows, and record the row filter in every answer's provenance.
  3. 在每条路径中屏蔽列
    • 运行 masked-emails.py
    • 工作准则 通过替换列所在的表来屏蔽列:在角色的数据库中使用视图,在改写中使用子查询,在该列的位置返回屏蔽值,绝不要通过改写查询所选取的列来屏蔽。不要把个人信息列放入语义层。对角色不得知道其存在的列,予以拒绝;对角色可以知道其存在但不得读取的列,予以屏蔽。
  4. 抑制小到足以识别个人的分组
    • 运行 small-group-suppressed.py
    • 工作准则 为每个可以查看针对个人的聚合、但不能查看个人本身的角色设定最小分组规模,并将其作为政策选择连同理由一并记录:统计机构对金额表使用 3,而更大的数并不能阻止跨回答的相减。按指标自身的过滤条件统计每组中不同的人数,抑制所有低于最小值的分组的值,并拒绝提供其行无法追溯到个人的指标。
  5. 两个答案相减可还原出一个分组
    • 先行询问 Before you run the example, predict whether the policy lets the second answer through, and what subtracting the first answer from it gives.
    • 运行 difference-two-answers.py
    • 工作准则 将小分组抑制视为对单个答案的保护,而不是对某个人跨多个答案的保护。在小分组重要的场合,应把智能体限定在一并规划好的分解上,或对数值加扰动,并检查审计日志中同一个人提出的相互重叠的问题。
  6. 把数据中的文本当作数据
    • 运行 injected-product-name.py
    • 工作准则 把模型读取的每个值都视为不可信,并且绝不让模型的文字成为答案的唯一形式。返回带有出处的表格,只有在代码对照表格检查过摘要之后才展示它,并且不要让模型能够写入的任何内容决定角色和策略。在提示中把数据标记为数据,并不是一项控制措施。
  7. 在黄金问题上衡量访问控制
    • 运行 role-scope-score.py
    • 工作准则 用写明提问者角色的黄金问题为每次策略变更评分,两个划分中都要有禁止类问题,并查看每个问题是如何被拒绝的,而不只是看是否被拒绝。决定应当告诉角色存在某条规则,还是只告诉它没有答案,并让每次拒绝都以同样的方式表述。
  8. Log who asked what, and what ran
    • 运行 audit-entries.py
    • 工作准则 Write one audit entry per question, from code, with the principal from your sign-in system, what the agent asked for, the SQL that ran after the policy, and the outcome. Keep values out of the log, protect its questions as personal data, and review it for overlapping questions and for declines a role keeps hitting.
  9. 生产环境中会出什么问题
    • 工作准则 从登录系统绑定角色,绝不取自请求的参数;在 CI 中针对数据仓库的表测试策略文件;为策略保留唯一的事实来源;通过策略列出维度取值;每次策略变更之后,查看审计日志中的拒绝记录、单一分组的答案以及相互重叠的提问。
  10. 本章做出的决定

10. 评判回答并发现回归

阅读约 98 分钟,7个示例。

读完本章,你将能够:同时用多项指标为智能体的一次运行打分;只在结果无法直接比较时才使用模型作为评判者;用任何人都能重新计算的参考标签来校准这个评判者;了解分数在两次运行之间会波动多少;并在 CI 中基于已记录的运行,对提示词、上下文或指标的变更设置关卡。

讲义大纲:8节
  1. Score a run on more than accuracy
    • 运行 scorecard.py
    • 运行 figure-accuracy-intervals.py
    • 工作准则 Report every run as a scorecard: correct with a Wilson interval, wrong numbers, declines and their recall and precision, failures by kind, and calls and tokens per question. Compare agents on the same questions in the same table. Score the test split once, when you report a final number, and say that you did; when two agents' intervals overlap, don't call either better from the totals.
  2. Judge only what can't be compared
    • 运行 judge-an-explanation.py
    • 工作准则 Use a judge only for what can't be compared with a result, such as reasons, explanations and questions back, and keep results_match() for every number. Judge each pair in both orders and count the verdicts that change, record every verdict, and read a sample of the judge's reasons, not only its labels. Don't let a judge's preference between two texts decide a release until you have measured that judge on cases with known answers.
  3. Calibrate the judge against reference labels
    • 运行 judge-agreement.py
    • 工作准则 Before you use a judge on text, measure it on cases whose answers a check can label, with labels anyone can recompute. Report observed agreement with Cohen's kappa and Scott's pi, split by the kinds of answer you'll judge, list the errors in each direction, and say how far one case moves kappa when the cases number a few dozen. Thresholds such as 0.8 are conventions, not results (Artstein and Poesio); at a kappa like the one measured here, use the judge to choose what a person reads, never to pass or fail a release on its own.
  4. Repeat runs to see the variance
    • 运行 seed-variance.py
    • 工作准则 Run each golden question several times at the sampling settings you serve, with seeds pinned in the recording's manifest, and confirm once that a seed replays exactly. Report per-question flips, not only the spread of the total, because a total can stay put while questions trade places. Never lower the temperature to make runs agree, unless that is the setting you will serve.
  5. Gate a change in CI
    • 运行 regression-gate.py
    • 工作准则 Gate a change to prompts, context or metrics on paired, per-question differences over repeated runs, never on a difference of totals. Fail on any stable break and on a mean difference whose interval lies below zero, write both rules down as your choice, and compute the smallest change they can detect on your set. When the gate fails, read the questions that moved before you touch the rules.
  6. Catch a schema change before users do
    • 运行 renamed-column-caught.py
    • 工作准则 Run the golden SQL, every metric and every recorded replay in CI on changes to the warehouse as well as to the agent, and treat MissingRecording as a failure, never as a reason to skip a question. When a check fails after a schema change, fix the definition in the semantic layer before you record anything again.
  7. 生产环境中会出什么问题
    • 工作准则 在关卡守护生产智能体之前,把其评审器的校准用例与评审提示词放在一起,并在二者任一变动时重新度量;向评审器展示它能够核对的内容;在部署所用的设置下录制多次重复运行;与对这些数字负责的人商定关卡的规则;并在每份清单中记录某个数据划分被录制了多少次。
  8. 本章做出的决定

11. 通过 MCP 提供语义层服务

阅读约 65 分钟,5个示例。

读完本章,你将能够把商店的受管指标作为 MCP 工具提供出来,使其按服务器构建时所面向的角色作答,并以结构化数据的形式随每个答案返回其出处;你还能够在内存中测试该服务器,并让本书的智能体以宿主的身份通过它运行。

讲义大纲:7节
  1. Turn metrics into tools
    • 运行 list-metric-tools.py
    • 工作准则 Serve the tools your agent was measured with, each one a thin call into the same code the in-process agent uses, so that the server can't drift from what you tested. List them in a fixed order and mark them read-only. Let the role change what a tool returns, and shorten the tool list only when a role can't use a tool at all.
  2. 将调用者的角色带入每一次查询
    • 运行 role-bound-at-build.py
    • 工作准则 在人被认证的地方绑定角色,绝不要在工具的参数中绑定。对于 stdio 服务器,由宿主在环境中传入角色,服务器打开该角色的只读数据库并一次性构建其策略。对于 HTTP 服务器,在每个请求中从为该服务器签发的已验证令牌里取得角色,并且无论令牌的作用域如何声明,都在数据库和策略中强制执行该角色的行范围。把 role 从每个输入模式中去掉,这样模型或问题就没有可填写之处;并记录工具忽略的每个参数,首先是 role,因为这样的参数表明模型读到的文本正在左右它(把工单文本视为不可信数据)。
  3. 返回带有出处的答案
    • 运行 tool-result-with-provenance.py
    • 工作准则 让每个工具都返回 pydantic 模型,使每个答案都以结构化内容的形式传递,带有它的行数据、角色、过滤条件和数据的新鲜程度,宿主的代码可以检查这些内容。对于模型能够修正的请求,抛出工具错误,并在消息中说明如何修正。对于访问方面的拒绝,则作为拒绝的答案连同理由一并返回,使宿主结束这次运行,而不是让模型尝试从别的途径进入。
  4. 在内存中测试服务器
    • 运行 semantic-server-tests.py
    • 工作准则 通过内存中的客户端测试每个角色的规则,每个角色一台服务器,并对结构化回答进行断言,同时包含一项在绑定错误时会失败的检查。使用黄金问题的结果作为期望值,使测试与评分对“正确”的含义保持一致。对于内存中的客户端无法发送的内容,添加基于 HTTP 的测试,首先是令牌。
  5. Answer questions through a host
    • 运行 host-asks-the-server.py
    • 工作准则 Put the server under the host you already measured, and score it on the golden questions before anyone uses it, because the transport can change what the model reads. Compare outcomes question by question with the in-process runs, and read every run that changed. Record what the new text produces rather than editing the server's messages to match old recordings, and show people the structured answer with its provenance.
  6. 生产环境中会出什么问题
    • 工作准则 每人运行一个 stdio 服务器,或者使用 HTTP 并让角色取自每个请求的令牌,对策略文件不认识的任何声明一律默认拒绝。使用角色自己的只读数据库查询,而不是共享的数据库。固定 SDK 版本,每当它变化时就通过宿主重新运行黄金问题。每个宿主中每个语义层只保留一个服务器,为每个回答记录一条审计条目,并留意那些看起来被多人共用的主体。
  7. 本章所做的决定

测验题库

为通过认证的教育者提供每章的习题及参考答案。每个答案均对应其所在的节。 如何获取