データエージェントをエンドツーエンドで作る

読了まで約54 分分、8 節 節の 6 例 例。

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

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

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

この章を終えると、次のことができるようになる。ショップのウェアハウスを構築し、記録済みのモデルにビジネス上の問いに対する SQL を書かせ、その SQL を実行して返ってくる誤った数値を見つけ、同じ問いに一つの定義済みメトリクスから答え、さらに両方の方法を五つのゴールデン質問で採点する。これは本書全体の成果を粗い形で示したものであり、以降の各章はその一部分を確かなものにしていく。

本書が扱う依頼は、たいてい一文で届く。データに直接問いかけられるようにしてほしい、というものである。経理担当者がダッシュボードの完成を待たずに先月の地域別純売上を知りたいと考え、誰かがあなたに言語モデルを渡す。ありがちな構成では、モデルにウェアハウスのスキーマと質問を与え、モデルが書いた SQL を実行して結果を表示する。この構成は、選び抜いた質問に対してはうまく動くことが多く、デモには十分である。しかし本書の五つのゴールデン質問では、0 of 5の正解にとどまる。問題はその失敗のしかたにある。失敗の多くは失敗に見えないからである。実行に失敗するクエリは、誰かの目に触れるエラーになる。一方、実行は成功して数パーセント高い数値を返すクエリは、そのままスライドに載ってしまう。

この章ではまず、ありがちな版を作って実行し、その数値がどこで誤るかを正確に示す。次に、本書が推奨する代替案の最小版を作る。それは、テーブルをまったく見ることができず、定義済みのメトリクスだけを扱い、メトリクスが質問をカバーしないときにはそのことを告げるエージェントである。どちらも、答えを確認済みの同じ五つの質問で採点する。この習慣は、本書の残りの部分が拠り所とするものである。

必要なものは Python 3.12.15 と SQL だけであり、GPU もクラウドアカウントも API キーも要らない。すべての例は、本書が生成するデータに対して duckdb 2.0.0 上でオフラインで動く。例で使うモデルの返答はすべて、オープンモデルから一度だけ記録したものであり、ファイルから再生される。

ショップとそのウェアハウスを知る

最終変更:版2026.11.15

ウェアハウスから質問に答えるエージェントは、ウェアハウスの定義が許す範囲でしか正しくなれない。実際のウェアハウスにはテーブル以外のものも入っている。何を注文と数えるか、合計がどの通貨で表されているか、タイムスタンプがどの日に属するかといった判断である。これらの判断は、マートの中、マートを作ったSQLの中、そしてそのSQLを書いた人々の頭の中にある。したがって、エージェントがどこで誤るのかを見るには、そうした判断と、それが生むわなを含んだウェアハウスが必要になる。

本書は全体を通して1つの事例を扱う。EMEA、AMER、APACの3つの地域でアウトドア用品とキャンプ用品を販売するオンラインショップであり、以下ではこれをショップと呼ぶ。ブランド名はなく、実在の事業を表すものでもない。そのデータは本書自身のコード lib/shop_data.py が、固定された1つのシードから生成する。そのため、どの読者も完全に同じ行を構築することになる。注文は 2024-02-01 から 2026-06-30 までにわたり、データのどの部分も、例を実行する日には左右されない。

すべての例が問い合わせるショップのウェアハウスは、アナリティクスエンジニアが組むのと同じ2つのスキーマを持つ DuckDB データベースである。raw スキーマには、ソースシステムが読み込んだもの、すなわち注文、注文明細、返金、顧客、商品、セッション、マーケティング費用、為替レートが入っている。analytics スキーマには、raw のテーブルからSQLで構築したマートが入っている。たとえば fct_orders は、実際の注文1件につき1行を持ち、金額をユーロで保持する。構築は lib/warehouse.py が行う。その connect() は、データを生成し、raw を読み込み、analytics を構築するSQLを実行して、読み取りはできるが書き込みはできず、他のファイルへのアクセスも無効にした接続を返す。

行数を見るのが最も手早い。そこで、例ではウェアハウスを構築して行数を出力する。

load-the-warehouse.py Python 3.12.15 · duckdb 2.0.0 合格
"""Build the shop's warehouse from its seed and list every table with its row count. The point about test orders rests on the `raw.orders` and `analytics.fct_orders` rows; the last two lines give the shop's test orders and its cancelled orders."""from lib.shop_data import SHOP_SEEDfrom lib.warehouse import connect, table_sizescon = connect()                  # generates the shop, loads raw, builds the marts, reopens read-onlyprint(f"seed: {SHOP_SEED}")for table, rows in table_sizes(con):    print(f"{table}: {rows:,}")# The trailing comma unpacks the one row this query returns. order_date_local is the order's day in its# region's time zone, the day sales are counted on; is_test marks orders placed from the shop's test accounts.(first, last, test_orders, cancelled), = con.execute("""    SELECT (SELECT min(order_date_local) FROM analytics.fct_orders),           (SELECT max(order_date_local) FROM analytics.fct_orders),           (SELECT count(*) FROM raw.orders WHERE is_test),           (SELECT count(*) FROM analytics.fct_orders WHERE status = 'cancelled')""").fetchall()print(f"first order day: {first}")print(f"last order day: {last}")print(f"test orders in raw.orders: {test_orders}")print(f"cancelled orders in fct_orders: {cancelled}")
出力python load-the-warehouse.py
seed: 2718
raw.customers: 3,100
raw.fx_rates: 2,649
raw.marketing_spend: 2,643
raw.order_lines: 38,439
raw.orders: 15,000
raw.products: 120
raw.refunds: 1,077
raw.sessions: 60,000
analytics.dim_customers: 3,040
analytics.dim_date: 912
analytics.dim_products: 120
analytics.fct_order_lines: 38,071
analytics.fct_orders: 14,856
analytics.fct_refunds: 1,068
analytics.fct_sessions: 60,000
analytics.orders_legacy: 15,000
first order day: 2024-02-01
last order day: 2026-06-30
test orders in raw.orders: 144
cancelled orders in fct_orders: 819

この件数だけで、すでに3つの判断が読み取れる。1つ目は、マートがショップ自身のテスト注文を除外していることである。raw.orders には 15,000 件の注文があり、analytics.fct_orders には 14,856 件がある。したがって、ショップのテストアカウントから出された 144 件のテスト注文は、マートに届かない。raw.customers から analytics.dim_customers にかけて顧客が減るのは、別の理由による。大文字小文字だけが異なるメールアドレスで2回登録した顧客がおり、またテストアカウントが除外されるためである。マートは、819 件のキャンセル済み注文をそれぞれのステータス付きで残している。キャンセルに関する質問もあるからである。

件数からは見えない判断もある。EMEAの価格はVAT込みで、AMERとAPACの価格はVAT抜きであるため、総売上と純売上は地域によって異なる。タイムスタンプはUTCで保存されているが、ショップは各地域の現地の営業日で売上を数える。ショップの会計年度は2月1日に始まり、終わる年の名で呼ばれる(たとえば2025年2月に終わる年度は2025年度)。さらに、古いダッシュボードがいまも参照している旧式のマート analytics.orders_legacy には、revenue という列があるが、そこには別の数値が入っている。税込みの総額で、テスト注文も残したものである。これらの規則のどれがどの質問に当てはまるのかは、スキーマからは何もわからない。

実践ルール: 自分の環境にある実際のわなを含んだウェアハウスに対して、エージェントを構築する。ウェアハウスには、テスト行、キャンセル済み注文、複数の通貨、現地の営業日、会計カレンダー、そして紛らわしい名前を持つ旧式テーブルを少なくとも1つ含めておく。本番データを共有できない場合は、シードから生成し、誰でも再構築できるようにする。整いすぎたデモ用スキーマは、見る必要のある失敗をまさに覆い隠してしまう。

質問をして、モデルから SQL を得る

最終変更:版2026.11.12

店舗のウェアハウスが構築できたので、次の自然な一手は、モデルにそれを照会させることである。スキーマのみのテキストから SQL への変換(text-to-SQL)とは、すべての列の名前と型、および利用者の質問だけをモデルに与え、それ以外は何も与えずに SQL を書かせる方式を指す。私たちの経験では、多くの最初の実装はここから始まる。スキーマはウェアハウスについて存在する唯一の記述であり、データベースがそれを最新の状態に保ってくれるからである。一方で、この方式が取りこぼすのは定義である。定義はスキーマには含まれない。

例でモデルを呼び出す本は、実行のたびに異なる答えを返すことになり、API キーも必要になる。そのため、本書のモデルの返答はすべて記録されている。記録とは、保存されたモデルの返答の集合にマニフェストを添えたものである。記録は、リポジトリの recordings/ フォルダにあるスクリプトによって一度だけ作成され、例の中で再生される。モデルは Qwen3-4B-Instruct-2507 で、Qwen が Apache 2.0 ライセンスで公開している。パラメータ数は 40 億(4.0 billion)で、独立した思考の段階を持たずに答えるため、返答は答えだけになる(Qwen のモデルカード)。私たちはこのモデルの 4 ビット量子化版を使う。約 2.5 GB のファイルで、SHA-256 ハッシュによって固定されており(該当ファイル)、llama-cpp-python により 4 本の CPU スレッドで実行する。そのため、GPU がなくても誰でも記録をやり直せる。

サンプリングの設定は、Qwen がこのモデルに推奨するものである。temperature は 0.7、top-p は 0.8、top-k は 20、min-p は 0 とする(Qwen のモデルカード)。シードは呼び出しのたびにリセットする。返答の上限は、SQL では 384 トークン、それ以外では 256 トークンとする。この上限は私たちの選択であり、CPU での記録の実行を短く保つためのものである。Qwen は 16,384 を提案している。各記録の manifest.json には、スクリプト、モデルとそのファイルのハッシュ、プロンプトのハッシュ、サンプリング、日付、および各呼び出しの所要時間が記される。

例の側では、lib/model.py が RecordedModel("schema-only-sql") を提供し、これがその記録を再生する。返答は、送信されたメッセージそのものの SHA-256 によって引き当てられる。1 文字でも異なるプロンプトには記録がなく、再生は別のプロンプトの返答を返すことなく、エラーで停止する。プロンプト自体は lib/prompts.py の定数 SCHEMA_ONLY_SQL であり、記録用スクリプトと例の両方で共有される。

質問は、財務チームが毎月尋ねるものである。「2026 年 3 月の地域別の純売上はいくらだったか」。これは gq-002 でもあり、答えが検証済みのゴールデンクエスチョンである。次の節では、この答えに照らして結果を検査する。返された数値を判断する前に、モデルが書いた SQL を読もう。

first-question-to-sql.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Send the warehouse's schema and one question to the recorded model, and print the SQL it wrote. The prose reads that SQL for its table, its columns and its date filter, against the `analytics.fct_orders` line printed above it."""from lib.golden import load_goldenfrom lib.model import RecordedModelfrom lib.prompts import schema_only_messagesfrom lib.warehouse import connect, describe_schemaschema = describe_schema(connect())# gq-002 is net revenue in each region in March 2026, the question the prose follows.question = next(q for q in load_golden() if q.question_id == "gq-002")messages = schema_only_messages(schema, question.question)# Each table's schema is one CREATE TABLE statement, so counting them counts the tables.print(f"tables in the prompt: {schema.count('CREATE TABLE')}")# The trailing space makes this match the whole table name, not a longer one that starts the same way.print(next(line for line in schema.splitlines() if "analytics.fct_orders " in line))model = RecordedModel("schema-only-sql")       # replays the pinned model's real repliescall = model.call_for(messages)print(f"prompt tokens: {call['prompt_tokens']}")print(f"question: {question.question}")print(call["reply"])
出力python first-question-to-sql.py
tables in the prompt: 16
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);
prompt tokens: 827
question: What was net revenue in each region in March 2026?
```sql
SELECT
    region,
    SUM(net_revenue_eur) AS net_revenue
FROM
    analytics.fct_orders
WHERE
    order_date_local >= '2026-03-01'
    AND order_date_local < '2026-04-01'
GROUP BY
    region
ORDER BY
    net_revenue DESC;
```

プロンプトには、両方のスキーマのすべてのテーブル(16 個)が CREATE TABLE 文として列挙されており、指示と質問を合わせて 827 トークンである。ここで重要なのは analytics.fct_orders の行である。この行には、net_revenue_eur 列、order_date_local 列、region、そして status がある。

モデルが書いた SQL は、多くのアナリストが最初に書くであろうものである。生のテーブルや orders_legacy ではなくマートを選んでいる。総売上ではなく net_revenue_eur を合計している。order_date_local で絞り込んでおり、各注文は UTC の日ではなく、その地域の営業日に属することになる。地域ごとにグループ化し、列には適切な名前を付けている。このクエリをプルリクエストでレビューするなら、承認するかもしれない。問題は、返される数値が正しいかどうかであり、この出力からはそれを知る手がかりが何も得られない。

実践ルール: スキーマのみの text-to-SQL は、製品ではなく、上回るべきベースラインとして扱うこと。自分のウェアハウスで一度実行して返答を保存しておくと、スキーマが伝えていない定義がどれかが分かる。テストが依拠するモデルの返答はすべて、モデルのファイル、プロンプトのハッシュ、固定したサンプリングに紐づけて記録すること。そうすれば、見つけた失敗を他の人が再現できる。

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

Run the SQL and check the number

最終変更:版2026.11.12

The model's query for March 2026 looks right, and it runs. A query that fails is caught when someone sees the error; one that runs and returns a plausible number is the failure that matters, because nothing marks it as wrong. The only way to know is to compare the result with an answer someone has checked.

A golden question is a question with its checked answer: the golden SQL, written against the owner's definition, the golden result that SQL returns, and the kind of answer expected. The golden SQL is checked by running it, which chapter 3 covers. The book keeps its golden questions in examples/data/golden/questions.toml, and lib/golden.py loads them. The golden SQL for gq-002 follows the shop's definition of net revenue, which the finance team owns: revenue in euros after discounts and before tax, from real orders that weren't cancelled, on the order's local business day.

Put the model's query beside the golden one, region by region, with each region's cancelled orders alongside to check the gap against.

run-the-model-sql.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Run the SQL the model wrote for net revenue by region in March 2026, and check it against the golden result. The prose reads each region's model, golden and cancelled-orders lines, and the final match line."""from lib.golden import golden_result, load_golden, results_matchfrom lib.model import RecordedModelfrom lib.prompts import schema_only_messagesfrom lib.tools import extract_sql, run_sqlfrom lib.warehouse import connect, describe_schemacon = connect()question = next(q for q in load_golden() if q.question_id == "gq-002")   # gq-002: net revenue in each region in March 2026reply = RecordedModel("schema-only-sql").complete(schema_only_messages(describe_schema(con), question.question))model_answer = dict(run_sql(con, extract_sql(reply)).rows)   # the query returns (region, net revenue) rows, keyed here by regiongolden = dict(golden_result(con, question))# order_date_local is a date, so BETWEEN with March 31 includes all of March.cancelled = dict(con.execute("""    SELECT region, sum(net_revenue_eur) FROM analytics.fct_orders    WHERE status = 'cancelled' AND order_date_local BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'    GROUP BY region""").fetchall())for region in sorted(golden):    print(f"{region} model: {model_answer[region]:,.2f}")    print(f"{region} golden: {golden[region]:,.2f}")    print(f"{region} cancelled orders: {cancelled[region]:,.2f}")print(f"model total: {sum(model_answer.values()):,.2f}")print(f"golden total: {sum(golden.values()):,.2f}")# as a share of the golden totalprint(f"overstated by: {sum(model_answer.values()) / sum(golden.values()) - 1:.1%}")matches = results_match(model_answer.items(), golden.items())assert not matches           # the model's SQL keeps cancelled orders, so its rows can't equal the golden rowsprint(f"matches golden: {'yes' if matches else 'no'}")
出力python run-the-model-sql.py
AMER model: 55,207.80
AMER golden: 51,762.14
AMER cancelled orders: 3,445.66
APAC model: 40,832.21
APAC golden: 35,296.93
APAC cancelled orders: 5,535.28
EMEA model: 66,502.78
EMEA golden: 63,023.76
EMEA cancelled orders: 3,479.02
model total: 162,542.79
golden total: 150,082.83
overstated by: 8.3%
matches golden: no

The query overstates net revenue by exactly the cancelled orders it counts. For EMEA it reports 66,502.78 euros against a golden 63,023.76, and the gap, 3,479.02, is the net revenue of EMEA's cancelled orders that month. AMER and APAC follow the same pattern. Across the three regions, the model's total is 8.3% above the golden total.

The query wasn't careless. The schema shows a status column, but nothing in it says cancelled orders don't count toward revenue. That rule lives in the finance team's definition, which a model reading column names can't see. A larger model might guess the rule more often, but a guess is the wrong mechanism: the next question may depend on a rule nobody would guess, such as which day a refund belongs to.

Notice what the check compares: the rows, not the SQL text, and here the rows don't match. results_match() in lib/golden.py, the rule every score in this book uses, rejects them, which the example checks.

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

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

Answer from one defined metric

最終変更:版2026.11.15

Counting cancelled orders broke the first number, because the rule that excludes them isn't in the schema. The fix this book recommends is to stop asking the model for SQL over tables, and to give it defined metrics instead. A metric is a business measure written down once, by the people who own it: a name, a description a person can check, one aggregate over one mart, the rule for which rows count, and the dimensions it may be grouped and filtered by. The model's job shrinks to choosing a metric and its arguments. Code that you wrote and tested turns that choice into SQL.

This chapter has one metric, net_revenue, in lib/metrics.py. Its rule for which rows count is the finance team's: status <> 'cancelled' on analytics.fct_orders. Its dimensions are region, channel, fiscal_year, fiscal_quarter, calendar_year and calendar_month, each mapped to one SQL expression. A metric request names the metric, the dimensions to group by and one value per filtered dimension, and compile_request() turns it into SQL. Dimension names come only from that list, and filter values are passed as query parameters, never pasted into the SQL text.

The model reaches the metric through tools. A tool is a function the model may ask the code to run, by replying with a JSON object that names it and gives its arguments. This agent has two, in lib/tools.py. query_metric computes a metric for a request. cannot_answer declines, with a one-sentence reason, when no metric covers the question. The loop that connects them is the book's own, run_agent() in lib/agent.py. It sends the messages, reads one tool call from the reply, runs the tool and stops when the tool returns an answer, after at most three model calls. The prompt, METRIC_TOOLS in lib/prompts.py, lists the metric's description and each dimension's meaning, including when the fiscal year starts. It lists no tables.

The recording metric-tool-runs holds the same model's replies to the metric prompt, recorded the way schema-only-sql was. Here is gq-002 again, through the metric.

one-metric-answer.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Answer the same question from one defined metric: the model picks the metric, the code writes and runs the SQL. The point rests on the request and the compiled SQL printed here, and on the assertion that the answer equals the golden result."""from lib.agent import run_agentfrom lib.golden import golden_result, load_golden, results_matchfrom lib.metrics import METRICS, NET_REVENUEfrom lib.model import RecordedModelfrom lib.prompts import metric_tools_promptfrom lib.tools import Toolboxfrom lib.warehouse import connectcon = connect()question = next(q for q in load_golden() if q.question_id == "gq-002")   # the same question the SQL examples answerprint(f"metric: {NET_REVENUE.name}")print(f"definition: {NET_REVENUE.description}")system = metric_tools_prompt(METRICS.values())trace = run_agent(question.question, system, RecordedModel("metric-tool-runs"), Toolbox(con))answer = trace.answer# the first step is the model's tool call, and its arguments are the request the code compilesprint(f"request: {trace.steps[0].arguments}")print(answer.provenance.sql)print(answer.show())print(answer.provenance.describe())matches = results_match(answer.rows, golden_result(con, question))assert matches               # the metric's rule drops cancelled orders, as the golden SQL doesprint(f"matches golden: {'yes' if matches else 'no'}")
出力python one-metric-answer.py
metric: net_revenue
definition: Revenue in EUR after discounts and before tax, from real orders that weren't cancelled, counted on the order's local business day. Returned orders count; refunds are not subtracted.
request: {'metric': 'net_revenue', 'group_by': ['region'], 'filters': {'calendar_month': 3, 'calendar_year': 2026}}
SELECT o.region AS region, 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_month = $1 AND d.calendar_year = $2
GROUP BY o.region
ORDER BY o.region
region  net_revenue
AMER    51,762.14
APAC    35,296.93
EMEA    63,023.76
source: metric (net_revenue)
filters: {'calendar_month': 3, 'calendar_year': 2026}
role: analyst
data as of: 2026-07-02 02:00:00
matches golden: yes

The model asked for net_revenue, grouped by region and filtered to calendar month 3 of calendar year 2026. The SQL the code compiled from that request applies the cancelled-orders rule, joins the date dimension on the local business day and passes the month and year as parameters. Each region matches its golden result.

The answer also carries its provenance: the metric that produced it, the filters, the role it was computed for, and how fresh the data is. The data as of line is when the newest row in fct_orders was loaded, read from its _loaded_at column. A person can see the definition and the currency of a number without reading SQL.

One metric is a long way from a semantic layer. It can't join through entities, it has one grain and it holds one definition. Chapter 5 replaces it with a semantic layer that does those things. The shape stays, though: the model chooses a governed definition, and code writes the SQL.

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

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

Score both on five golden questions

最終変更:版2026.11.15

One question answered from the metric shows the approach can work. It doesn't show that it works more often than schema-only SQL. For that, score both on golden questions under the same comparison rule. A score on five questions is a smoke test, not a measurement, and it can't support a claim about this model, or about text-to-SQL in general. It still separates outcomes that one accuracy figure hides.

Each answer gets one of four outcomes. An answer is correct when the result matches the golden result, or when it declines a question that should be declined. A wrong answer returns a different result, or returns any result for a question that should be declined. An error is an answer whose SQL doesn't run. A declined answer says it can't answer a question that has an answer. A decline is not a wrong number, and a score that counts the two together hides the difference this book cares about most.

The comparison rule, results_match() in lib/golden.py, accepts an answer when it has as many rows as the golden result and its columns include every golden column's values. Columns are matched by their values, not their names, so column order doesn't matter, and neither do extra columns, such as a fiscal_year column beside the total. Row order doesn't matter unless the question says it does. Numbers must agree within 0.05 percent, or within half a cent. Chapter 3 discusses each of these choices.

The five golden questions cover the traps one at a time:

ID Question Kind
gq-001 Net revenue in fiscal year 2026 answer
gq-002 Net revenue in each region in March 2026 answer
gq-003 Net revenue by sales channel in calendar 2025 answer
gq-004 Customers whose first order was in fiscal 2026 answer
gq-005 Net revenue next quarter decline

Both approaches face all five, and the output has one row per question, showing where each one fails.

score-five-golden.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Score both approaches on five golden questions: schema-only SQL, and the agent with one defined metric. The prose's counts are the totals printed on the last lines, one per outcome and approach."""from collections import Counterimport duckdbfrom lib.agent import run_agentfrom lib.golden import golden_result, grade, load_goldenfrom lib.metrics import METRICSfrom lib.model import RecordedModelfrom lib.prompts import metric_tools_prompt, schema_only_messagesfrom lib.tools import Toolbox, extract_sql, run_sqlfrom lib.warehouse import connect, describe_schemacon = connect()schema, system = describe_schema(con), metric_tools_prompt(METRICS.values())sql_model, metric_model = RecordedModel("schema-only-sql"), RecordedModel("metric-tool-runs")totals = {"schema-only": Counter(), "metric": Counter()}print("question  kind     schema-only  metric")for q in load_golden()[:5]:      # the first five; chapter 3 builds the full set    golden = golden_result(con, q)    try:        sql = extract_sql(sql_model.complete(schema_only_messages(schema, q.question)))        sql_outcome = grade(q, run_sql(con, sql), golden)    except duckdb.Error:         # a query that doesn't run raises a DuckDB error, which the score counts as an error        sql_outcome = "error"    metric_outcome = grade(q, run_agent(q.question, system, metric_model, Toolbox(con)).answer, golden)    totals["schema-only"][sql_outcome] += 1    totals["metric"][metric_outcome] += 1    print(f"{q.question_id}    {q.kind:<7}  {sql_outcome:<11}  {metric_outcome}")for name, counts in totals.items():    for outcome in ("correct", "wrong", "error", "declined"):        print(f"{name} {outcome}: {counts[outcome]} of {sum(counts.values())}")
出力python score-five-golden.py
question  kind     schema-only  metric
gq-001    answer   error        correct
gq-002    answer   wrong        correct
gq-003    answer   error        correct
gq-004    answer   wrong        declined
gq-005    decline  wrong        correct
schema-only correct: 0 of 5
schema-only wrong: 3 of 5
schema-only error: 2 of 5
schema-only declined: 0 of 5
metric correct: 4 of 5
metric wrong: 0 of 5
metric error: 0 of 5
metric declined: 1 of 5

Schema-only SQL gets 0 of 5 questions right, and the way it fails matters more than that count. It fails to run on 2 of 5 questions: for gq-001 and gq-003 the model filtered fct_orders on fiscal_year and calendar_year, columns that exist only in dim_date. Those failures are visible, which makes them the cheap ones. Its wrong answers, on 3 of 5 questions, are not. gq-002 counts cancelled orders. gq-004 counts customers whose first order fell in calendar 2026 instead of fiscal 2026. And gq-005, a forecast the warehouse can't make, gets a query over the quarter that contains today's date, which runs and returns a total instead of saying the question can't be answered.

The agent with one metric gets 4 of 5 questions right, including the decline for the forecast, and makes 0 of 5 wrong answers. It declines gq-004, which the warehouse can answer but net_revenue can't, since it counts revenue, not customers. That decline is the cost of the approach, and it is the right cost. A person who hears "I can't answer that from the metrics I have" knows to ask someone, while a person who hears a wrong count doesn't.

Small as it is, the score does show one thing. On this warehouse, the failures came from definitions the schema doesn't hold, and moving the definitions into code removed them. Chapter 3 builds the golden set to 48 questions, with a held-out split, and every later chapter reports its numbers on it.

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

1回の実行のトレースを読む

最終変更:版2026.11.12

スコアは、エージェントがどのくらいの頻度で正しかったかを示す。トレースは、1回の実行について、その理由を示す。トレースとは、run_agent() が記録した1回の実行のすべてのステップであり、モデルの各応答と、返送された各ツールの結果から成る。トレースを読むと、正しい結果が正しい理由によるものだったかどうか、そして辞退が何に基づいていたかが分かる。

エージェントは5問のスコアの中で gq-004 を辞退した。そこで、この再現では、その実行のすべてのステップを出力する。

辞退という判断は正しいが、その理由は誤っている。辞退が正しいのは、net_revenue が顧客数を数えられないからである。ところが、理由には、会計年度に初回注文を行った顧客の数に関する情報がデータにないと述べられているが、実際には analytics.dim_customers に first_order_on 列がある。実行は、全部で 1 回のモデル呼び出しの後、結果ではなく理由を返す cannot_answer の呼び出しで終了した。モデルが見たのはメトリクスの説明とディメンションだけであり、見えていないデータについて主張したことになる。読み手は、ウェアハウスにはこの問いに答えられないと結論するだろうが、それは事実ではない。

実践ルール: スコアだけでなくトレースを読み、辞退を最初に読む。各辞退の理由が、「顧客数を数えるメトリクスがない」のように、エージェントに与えられたものについて述べているのであり、見たことのないデータについての主張ではないことを確かめる。理由が誤っている辞退は、スコア上は辞退として数えられていても、欠陥として扱う。

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

What goes wrong in production

最終変更:版2026.11.12

The rough agent built here works on five questions. These are how the design fails once people depend on it, and how you'd notice each.

A plausible number goes into a decision. Schema-only SQL that runs returns a number with no warning attached, as gq-002 showed with a total 8.3% too high. Nobody notices until someone compares it with the finance team's report, often weeks later. The early warning is scoring on golden questions before release and after every change, and showing provenance with each answer, so a reader sees which definition was used.

Definitions drift away from the metric. The metric's description says cancelled orders don't count, and its SQL enforces that. When the finance team changes a rule, such as excluding a marketplace's fees, the description, the SQL and the golden SQL all need the same change. If one is missed, the agent's answers and the golden results move apart, and the score drops. That drop is the alarm, so keep the golden questions in the same repository as the metric definitions, and review changes to both together.

The agent declines for a reason that isn't true. The trace of gq-004 declined correctly but claimed the data has no first-order dates. A person who believes that reason stops asking. You notice by reading declines in traces, and by keeping golden questions that the warehouse can answer but the metrics can't, so a false reason shows up as a decline on a question you know is answerable.

A model reply changes without anyone noticing. If an example called a model live, a new model version or a changed prompt would change every downstream number silently. The replay in lib/model.py looks replies up by the hash of the exact messages, so a changed prompt stops with MissingRecording. Record again on purpose, and treat a new model version like a library release: record, score and compare.

The model file's chat template isn't the publisher's. The quantized file this book records with embeds a chat template that differs from the one Qwen publishes for this model (Qwen's template). The embedded one adds an empty thinking block to an assistant turn that ends the conversation, which Qwen's own template doesn't do. Our recording runtime, recordings/local_model.py, renders every prompt with Qwen's template at a pinned revision, checked by hash, and each manifest records whether the embedded template matched. Comparing the two before the first recording catches it, not a run of odd replies afterward.

Stale data answers confidently. The metric's answer said when the newest row in fct_orders was loaded. A mart whose load stopped would still answer, from old data, unless something checks that date against what the question needs. Show the date with every answer at least, and decline when it's too old for the question.

The model's SQL runs with no checks. In this chapter, run_sql() in lib/tools.py executes whatever the model wrote. Here the warehouse connection is read-only and can't open other files, which limits the damage to reading. A production warehouse connection usually has more rights than that. Never give a model's SQL a connection that can write: connect it read-only to a database that holds only what the asker's role may read (chapter 7), and add guards in front of it as defence in depth.

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

この章で下した決定

最終変更:版2026.11.12
  • 本書で一貫して使う事例は、生成したショップである。 ショップのウェアハウスは 1 つのシードから生成し、実際のウェアハウスにある落とし穴も含める。そのため、どの読者にも同じ行が得られ、非公開データには依存しない。
  • ウェアハウスは読み取り専用である。 warehouse.connect() は、書き込みも他のファイルを開くこともできない接続を返す。したがって、未検査の SQL であっても読み取りしかできない。
  • ベースラインは実際に記録する。 スキーマのみの SQL の応答は、前述の固定したモデルから得ている。サンプリングには Qwen の推奨設定を用い、呼び出しのたびにシードをリセットする。
  • モデルの応答はすべて記録し、メッセージのハッシュで再生する。 プロンプトが変わった場合は、古い応答を再利用せず、明示的に失敗する。
  • メトリクスを SQL より先に決める。 モデルは定義済みのメトリクスとその引数を選び、コードがリクエストを検証して SQL を書く。
  • 回答しないことも回答である。 エージェントには cannot_answer ツールがあり、スコアでは回答拒否を誤答とは別に数える。
  • すべてを 1 つの比較で採点する。 比較するのは SQL の文字列ではなく行であり、毎回同じ規則を用いる。その規則とは、行が同じであること、正解のすべての列が含まれていること、順序は問わないこと、小さな許容誤差を認めることである。
  • ループはフレームワークのものではなく、自前のものである。 lib/agent.py にある数十行のコードであり、ライブラリのリリースによって変わることはない。フレームワークの開発は止まることがある。オープンソースのテキストから SQL への変換フレームワークである vanna は、2026年3月29日にメンテナによってアーカイブされた(リポジトリ)。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全11章中の第1章: データエージェントをエンドツーエンドで作る

  1. ショップとそのウェアハウスを知る
  2. 質問をして、モデルから SQL を得る
  3. Run the SQL and check the number
  4. Answer from one defined metric
  5. Score both on five golden questions
  6. 1回の実行のトレースを読む
  7. What goes wrong in production
  8. この章で下した決定

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