エージェントに階層化したコンテキストを与える

読了まで約66 分分、9 節 節の 9 例 例。

第2026.11.15版 2026年11月19日時点で例が通過 78 例中 78 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.15)から翻訳した。 原文を読む

この章を終えると、SQL を書くモデルにスキーマ以上の情報を、階層に分けて与えられるようになる。階層とは、名前が誤解を招く列についての注記、ショップの業務用語を集めた用語集、質問ごとに取得する検証済みクエリである。これらの階層をトークン予算に収まるように調整し、正解付き質問の開発用分割で各階層が何を加えるかを測定し、最良の組み合わせをホールドアウトしたテスト用分割で一度だけ検証する。

スキーマは、列が何を意味するのかを語れない。第1章では、モデルにショップのスキーマだけを与え、2026年3月の地域別の純売上を求めさせた。モデルが書いたクエリは実行でき、正しそうに見えたが、キャンセルされた注文まで数えていた。見落とされた規則は、財務チームによる純売上の定義として存在している。しかし、モデルに与えられたもののどこにも、その規則は含まれていない。階層化したコンテキストは、スキーマが語れないことに対する最も直接的な対処法であり、規則をモデルが読む場所に書き下しておく手法である。ただし、本書が最終的に採る対処法ではない。第5章と第6章では、定義をセマンティックレイヤーに移し、モデルが読み違えられない形にする。それでも、SQL を書くエージェントにはコンテキストが必ず必要である。第7章のガード付きエージェントも例外ではない。また、この章で身につける習慣、すなわち階層を一つずつ加えて、そのたびに測定するという方法は、以後のあらゆる変更に当てはまる。

この部分はまだ翻訳されていないため、英語で表示している。

What the schema says, and what it doesn't

最終変更:版2026.11.12

A schema tells a model which tables exist, what their columns are called and what type each column holds. That is a lot, and it never goes out of date, because the database produces it. What it can't tell the model is what the columns mean: which rows a table holds, which rows count toward a business number, which time zone a timestamp is in, and which of two similar tables is the one people trust. Those meanings decide whether a query returns the right number, and they live in the SQL that built the marts and in the heads of the people who own them.

The book's measure of this is the golden questions, which chapter 3 built: questions with a verified answer, scored on the dev split while context and prompts are tuned, and once on the held-out test split. Every layer in this chapter is added to the schema, so the schema is the first layer, and the place to start is what it leaves open. build_context() in lib/context.py, the shared module that builds every layer in this chapter, returns the schema layer when it's asked for nothing else.

schema-digest.py Python 3.12.15 · duckdb 2.0.0 合格
"""What the schema tells a model about revenue, and three March 2026 totals that all fit it. The three printed totalscarry the paragraph's point: they differ, and only the one that leaves out cancelled orders follows the finance definition."""from lib.context import build_contextfrom lib.warehouse import connectcon = connect()schema = build_context(con, "", layers=("schema",))      # no question, so only the schema layer is builtprint(f"tables in the schema: {schema.text.count('CREATE TABLE')}")print(f"schema tokens (estimated): {schema.tokens}")for line in schema.text.splitlines():    if "analytics.fct_orders " in line or "analytics.orders_legacy " in line:        print(line)march = "BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'"   # the window of the question, on the business daycandidates = {    "orders_legacy.revenue": f"SELECT sum(revenue) FROM analytics.orders_legacy WHERE order_date {march}",    "fct_orders.net_revenue_eur, every order":        f"SELECT sum(net_revenue_eur) FROM analytics.fct_orders WHERE order_date_local {march}",    "fct_orders.net_revenue_eur, not cancelled":        f"SELECT sum(net_revenue_eur) FROM analytics.fct_orders WHERE order_date_local {march} "        "AND status <> 'cancelled'",          # net revenue leaves out cancelled orders, as the status note says}for name, sql in candidates.items():    (total,), = con.execute(sql).fetchall()    print(f"{name}: {total:,.2f}")
出力python schema-digest.py
tables in the schema: 16
schema tokens (estimated): 912
CREATE TABLE analytics.fct_orders (order_id INTEGER, customer_id INTEGER, region VARCHAR, country VARCHAR, channel VARCHAR, status VARCHAR, placed_at TIMESTAMP, order_date_local DATE, currency VARCHAR, line_count BIGINT, gross_revenue_eur DECIMAL(12,2), net_revenue_eur DECIMAL(12,2), discount_eur DECIMAL(12,2), tax_eur DECIMAL(12,2), _loaded_at TIMESTAMP);
CREATE TABLE analytics.orders_legacy (id INTEGER, cust_id INTEGER, order_date DATE, order_status VARCHAR, sales_region VARCHAR, revenue DECIMAL(12,2));
orders_legacy.revenue: 186,635.93
fct_orders.net_revenue_eur, every order: 162,542.79
fct_orders.net_revenue_eur, not cancelled: 150,082.83

The schema layer is the whole warehouse: all 16 tables, about 912 tokens. Read the two printed lines as a model would. analytics.fct_orders has a net_revenue_eur column and a status column, and analytics.orders_legacy has a revenue column and an order_date.

Each of the three totals the example computes for March 2026 is a reasonable reading of those two lines, and they disagree. The legacy table's revenue gives 186,635.93 euros, and the mart's net_revenue_eur over every order gives 162,542.79, which is what chapter 1's model computed. Only the third, 150,082.83, follows the finance team's definition, and nothing in the schema points to it rather than the other two.

The whole of the shop's warehouse fits in those 912 tokens, so there's no case for trimming it: a study of strong models on the BIRD benchmark found that passing the whole schema when it fits can beat selecting tables first, because the selection step can drop a column the query needs (Maamari et al., 2024). A warehouse with thousands of tables is a different problem, which this chapter doesn't solve. The shop's problem isn't which tables to show. It's that what the tables show doesn't say which number is right.

Working rule: Keep the whole schema in the context when it fits, and add meaning to it rather than taking tables away. Before you write any other layer, take one real question and list every reading of the schema that answers it. Each reading the schema doesn't rule out is a rule some other layer has to state.

この部分はまだ翻訳されていないため、英語で表示している。

Describe columns where names mislead

最終変更:版2026.11.15

The schema leaves open which of several readings is right, and the cheapest place to close some of them is the column itself. A column note is a sentence about one table or column that says what its name doesn't: which rows the table holds, the unit and sign of an amount, the time zone of a timestamp, the values a column takes, or that a table is deprecated. A note isn't documentation of every column. A column called product_name needs none, and a note that repeats the name costs tokens and says nothing. The notes worth writing are on the columns a careful analyst new to the warehouse would misread.

Published evidence points the same way. A study that generated column descriptions with a language model found that adding them to the prompt improved text-to-SQL accuracy and, in an ablation that replaced column names with uninformative ones, that the descriptions helped most there (Wretblad et al., 2024); it is a single preprint on the BIRD benchmark. Databricks' guidance for its Genie Agents says that "quality table and column descriptions in Unity Catalog are critical for Genie accuracy" (Databricks), which is the vendor's advice, not a measurement.

The shop's notes live in examples/data/shop/columns.toml, one entry per table with an optional note per column, and load_column_notes() in lib/context.py turns each into one line, such as analytics.fct_orders.placed_at: When the order was placed, in UTC. The notes cover the traps chapter 2 found: orders_legacy is deprecated, net_revenue_eur still holds a value for cancelled orders, placed_at is UTC while order_date_local is the business day, discount is negative in raw.order_lines and positive in the marts, and the fiscal year starts on February 1.

The recording context-layers shows what the notes do once the examples replay it. The recording holds the pinned model's SQL for every dev question of kind answer, written once with each layer set this chapter measures, using the prompt LAYERED_SQL in lib/prompts.py. The recording was made by recordings/record_context_layers.py, with the same model, sampling and seed as chapter 1's, and the examples replay it by the hash of the exact messages.

column-descriptions.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Add the column notes on columns whose names mislead, and count the dev questions they fix and break under the recordedmodel. The `fixed` and `broken` lines settle the net effect of the notes, and the broken question shows how a note misleads."""from lib.context import LAYER_SETS, build_context, grade_with_context, load_column_notesfrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.warehouse import connectcon = connect()notes = load_column_notes()print(f"column notes: {len(notes)}")print(f"column notes tokens (estimated): {build_context(con, '', layers=('columns',)).tokens}")for note in notes:    if note.startswith(("analytics.fct_orders.status", "analytics.fct_orders.placed_at")):        print(note)model = RecordedModel("context-layers")before, after = LAYER_SETS[0], LAYER_SETS[1]          # the sets are cumulative: [0] is the schema alone, [1] adds the notesdev = [q for q in load_golden() if q.split == "dev" and q.kind == "answer"]fixed, broken = [], []for q in dev:    was, now = grade_with_context(con, model, q, before), grade_with_context(con, model, q, after)    if was != "correct" and now == "correct":          # fixed: wrong or error without the notes, correct with them        fixed.append(q.question_id)    if was == "correct" and now != "correct":        broken.append(q.question_id)print(f"fixed by column notes: {len(fixed)} ({', '.join(fixed)})")print(f"broken by column notes: {len(broken)} ({', '.join(broken)})")
出力python column-descriptions.py
column notes: 33
column notes tokens (estimated): 1087
analytics.fct_orders.status: One of placed, shipped, delivered, cancelled, returned. Revenue leaves out cancelled orders; order and customer counts include them. Returned orders count everywhere.
analytics.fct_orders.placed_at: When the order was placed, in UTC. Don't filter or group dates on it; use order_date_local.
fixed by column notes: 7 (gq-001, gq-002, gq-003, gq-004, gq-008, gq-009, gq-011)
broken by column notes: 1 (gq-018)

The 33 notes add about 1087 tokens, more than the schema itself. On the dev questions they fix 7 (gq-001, gq-002, gq-003, gq-004, gq-008, gq-009, gq-011), among them gq-002, the March question from chapter 1, whose query now filters out cancelled orders. They also break 1 (gq-018). That question asks for the refunds on orders placed in March 2026, and with the notes the model filtered on both the order's date and refund_month, so it dropped refunds paid in a later month. The note on refund_month was accurate. The model used it on a question that didn't call for it, which is what a note can't prevent.

Working rule: 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.

ビジネス用語集を加える

最終変更:版2026.11.15

列の注記はテーブルを説明するものである。しかし、多くの質問は別の点にかかっている。ビジネス上の言葉がその会社で何を意味するか、という点である。「売上」は総額かもしれず、純額かもしれない。「注文数」にキャンセル済みの注文を含めるかどうかも定まっていない。「3月の」返金は、3月に支払われた返金を指すこともあれば、3月の注文に対する返金を指すこともある。これらは数値を管轄するチームが下した選択であり、どのテーブルにも書かれていない。ビジネス用語集は、会社のチームが意味を選んだビジネス用語を列挙し、それぞれの意味をウェアハウスのテーブルと列を使って記述したものである。

この層の根拠は、テキストから SQL への変換を評価するベンチマーク BIRD にある。BIRD の質問には「外部知識の証拠」が付属する。これは質問中の語をデータベースに結び付けるヒントであり、たとえば、ある用語が列に対する式として何を意味するかを示す。このベンチマークの論文では、証拠を加えることで、開発セットにおける GPT-4 の実行精度が 30.90% から 46.35% に上がった。条件は2023年当時のモデルとゼロショットのプロンプトである(Li et al., 2023)。ただし、このヒントは質問ごとに書かれており、一度書けば済む用語集を与えるというより、答えの材料をモデルに渡すことに近い。

このショップの用語集はexamples/data/shop/glossary.tomlである。その項目は、売上を、質問が総額と指定しない限り純売上と定義し、注文を、キャンセル済みを含むすべての注文と定義する。さらに、平均注文額、会計期間、新規顧客、支払月ごとの返金、販売数量、そして「チャネル」の二つの意味を定義する。load_glossary()は、各項目を1行に変換する。

用語集は何も見ずに書かれたわけではなく、この本の履歴がその変化を示している。スキーマだけを与えたモデルの最初の開発セットへの回答を記録した同じ変更で、注文の項目が訂正された。それまでは、注文数にキャンセル済みの注文を含めないと書かれており、財務チームの正解 SQL と食い違っていた。販売数量の項目と注文した顧客の項目もその変更で加えられ、statusの列の注記も、それに合わせて書き直された。のちに、スキーマだけでテスト用の質問への回答を記録した後で、返金率の項目が、第5章が用い、テスト用の質問gq-028も従う、本書共通の定義に変更された。その定義とは、返金額を総売上で割ることである。返金は税額も払い戻すが、総売上だけが税額を含むからである。変更のたびに、用語集は、その後で採点の基準となる正解 SQL に合うように整えられた。開発セットの得点が開発セットに合わせて調整されるのは、このようにしてである。その代償はテストセットでの検証で改めて扱う。

glossary-context.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Add the business glossary on top of the column notes, and count what it changes on the dev questions. The gq-002lines show the query the prose describes: with the glossary, the March query no longer filters on status."""from lib.context import LAYER_SETS, build_context, grade_with_context, load_glossaryfrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.prompts import layered_sql_messagesfrom lib.warehouse import connectcon = connect()terms = load_glossary()print(f"glossary terms: {len(terms)}")print(f"glossary tokens (estimated): {build_context(con, '', layers=('glossary',)).tokens}")print(next(t for t in terms if t.startswith("revenue:")))model = RecordedModel("context-layers")before, after = LAYER_SETS[1], LAYER_SETS[2]          # schema and column notes; then the glossary toodev = [q for q in load_golden() if q.split == "dev" and q.kind == "answer"]changes = {(was, now): [] for was in ("correct", "other") for now in ("correct", "other")}   # "other" is wrong or errorfor q in dev:    was, now = (grade_with_context(con, model, q, layers) for layers in (before, after))    changes["correct" if was == "correct" else "other", "correct" if now == "correct" else "other"].append(q.question_id)print(f"fixed by the glossary: {len(changes['other', 'correct'])} ({', '.join(changes['other', 'correct'])})")print(f"broken by the glossary: {len(changes['correct', 'other'])} ({', '.join(changes['correct', 'other'])})")q = next(q for q in dev if q.question_id == "gq-002")reply = model.complete(layered_sql_messages(build_context(con, q.question, after).text, q.question))filters_status = "status" in reply     # a query that filters on status has to name the columnassert not filters_status              # the chapter states it: with the glossary, gq-002 no longer filters on statusprint(f"gq-002 with the glossary filters status: {'yes' if filters_status else 'no'}")
出力python glossary-context.py
glossary terms: 13
glossary tokens (estimated): 609
revenue: Net revenue unless the question says gross: sum of analytics.fct_orders.net_revenue_eur over orders whose status isn't 'cancelled'. In EUR.
fixed by the glossary: 3 (gq-012, gq-015, gq-018)
broken by the glossary: 3 (gq-002, gq-009, gq-016)
gq-002 with the glossary filters status: no

用語集の得失は相殺される。開発セットの質問のうち3 (gq-012, gq-015, gq-018)問を直し、3 (gq-002, gq-009, gq-016)問を壊す。13個の用語は、スキーマと列の注記に加えて、約609トークンを増やす。壊れた質問こそ示唆に富む。gq-002は同じ3月の質問であるが、用語集を付けて書かれたクエリは、売上の項目とstatusの注記がいずれもキャンセル済みの注文を除くよう述べているにもかかわらず、statusでの絞り込みをしなくなった。gq-016では、モデルは顧客数の集計でキャンセル済みの注文を除外した。用語集が適用しないと述べている売上の規則を、顧客数に当てはめたのである。平均注文額を求めるgq-009では、用語集がこの指標を純売上を注文数で割ったものと定義しているにもかかわらず、モデルは平均的な注文の純売上をもう一度注文数で割った。

各構成は、質問ごとに標本抽出した回答を1つずつ、1回だけ記録している。そのため、17問のうち1、2問の変化は、2回目の標本で覆り得る範囲にある。第10章では、繰り返しの実行でこのばらつきを測る。この結果が支持するのは、もっと限定された主張である。すなわち、用語集はこれらの質問でこのモデルを良くしなかったこと、そして2回述べた規則でも見落とされたことである。もっともらしい理由は、長い文脈では小さなモデルがその各部分を確実に使えなくなることだが、ここでは測っていない。長い文脈の研究によれば、モデルはプロンプトの中ほどの情報を端の情報よりうまく使えず(Liu et al., 2024)、質問と本文が語を共有しない場合には、長さとともに精度が下がる(Modarressi et al., 2025)。

実践ルール: 意味が誰かの選択であるビジネス用語ごとに用語集の項目を書き、テーブルと列を使って記述する。各規則は、列の注記か用語集の項目のどちらか1か所に置くのが望ましい。このショップのファイルはキャンセル済み注文の規則を両方に書いているが、gq-002での見落としは、2回述べても定着しないことを示している。用語集を信頼する前に、開発セットの質問で効果を測り、そこで役立つ場合か、次の層がそれに依存する場合に限って残す。

検証済みクエリを例として取得する

最終変更:版2026.11.15

列の注記と用語集は規則を述べるものである。検証済みクエリは、その規則が適用された結果を示す。誰かが尋ねた質問と、店の定義に照らして人が確認した SQL の組である。質問に似たこうした組を数件与えると、モデルは会計期間のための dim_date への結合や status に対する絞り込みといった形を、自分で考え出す代わりに写し取ることができる。text-to-SQL のプロンプト設計を体系的に比較した研究では、最良の構成は、領域固有の語をマスクしたうえでの質問の類似度と、最初に書かせた下書きクエリとの SQL の類似度によって例を選び、各例を質問とその SQL のみで示すものであった(Gao et al., 2023)。ウェアハウスのベンダーも同じ考え方をアシスタントに組み込んでいる。Snowflake の Cortex Analyst は「質問とそれに答える対応する SQL クエリ」からなる検証済みクエリのリポジトリを保持し(Snowflake)、Databricks は Genie Agent が例の SQL クエリをそのまま使うことも、そこから学ぶこともでき、パラメータ化されたものは信頼できる資産として扱うと述べている(Databricks)。どちらもベンダー自身による説明であり、測定結果ではない。

店の検証済みクエリは examples/data/shop/verified_queries.toml にある。そのフィールドは Snowflake のフィールド名である name、question、sql、verified_at、verified_by に、クエリが確認の対象とした role を加えたものである。このうち 2 つは内容が異なる。Snowflake の verified_at は省略可能で、1970 年からの秒数で数えられ、verified_by はクエリを確認した個人を指す。店のファイルは日付を記し、チームを名指しし、個人は決して挙げない。検証済みクエリのどれも、正解質問(golden question)ではない。それらは両方の分割にある質問の近傍にあたる。たとえば 2025 会計年度の会計四半期別の純売上や、2024 年の地域別の平均注文額である。実際のリポジトリはこのように、人々が以前に尋ねた質問から育っていく。正解質問そのものが検証済みクエリであれば、スコアは複写を測ることになってしまう。

lib/context.py の取得は語彙に基づくもので、埋め込みは使わない。question_terms() は質問を小文字にし、ありふれた語を除き、3 種類の語をマスクする。数字、月名、店の 3 つの地域コードである。それ以外の語はそのまま残る。QueryIndex は各検証済み質問をマスク後の質問に対して TF-IDF とコサイン類似度で採点し、search() は 0.4 以上のスコアを持つ一致を最大 3 件まで残す。これは Gao et al. の選択方法の安価な代用であり、その再現ではない。マスクする語ははるかに少なく、下書き SQL を比較する第 2 段階も省いている。

retrieve-similar-queries.py Python 3.12.15 · duckdb 2.0.0 合格
"""Retrieve the verified queries most like a question, by TF-IDF over the masked question's words. The matches kept at the0.4 default show that a threshold can leave a question with no example, and the masked phrases show what masking does."""from lib.context import QueryIndex, load_verified_queries, question_termsqueries = load_verified_queries()index = QueryIndex(queries)print(f"verified queries: {len(queries)}")for label, question in (("aov", "What was the average order value in each region in March 2026?"),                        ("parcels", "Which warehouse ships the most parcels?")):    print(f"question: {question}")    print(f"masked terms: {' '.join(question_terms(question))}")    for score, query in index.search(question, k=3, min_score=0.0):     # no threshold here, so the scores show the gap        print(f"  {score:.3f}  {query.name}")    print(f"{label} matches kept: {len(index.search(question))}")         # the default threshold, 0.4, is the one the book uses# Months and numbers are masked; "calendar" and "year" are not common words, and "Q3" is not masked at all.for phrase in ("March 2026", "January 2025", "calendar year 2024", "EMEA in Q3"):    print(f"masked \"{phrase}\": {' '.join(question_terms(phrase))}")
出力python retrieve-similar-queries.py
verified queries: 16
question: What was the average order value in each region in March 2026?
masked terms: average order value region <month> <number>
  0.835  average_order_value_by_region
  0.422  gross_revenue_by_region_month
  0.191  orders_of_one_customer
aov matches kept: 2
question: Which warehouse ships the most parcels?
masked terms: warehouse ships most parcels
  0.375  units_sold_by_product
  0.357  net_revenue_by_category
  0.000  average_order_value_by_region
parcels matches kept: 0
masked "March 2026": <month> <number>
masked "January 2025": <month> <number>
masked "calendar year 2024": calendar year <number>
masked "EMEA in Q3": <region> q3

2026 年 3 月の地域別の平均注文額については、16 件の検証済みクエリのうち最も近いのは 2024 年の地域別の同じ指標であり、しきい値を通過する一致は 2 件である。2 番目の質問、どの倉庫が最も多くの荷物を出荷するかは、店のデータでは全く答えられない質問である。最良のスコアは共通する「most」という 1 語だけから生じ、しきい値を通過するものはないため、提示されるクエリは 0 件である。しきい値がなければ、モデルは出荷に関する質問に対して、自信ありげに見える 3 つの例(うち 2 件は商品に関するもの)を受け取ることになる。

出力の最後の数行は、マスクが何をし、何をしないかを示している。「March 2026」と「January 2025」はどちらも <month> <number> になるので、ある月についての質問が別の月についての検証済みクエリに一致する。「Calendar year 2024」は calendar year <number> になる。「calendar」と「year」はありふれた語でも値でもないからであり、「Q3」と書かれた四半期はまったくマスクされない(「Q3」自体は値として扱われない)。3 月の質問の最良の一致である 2024 暦年についての質問が、満点の 1 に届かないのはこのためである。

実践ルール: 質問ごとに検証済みクエリを数件取得し、マスクした質問の類似度で選び、それぞれを質問と SQL として示す。最小スコアを設定し、ウェアハウスが答えられない質問でそれを確かめる。語彙に基づく取得は常に何かを返すからである。正解質問を検証済みの集合に入れてはならない。語彙に基づく取得が、人が似ていると判断するクエリを取りこぼしていることを自分の測定が示したときに限り、埋め込みへ移る。

コンテキストを予算に収める

最終変更:版2026.11.12

スキーマ、列の注記、用語集、そして検索された検証済みクエリを含めた時点で、このショップのコンテキストはすでに、スキーマだけの場合の数倍のトークンを占める。層を一つ加えるごとに、コンテキストはさらに長くなる。トークン予算とは、エージェントが一つの質問に対して送ってよいコンテキストの上限である。予算が必要な理由は三つある。第一に、モデルのウィンドウには限りがある。本書の記録用ランタイムでは、モデルに 8,192 トークンが与えられ、そのうち最大 384 トークンは返答のために確保される。第二に、プロンプトの各トークンは、CPU では時間を、ホスト型のモデルでは費用を消費する。第三に、長いコンテキストは均等に使われるわけではない。モデルは、長いプロンプトの冒頭や末尾の情報に比べて、中ほどの情報をあまり利用しないからである(Liu et al., 2024)。

コンテキストを予算に収めるとは、何を省くかを決めることであり、その決定には優先順位が必要である。build_context() は、優先順位の順に層を取り上げ、その項目を一つずつ加え、予算を超えてしまう項目は捨てる。そのため、後から現れた短い項目は収まることがある。スキーマは決して捨てない。その理由は最初の節で述べたとおり、収まるスキーマは丸ごと送るべきだからである。優先順位がどうであっても、コンテキストは固定された一つの順序で組み立てる。安定した層を先頭に置き、検索されたクエリをその後ろに置き、質問を最後に置く。こうすると、質問が最もよく似た例の隣に来る。また、すべての質問が共有するプロンプトの部分を、モデルランナーが呼び出しのたびに読み直さず再利用できる。本書の記録を作成したランナーである llama-cpp-python 0.3.36 は、Llama.generate でこれを行っている。新しいプロンプトのトークンを直前のプロンプトのトークンと比較し、両者が共有する最長の接頭辞より後のトークンだけを評価する(llama-cpp-python 0.3.36, llama.py)。

lib/context.py のトークン数は推定値である。例ではモデルのトークナイザを読み込まないため、estimate_tokens() は文字数を 3.5 で割っている。以下では、この推定値を、プロンプトを記録した際にモデルのトークナイザが報告した数と比較する。また、平均注文額の質問 gq-009 のコンテキストを、例示用の 2,400 トークンの予算に、二通りの優先順位で収める。

context-token-budget.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Fit one question's layered context to a token budget, and check the token estimate against the model's count. Theestimate runs high, the safe side for a budget, and the dropped lines show what each priority gives up."""from lib.context import LAYERS, build_context, estimate_tokensfrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.prompts import layered_sql_messagesfrom lib.warehouse import connectcon = connect()question = next(q for q in load_golden() if q.question_id == "gq-009").questionfull = build_context(con, question)for layer, tokens in full.layer_tokens().items():    print(f"{layer} tokens (estimated): {tokens}")messages = layered_sql_messages(full.text, question)call = RecordedModel("context-layers").call_for(messages)print(f"prompt tokens (estimated): {estimate_tokens(''.join(m['content'] for m in messages))}")   # every message, joinedprint(f"prompt tokens (model's tokenizer): {call['prompt_tokens']}")budget = 2400          # an illustrative budget, well inside the 8,192-token window the recordings usefor name, priority in (("default", LAYERS), ("examples first", ("schema", "columns", "verified", "glossary"))):   # verified ranks above glossary    fitted = build_context(con, question, layers=priority, budget=budget)    kept = {layer: len(items) for layer, items in fitted.items.items()}    print(f"{name} priority: {fitted.tokens} tokens, kept {kept}")    print(f"{name} dropped: {len(fitted.dropped)}")print(f"render order: {', '.join(layer for layer, items in fitted.items.items() if items)}, then the question")
出力python context-token-budget.py
schema tokens (estimated): 912
columns tokens (estimated): 1087
glossary tokens (estimated): 609
verified tokens (estimated): 200
prompt tokens (estimated): 2917
prompt tokens (model's tokenizer): 2364
default priority: 2393 tokens, kept {'schema': 1, 'columns': 33, 'glossary': 9, 'verified': 0}
default dropped: 6
examples first priority: 2384 tokens, kept {'schema': 1, 'columns': 33, 'glossary': 5, 'verified': 2}
examples first dropped: 8
render order: schema, columns, glossary, verified, then the question

プロンプト全体の推定値は 2917 トークンであり、モデルのトークナイザが数えた値は 2364 である。推定値が高めに出るのは、予算にとって安全な方向である。その推定で受け入れたコンテキストは、必ず収まるからである。層を導入した順に従う既定の優先順位では、予算は列の注記をすべて残し、用語集の一部を残し、検索された二つのクエリを両方とも捨てる。捨てた項目は、二つのクエリを含めて合計 6 件である。検証済みクエリを用語集より上位に置くと、同じ予算で二つのクエリが残り、代わりに 8 件の用語集の項目が捨てられる。どちらの順序も、一般的に正しいわけではない。次の節では、このショップの質問に対して、どの層がそのトークンに見合う効果を持つかを測定する。順序を決めるべきものは、その測定結果である。

実践ルール: トークン予算はモデルのウィンドウの十分内側に設定し、各質問のコンテキストを、層を書いた順序ではなく、測定した優先順位によって予算に収める。スキーマが収まるときは、決して捨てない。何を捨てたかにかかわらず、安定した層を先頭に、質問を最後に置いて組み立てる。トークンの推定値は、モデルが実際に数えた値と一度照合し、高めの側に保つ。

この部分はまだ翻訳されていないため、英語で表示している。

Measure what each layer adds

最終変更:版2026.11.15

Each layer so far was judged by the questions it fixed and broke. To choose which layers to keep, and in what order a budget should drop them, you need all of them measured the same way. An ablation measures every layer the same way: it scores a series of configurations that differ by one layer each, on the same questions, under the same comparison rule. The questions are the dev split of the golden questions, because choosing among configurations is tuning, and tuning on the test split would leave nothing held out to check the choice.

The shop's dev split has 24 golden questions. This chapter scores the 17 of kind answer. The other 7 should be declined, because the warehouse can't answer them or the role asking may not see the answer, and a prompt that only writes SQL can't decline, so they would score as wrong under every layer set; chapters 8 and 9 score them. Each layer set adds one layer to the one before: the schema alone, then column notes, then the glossary, then up to three retrieved verified queries. The outcomes come from grade() in lib/golden.py, as in every chapter: correct when the result matches the golden result, wrong when it runs and doesn't, error when it doesn't run. The first layer set, the schema alone, isn't chapter 3's baseline either. That baseline used the schema-only prompt and scored every question in each split, while this run uses the layered prompt LAYERED_SQL with no other layer filled in and scores the answer questions only, so its numbers differ.

layer-ablation-dev.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Score each layer set on the dev split's answer questions, replaying the recorded model's SQL for each, and print thetotals, the average token counts and the outcome grid. The correct totals and the fixed and broken lines are the numbers the prose rests on."""from collections import Counterfrom lib.context import LAYER_SETS, build_context, grade_with_context, layer_set_namefrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.warehouse import connectcon = connect()model = RecordedModel("context-layers")dev_split = [q for q in load_golden() if q.split == "dev"]dev = [q for q in dev_split if q.kind == "answer"]          # the other questions are declined, and are scored in chapters 8 and 9print(f"dev split questions: {len(dev_split)}")print(f"dev questions: {len(dev)}")print(f"dev questions to decline: {len(dev_split) - len(dev)}")grid = {}for layers in LAYER_SETS:    name = layer_set_name(layers)    grid[name] = [grade_with_context(con, model, q, layers) for q in dev]    counts = Counter(grid[name])    tokens = sum(build_context(con, q.question, layers).tokens for q in dev) // len(dev)   # mean over the dev questions, whole tokens    print(f"{name}: correct {counts['correct']}, wrong {counts['wrong']}, error {counts['error']}")    print(f"{name} correct: {counts['correct']}")    print(f"{name} error: {counts['error']}")    print(f"{name} tokens: {tokens}")print("question  " + "  ".join(f"{i + 1}" for i in range(len(LAYER_SETS))))for i, q in enumerate(dev):    print(f"{q.question_id}    " + "  ".join(grid[name][i][0] for name in grid))# What the verified queries changed, against the run with the glossary.before, after = grid[layer_set_name(LAYER_SETS[2])], grid[layer_set_name(LAYER_SETS[3])]   # the glossary run, then the glossary plus verified queriesfixed = [q.question_id for q, was, now in zip(dev, before, after) if was != "correct" and now == "correct"]broken = [q.question_id for q, was, now in zip(dev, before, after) if was == "correct" and now != "correct"]print(f"fixed by verified queries: {len(fixed)}")print(f"fixed by verified queries, IDs: {', '.join(fixed)}")print(f"broken by verified queries: {len(broken)}")
出力python layer-ablation-dev.py
dev split questions: 24
dev questions: 17
dev questions to decline: 7
schema: correct 3, wrong 9, error 5
schema correct: 3
schema error: 5
schema tokens: 912
schema+columns: correct 9, wrong 7, error 1
schema+columns correct: 9
schema+columns error: 1
schema+columns tokens: 1999
schema+columns+glossary: correct 9, wrong 8, error 0
schema+columns+glossary correct: 9
schema+columns+glossary error: 0
schema+columns+glossary tokens: 2608
schema+columns+glossary+verified: correct 14, wrong 2, error 1
schema+columns+glossary+verified correct: 14
schema+columns+glossary+verified error: 1
schema+columns+glossary+verified tokens: 2775
question  1  2  3  4
gq-001    e  c  c  c
gq-002    w  c  w  c
gq-003    e  c  c  c
gq-004    w  c  c  c
gq-006    e  e  w  w
gq-007    w  w  w  w
gq-008    w  c  c  c
gq-009    w  c  w  c
gq-010    e  w  w  c
gq-011    w  c  c  c
gq-012    w  w  c  c
gq-013    e  w  w  c
gq-014    c  c  c  c
gq-015    w  w  c  c
gq-016    c  c  w  c
gq-017    w  w  w  e
gq-018    c  w  c  c
fixed by verified queries: 5
fixed by verified queries, IDs: gq-002, gq-009, gq-010, gq-013, gq-016
broken by verified queries: 0

Column notes and verified queries raise the score; the glossary doesn't. The schema alone gets 3 of the dev questions right, column notes take it to 9, and the glossary leaves it at 9. Verified queries on top give 14, the best set on dev.

The grid shows where the change came from. Against the run with the glossary, retrieved examples fixed 5 questions and broke 0. Two of the fixes are new: the fiscal-quarter question gq-010 and the order count by region gq-013, whose nearest verified queries show exactly the join and the count they needed. The other three, gq-002, gq-009 and gq-016, are the questions the glossary run had lost, so there the examples won back what the glossary had cost.

The totals say how much each layer helped. The failures say what the next layer should be, so the next two examples read them, starting with the schema-only queries that don't run.

missing-columns-schema-only.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Why the dev queries written with the schema alone don't run: the column each one names, and the analytics tables that have it.The per-table counts are the evidence the prose rests on: every failure is a column on the wrong table."""import refrom collections import Counterimport duckdbfrom lib.context import LAYER_SETS, build_contextfrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.prompts import layered_sql_messagesfrom lib.tools import extract_sql, run_sqlfrom lib.warehouse import connectcon, model = connect(), RecordedModel("context-layers")dev = [q for q in load_golden() if q.split == "dev" and q.kind == "answer"]where = Counter()for q in dev:    context = build_context(con, q.question, LAYER_SETS[0])          # the schema alone    sql = extract_sql(model.complete(layered_sql_messages(context.text, q.question)))    try:        run_sql(con, sql)        continue    except duckdb.Error as e:        column = re.search(r'column (?:named )?"(\w+)"', str(e)).group(1)   # DuckDB says either form; take the name    (tables,), = con.execute(        "SELECT string_agg(table_schema || '.' || table_name, ', ' ORDER BY 1) FROM information_schema.columns "   # sorted, so a column in two tables lists them in a fixed order        "WHERE table_schema = 'analytics' AND column_name = ?", [column]).fetchall()   # the marts only: where the model should have looked    where[tables] += 1    print(f"{q.question_id}: no column {column}; it is in {tables}")print(f"schema-only queries that don't run: {where.total()}")for tables, n in where.items():    print(f"missing column only {tables} has: {n}")
出力python missing-columns-schema-only.py
gq-001: no column fiscal_year; it is in analytics.dim_date
gq-003: no column calendar_year; it is in analytics.dim_date
gq-006: no column quantity; it is in analytics.fct_order_lines
gq-010: no column fiscal_quarter; it is in analytics.dim_date
gq-013: no column order_date; it is in analytics.orders_legacy
schema-only queries that don't run: 5
missing column only analytics.dim_date has: 3
missing column only analytics.fct_order_lines has: 1
missing column only analytics.orders_legacy has: 1

Every failure is a column the model put on the wrong table. Of the 5, 3 ask the orders mart for a fiscal or calendar column that only dim_date has, 1 asks it for quantity, which only the order lines have, and 1 uses the legacy table's order_date.

These are the mistakes column notes are for. With the notes, 1 query in the whole dev split fails to run.

A second script prints the query for each dev question that all four layers still don't get right.

what-stays-wrong.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""The dev questions that stay wrong with all four layers, each with its query, and a check of whether gq-007 fails only onthe spelling of 'tents'. The count line settles how many dev questions stay wrong, and the gq-007 line settles whether the spelling alone causes its failure."""import duckdbfrom lib.context import LAYERS, build_context, grade_with_contextfrom lib.golden import golden_result, grade, load_goldenfrom lib.model import RecordedModelfrom lib.prompts import layered_sql_messagesfrom lib.tools import extract_sql, run_sqlfrom lib.warehouse import connectcon, model = connect(), RecordedModel("context-layers")dev = [q for q in load_golden() if q.split == "dev" and q.kind == "answer"]def sql_with_all_layers(q):    return extract_sql(model.complete(layered_sql_messages(build_context(con, q.question, LAYERS).text, q.question)))unsolved = [(q, outcome) for q in dev if (outcome := grade_with_context(con, model, q, LAYERS)) != "correct"]   # LAYERS is all fourprint(f"not correct with all four layers: {len(unsolved)}")for q, outcome in unsolved:    sql = sql_with_all_layers(q)    print(f"{q.question_id} ({outcome}): {q.question}")    print("\n".join("    " + line for line in sql.strip().splitlines()))    if outcome == "error":        try:            run_sql(con, sql)        except duckdb.Error as e:            print(f"    -- {str(e).splitlines()[0]}")gq007 = next(q for q in dev if q.question_id == "gq-007")respelled = sql_with_all_layers(gq007).replace("'tents'", "'Tents'")   # change the spelling only, to see whether it is the whole failureprint(f"gq-007 with 'Tents' spelled as stored: {grade(gq007, run_sql(con, respelled), golden_result(con, gq007))}")
出力python what-stays-wrong.py
not correct with all four layers: 3
gq-006 (wrong): What were net revenue and the number of units sold in each region in 2025?
    SELECT
        o.region,
        SUM(o.net_revenue_eur) AS net_revenue,
        SUM(l.quantity) AS units_sold
    FROM analytics.fct_orders AS o
    JOIN analytics.fct_order_lines AS l USING (order_id)
    WHERE o.order_date_local >= '2025-01-01' AND o.order_date_local < '2026-01-01'
        AND o.status <> 'cancelled'
    GROUP BY o.region
    ORDER BY net_revenue DESC
gq-007 (wrong): How much net revenue came from orders that included a tent in 2025?
    SELECT
        SUM(fol.net_amount_eur) AS net_revenue
    FROM
        analytics.fct_order_lines fol
    JOIN
        analytics.fct_orders fo ON fol.order_id = fo.order_id
    JOIN
        analytics.dim_products dp ON fol.product_id = dp.product_id
    JOIN
        analytics.dim_date dd ON fo.order_date_local = dd.date_day
    WHERE
        dp.category = 'tents'
        AND dd.calendar_year = 2025
        AND fo.status != 'cancelled'
gq-017 (error): What was net revenue in each of our countries in 2025?
    SELECT d.country, round(sum(o.net_revenue_eur), 2) AS net_revenue
    FROM analytics.fct_orders AS o
    JOIN analytics.dim_date AS d ON d.date_day = o.order_date_local
    WHERE o.status <> 'cancelled'
      AND d.calendar_year = 2025
    GROUP BY d.country
    ORDER BY net_revenue DESC
    -- Binder Error: Table "d" does not have a column named "country"
gq-007 with 'Tents' spelled as stored: wrong

With all four layers, 3 questions are still not right. gq-006 asks for net revenue and units sold by region. The model joined the orders mart to its lines and summed net_revenue_eur over the joined rows, so an order's revenue counts once for every line it has. The glossary's entry for units sold says to sum the lines per order first for exactly this reason, so this is a rule the context stated and the model missed. gq-007 filters on the category 'tents' where the data says 'Tents', a value no layer lists. Spelled as stored, the answer is still wrong, because the query sums only the tent lines, where the question asks for the whole revenue of the orders that included one. gq-017 asks for "our countries", which depends on the region of the regional lead asking. No layer says who is asking, and the model's query, which takes country from dim_date, doesn't run.

This is the book's measurement on one synthetic warehouse and one 4-billion-parameter model, with one sampled reply per question, not a general result about layered context. We found no peer-reviewed study from 2025 or 2026 that measures retrieved verified queries separately from other context on business data, which is why the chapter measures it here.

Working rule: 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.

選んだ層を test で確認する

最終変更:版2026.11.12

アブレーションは、この章が調整に使った質問である dev 分割で、4 つの層すべてを選んだ。dev で最も高いスコアを出した層の組は、保持しておいた test 分割で一度確認する必要がある。このとき、スキーマのみの場合も併せて確認する。そうすれば、同じ質問で選んだことによって比較が有利になる事態を避けられる。記録 context-layers-test には、種類 answer の 17 件の test 質問に対するモデルの SQL が、この 2 つの層の組に限って収められている。各 test 質問は、後続の段落で使うため、検証済みクエリのうち最も一致するものとの照合でもスコアが付けられる。

best-layers-on-test.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Choose the best layer set on the dev split, then score it once on the held-out test split beside the schema alone. Thecorrect counts are the numbers the prose rests on, and the retrieval scores measure how close each split sits to the verified queries."""from collections import Counterfrom lib.context import LAYER_SETS, QueryIndex, grade_with_context, layer_set_name, load_verified_queriesfrom lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.warehouse import connectcon = connect()questions = [q for q in load_golden() if q.kind == "answer"]   # the answer questions only, as in the ablationdev = [q for q in questions if q.split == "dev"]test = [q for q in questions if q.split == "test"]dev_model = RecordedModel("context-layers")          # dev and test replies come from separate recordings; the test one plays no part in the choicedev_correct = {layers: sum(grade_with_context(con, dev_model, q, layers) == "correct" for q in dev)               for layers in LAYER_SETS}best = max(LAYER_SETS, key=lambda layers: (dev_correct[layers], -len(layers)))   # ties go to fewer layersprint(f"best on dev: {layer_set_name(best)}")print(f"best on dev correct: {dev_correct[best]} of {len(dev)}")test_model = RecordedModel("context-layers-test")print(f"test questions: {len(test)}")print(f"test question IDs: {', '.join(q.question_id for q in test)}")for name, layers in (("schema", LAYER_SETS[0]), ("best", best)):    counts = Counter(grade_with_context(con, test_model, q, layers) for q in test)    print(f"test {name}: correct {counts['correct']}, wrong {counts['wrong']}, error {counts['error']}")    print(f"test {name} correct: {counts['correct']}")# How close each split's questions sit to the verified queries, by the retriever's own score.index = QueryIndex(load_verified_queries())for split, qs in (("dev", dev), ("test", test)):    best_match = [(index.search(q.question, k=1, min_score=0.0)[0], q) for q in qs]   # the best match, whatever its score    print(f"{split} mean top retrieval score: {sum(score for (score, _), _ in best_match) / len(qs):.2f}")    print(f"{split} questions with no verified query kept: {sum(not index.search(q.question) for q in qs)}")    (score, query), q = max(best_match, key=lambda pair: pair[0][0])    print(f"{split} closest pair: {q.question_id} and {query.name}")    print(f"{split} closest score: {score:.3f}")
出力python best-layers-on-test.py
best on dev: schema+columns+glossary+verified
best on dev correct: 14 of 17
test questions: 17
test question IDs: gq-025, gq-026, gq-027, gq-028, gq-029, gq-030, gq-031, gq-032, gq-033, gq-034, gq-035, gq-036, gq-037, gq-038, gq-039, gq-040, gq-041
test schema: correct 4, wrong 9, error 4
test schema correct: 4
test best: correct 8, wrong 7, error 2
test best correct: 8
dev mean top retrieval score: 0.57
dev questions with no verified query kept: 2
dev closest pair: gq-001 and net_revenue_by_fiscal_quarter
dev closest score: 0.862
test mean top retrieval score: 0.63
test questions with no verified query kept: 1
test closest pair: gq-029 and new_customers_by_region
test closest score: 0.933

層は、誰も調整していない質問に対しても効果がある。これが重要な結果である。dev で最良の組は schema+columns+glossary+verified であり、dev では 14 of 17 件が正解であった。test では、スキーマのみの場合の正解は 4 件、4 つの層を使った場合の正解は 8 件である。

dev と test のスコアの差はもう一つの結果であるが、この章はその原因を測定していない。一つの説明は、検証済みクエリが dev により適しているというものである。しかし、検索器自身のスコアはこれと矛盾する。各質問の最良の一致のスコアの平均は、dev で 0.57、test で 0.63 である。

最も近い単一の組、すなわち正解質問とその検証済みの一致も test にある。それは gq-029 and new_customers_by_region であり、スコアは 0.933 で、暦年 2024 について同じ質問をしたものである。dev で最も近い組のスコアは 0.862 である。

分かっていることが 2 つある。第一に、dev は層の組を選ぶこと以外にも使われた。用語集の節で述べたとおり、最初の dev の応答を記録する際に、用語集は正解 SQL と一致するように編集された。このような編集は、意図の有無にかかわらず、コンテキストをスコア付けの対象となる質問に合わせてしまう。これが dev の過学習が起こる仕組みであり、dev のスコアを報告する結果としない理由である。第二に、2 つの分割は異なる内容を問うている。test 分割は粗利益、セッション、マーケティング費用について問うが、dev の質問はこれらに触れていない。これらの原因を切り分けるには、この章で扱った以上の質問数と繰り返しの実行が必要になる。

実践ルール: 層の組は dev で選び、test 分割でベースラインと並べて一度だけスコアを付け、test の数値を報告する。dev の結果を読んだ後にコンテキストに加えた変更はすべて書き留める。それぞれが dev のスコアを過大にしうる要因だからである。dev と test が一致しないときは、差の理由を説明する前に、各分割が手元の例にどれだけ近いかなど、測定できるものを確認する。

この部分はまだ翻訳されていないため、英語で表示している。

What goes wrong in production

最終変更:版2026.11.12

The layers raised the dev score well above the schema alone, and they stay correct only while the warehouse and its definitions stay put. Once people rely on them, the failures are quiet: a note or a verified query keeps teaching a rule its warehouse has since changed.

The notes drift away from the marts. A column note is true about the mart as it was built when someone wrote it. When the analytics engineers change fct_orders, for example to drop cancelled orders from the mart, the note that says to filter on status becomes wrong, and nothing fails. You notice by keeping the notes in the same repository as the SQL that builds the marts, reviewing them in the same pull requests, and checking in CI that every table and column a note names still exists.

A value the context never lists. The model wrote 'tents' for a category stored as 'Tents', and the query ran and returned nothing. Questions name values, such as categories, channels, regions and campaign names, and a model guesses their spelling. Reading the wrong answers whose result is empty or zero catches it. For columns with a few dozen distinct values, list them in the column note. For columns with many, retrieve the values that match the question's words, as you retrieve verified queries.

A rule stated in context is still ignored. With the glossary, the model dropped the cancelled-orders filter on gq-002 and left cancelled orders out of the customer count for gq-016. With the column notes, and again with the glossary, it left them out of the order count for gq-013. Both go against what the note on status and the glossary say. With all four layers, it summed order revenue over order lines on gq-006, which the glossary's entry for units sold warns against. Context makes a rule available. It doesn't make the model follow it. Only per-question golden scores reveal it. When a rule has to hold every time, move it out of the prompt and into code the model can't skip, which is what chapter 5's semantic layer does.

Retrieval offers the wrong example. Lexical retrieval matches words, so a question that shares only "most" with a verified query gets that query as its example unless a threshold stops it, and a question that means the same thing in other words gets nothing. Log which verified query each answer used, as Snowflake's Cortex Analyst reports it in the confidence field of its API (Snowflake), then read the logs for answers that went wrong.

A verified query is mistaken for a verified answer. A retrieved query guides the model, and the SQL it writes is new SQL that nobody checked. Databricks marks a Genie answer as verified only when the exact text of a parameterized example query is used (Databricks), which is the distinction to keep. Never show an answer as verified because a similar query was. You notice by checking what your interface says about answers that were built from examples.

Verified queries go stale. A query checked in October uses the definitions of October. When finance changes a definition, the old queries teach the old rule to every similar question. Keep a verified_at date on each query, re-run each against its golden counterpart when a definition changes, and remove queries nobody has checked since the change.

The context grows until it costs more than it gives. Each layer is cheap to add, and nobody removes one that stopped helping. On a CPU every prompt token costs time, and with a hosted model it costs money on every call. Recording the tokens of each call with its outcome, as the recordings here do, and re-running the ablation when a layer grows, shows which layer has stopped paying for its tokens.

Working rule: 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.

この部分はまだ翻訳されていないため、英語で表示している。

Decisions this chapter made

  • Context comes in four layers: the whole schema, notes on columns whose names mislead, a business glossary, and verified queries retrieved per question. Each lives in a file under examples/data/shop/, and build_context() in lib/context.py assembles them.
  • The schema is never trimmed while it fits; the budget applies to the other layers.
  • Verified queries are retrieved lexically, by TF-IDF over the question's words with numbers, months and region codes masked, at most three, each with a score of at least 0.4. None of them is a golden question, and each names the team that verified it, never a person.
  • The context is rendered stable layers first and the question last, so the question sits beside its examples and the runner can reuse the shared prefix.
  • Tokens are estimated from characters, at 3.5 characters a token, which overestimated the model's count on the prompt checked, so a context that fits the estimate should fit the model; check it on your own prompts.
  • Layers are measured by ablation on the dev split's answer questions, one layer at a time, and the best set is checked once on the test split beside the schema alone.
  • The book keeps all four layers for the chapters that write SQL, because that set scored best on dev. The glossary stays although it didn't improve the score by itself: the verified-query layer was measured on top of it, and we didn't measure verified queries without it.

この版における本章

第2026.11.15版2026年11月19日時点で例が通過この章の9 例件のうち9件が合格

英語版の書籍(版2026.11.15)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第4章: エージェントに階層化したコンテキストを与える

  1. What the schema says, and what it doesn't
  2. Describe columns where names mislead
  3. ビジネス用語集を加える
  4. 検証済みクエリを例として取得する
  5. コンテキストを予算に収める
  6. Measure what each layer adds
  7. 選んだ層を test で確認する
  8. What goes wrong in production
  9. Decisions this chapter made

ページの先頭に戻るすべての章