AI로 번역함. 영어 원문을 사람이 검증함. 원문 읽기

에이전트를 활용한 비즈니스 인텔리전스

교육 자료 키트

2026.11.19판으로, 책의 현재 판이다. 책이 바뀌면 함께 바뀐다. 출처를 밝히면 자유롭게 사용하고 수정할 수 있다.

강의 계획서

읽기 시간은 장의 본문 기준이다. 학습자는 Lab 또는 자신의 컴퓨터에서 예제도 실행한다.

주당 한 장: 11주

5주 후

학습 목표와 개요

각 장의 학습 목표는 첫 문장이다. 각 개요는 장의 절을 따르며, 절이 정의하는 용어, 예제가 실행되기 전에 요구하는 예측, 그리고 각 절이 끝나는 규칙을 담는다. 핵심 용어와 질문으로 제시되는 예측은 퀴즈 은행이 묻는 대로 영문판의 것이다.

1. 처음부터 끝까지 만드는 데이터 에이전트

읽는 데 약 45분, 6개 예제.

이 장을 마치면 쇼핑몰의 웨어하우스를 만들고, 응답을 기록해 둔 모델이 비즈니스 질문에 대한 SQL을 작성하게 하고, 그 SQL을 실행해 잘못된 숫자가 나오는 것을 잡아내고, 같은 질문에 하나의 정의된 지표로 답하고, 두 방식을 다섯 개의 골든 질문으로 채점할 수 있다. 이 책 전체의 결과를 거친 형태로 보여 주는 장이며, 이후의 각 장은 그 가운데 한 부분을 단단하게 만든다。

강의 개요: 8절
  1. 상점과 웨어하우스 살펴보기
    • 실행 load-the-warehouse.py
    • 작업 규칙 실제로 겪을 함정이 들어 있는 웨어하우스를 대상으로 에이전트를 만든다. 테스트 행, 취소된 주문, 여러 통화, 현지 영업일, 회계 달력, 그리고 이름이 솔깃한 레거시 테이블이 최소 하나는 있어야 한다. 운영 데이터를 공유할 수 없을 때는 시드로 생성해서 누구나 다시 만들 수 있게 한다. 깔끔한 데모 스키마는 꼭 봐야 할 실패를 가린다.
  2. 질문하고 모델에게서 SQL 받기
    • 실행 first-question-to-sql.py
    • 작업 규칙 스키마만 사용하는 text-to-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. 단순 text-to-SQL이 숫자를 틀리게 만드는 경우

읽는 데 약 51분, 7개 예제.

이 장을 마치면 스키마만 사용하는 text-to-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. Time zones and the fiscal calendar
    • 실행 fiscal-year-and-local-day.py
    • 작업 규칙 Give the agent your calendar, not only your columns: which timestamp is UTC, which date is the business day, and when the fiscal year starts and how it is named. Test every period question at a boundary, such as the first day of a month or the first month of a fiscal year, where UTC and local days or calendar and fiscal years disagree. Prefer a date dimension the agent joins over date arithmetic it writes.
  4. 이름이 그럴듯한 테이블
    • 실행 legacy-table-answer.py
    • 작업 규칙 에이전트가 읽어도 되는 테이블의 목록을 만들고, 이름이 아무리 친숙해도 레거시 테이블과 스테이징 테이블은 목록에서 제외한다. 모델이 작성한 모든 쿼리는 실행되기 전에 그 쿼리의 테이블을 목록과 대조해 확인한다. 테스트에서 에이전트가 그럴듯한 테이블을 한 번도 고르지 않았더라도 이 확인은 유지한다. 새로운 질문, 더 큰 스키마, 검색된 예제가 결과를 바꿀 수 있기 때문이다.
  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. What goes wrong in production
    • 작업 규칙 Before an agent's numbers reach anyone, grade every answer against golden results, keep golden questions at period boundaries and for every definition, list the tables the agent may read, and read a sample of wrong answers by hand. Count wrong numbers by kind, and treat a rising count in any kind as an alarm.
  8. 이 장에서 내린 결정

3. Build golden questions from your own work

읽는 데 약 47분, 9개 예제.

학습을 마치면 학습자는 write golden questions from the questions people in your business ask, each with its golden SQL, the role that asks it and the kind of answer it needs 수 있다.

강의 개요: 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에서만 튜닝한다. test 분할은 결과를 보고할 때만 채점하고, 두 분할을 나란히 보고한다. test 질문을 너무 자주 들여다봐서 사람들이 그에 맞춰 튜닝하게 되면, 새 test 질문을 작성하고 기존 질문은 dev로 옮긴다.
  8. 운영 환경에서 잘못되는 것들
    • 작업 규칙 골든 집합을 코드처럼 다룬다. 정의 옆에 두고, CI에서 확인 쿼리를 실행하고, 골든 결과는 채점 시점에 계산하고, 실제 트래픽에서 얻은 질문을 dev에 추가하며, 테스트 분할을 보호한다. 점수가 움직이면 집합이나 비교를 바꾸기 전에 달라진 답변을 먼저 읽는다.
  9. 이 장에서 내린 결정

4. 에이전트에 계층형 컨텍스트 제공하기

읽는 데 약 57분, 10개 예제.

이 장을 마치면 SQL을 작성하는 모델에 스키마 이상의 정보를 계층으로 제공할 수 있다. 계층은 이름이 오해를 부르는 열에 대한 메모, 가게의 업무 용어집, 질문마다 검색해 온 검증된 쿼리로 이루어진다. 또한 이 계층들을 토큰 예산에 맞추고, 골든 질문의 개발 분할에서 각 계층이 더하는 효과를 측정하며, 가장 좋은 조합을 보류해 둔 테스트 분할에서 한 번 확인할 수 있다。

강의 개요: 9절
  1. What the schema says, and what it doesn't
    • 실행 schema-digest.py
    • 작업 규칙 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.
  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
    • 작업 규칙 집합은 dev에서 고르고, 기준선과 나란히 테스트 분할에서 한 번만 점수를 매기며, 보고하는 수치는 테스트 수치로 한다. dev 결과를 읽은 뒤 컨텍스트에 가한 모든 변경을 기록한다. 변경 하나하나가 dev 점수를 과대평가하게 만드는 경로이기 때문이다. dev와 테스트가 어긋나면 차이를 설명하기 전에, 각 분할이 예시와 얼마나 가까운지처럼 측정할 수 있는 것부터 확인한다.
  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. 시맨틱 계층에서 지표를 한 번만 정의하기

읽는 데 약 52분, 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. Check the definitions against MetricFlow
    • 실행 metricflow-agrees.py
    • 실행 metricflow-needs-a-date.py
    • 작업 규칙 Compare your layer with MetricFlow, or whichever tool serves it in production, on every request shape you rely on, and run the comparison whenever either side changes. Pin MetricFlow's version exactly and keep its engine behind one module, because its Python API can change in any release.
  7. One definition, any warehouse's dialect
    • 실행 transpile-metric-sql.py
    • 작업 규칙 Keep one definition and transpile it, but treat each dialect's SQL as untested until it runs on that warehouse against a known answer. Cast dates and divisions explicitly in the compiler, so the translation has less to guess.
  8. 운영 환경에서 무엇이 잘못되는가
    • 작업 규칙 시맨틱 계층을 코드처럼 테스트한다. 엔티티의 고유성을 데이터와 대조해 확인하고, CI에서 모든 지표의 SQL을 실행하며, 변경할 때마다 MetricFlow 및 골든 질문과 비교하고, 계층을 유지·관리하는 사람이 아닌 모든 출처에서는 구조화된 요청만 받는다.
  9. 이 장에서 내린 결정

6. 관리되는 지표로 먼저 질문을 보내기

읽는 데 약 65분, 7개 예제.

이 장을 마치면 웨어하우스의 테이블 대신 시맨틱 레이어의 지표를 에이전트에게 도구로 제공할 수 있고, 에이전트가 아무것도 실행되기 전에 검증되는 구조화된 지표 요청을 반환하게 할 수 있으며, 질문이 여러 지표를 뜻할 수 있을 때 에이전트가 사용자에게 되묻게 할 수 있고, 골든 질문으로 그 변화를 측정할 수 있다。

강의 개요: 8절
  1. Give the agent metrics, not tables
    • 실행 metric-tools.py
    • 작업 규칙 Give the agent the metrics, their descriptions and the dimensions each can use, and keep tables out of its tools until a question needs them. Put the catalog in the prompt while it fits, so a run doesn't spend a call listing metrics, and let a describe tool return dimension values from the warehouse. When the catalog outgrows the prompt, keep names and descriptions there and move the dimensions behind the describe tool.
  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. Measure metrics-first on the golden questions
    • 실행 metrics-first-score.py
    • 실행 figure-outcomes-by-approach.py
    • 작업 규칙 Score metrics-first beside your baseline on the same golden questions, and tune on dev only. Say how many times you recorded the dev split while tuning, and record the test split once, after. Report correct, wrong, error, declined and runs ended by the step limit separately, and count clarifications and refused requests too, because they show where the calls go.
  6. Read the runs that weren't correct
    • 실행 metrics-first-misses.py
    • 작업 규칙 Read every run that wasn't correct, call by call, and sort it by what it needs: a near-miss metric means the descriptions need sharpening or the question needs asking back, a missing metric means the layer needs one or the question needs guarded SQL, and an answer that depends on the role means access rules, not prompts.
  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을 작성하게 하기

읽는 데 약 75분, 12개 예제.

이 장을 마치면 어떤 지표로도 다룰 수 없는 질문을 처리할 수 있다. 에이전트가 SQL을 작성하게 하되, 그 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. Bound the rows and the cost
    • 실행 explain-before-running.py
    • 실행 figure-plan-row-estimates.py
    • 작업 규칙 Bound every query four ways: a row limit that keeps a smaller one the agent wrote, a limit on the result's size, a plan-size limit from EXPLAIN checked before the query runs, and one deadline over every step of the guard, planning included. Refuse a result over either limit rather than cut it, and refuse a plan with a step that has no estimate. Set the plan limit from your own known-good queries. Never use EXPLAIN ANALYZE, which runs the query, and rely on the deadline and the result limits, not the estimate.
  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 the attacks on the guard
    • 실행 replay-guard-bypasses.py
    • 작업 규칙 Rely on the database's limits, and treat the parser as defence in depth. Keep every attack anyone finds as a test: replay it against the agent's database alone and through the guard, and check that each is refused by the layer you expect. When an attack gets past the parser, ask first why the database let it reach anything, and then fix the parser.
  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. 답할 수 없을 때는 그렇다고 말하라

읽는 데 약 49분, 6개 예제.

이 장을 마치면 답하지 않는 것을 하나의 정식 답변으로 다룰 수 있다. 웨어하우스가 답할 수 있는 질문과 답할 수 없는 질문을 구분하고, 알려진 종류의 이유를 들어 거절하고, 질문한 기간의 데이터가 도착했는지 확인하고, 모든 답변 뒤의 출처 정보(provenance)를 보여 주고, 정밀도와 재현율로 거절을 측정한다. 이렇게 하면 에이전트는 추측하지도 않고 지나치게 자주 거절하지도 않는다。

강의 개요: 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
    • 작업 규칙 기간을 명시하는 모든 답 앞에서 코드로 최신성을 확인한다. 답이 읽는 각 피드의 가장 최근 적재 시각을 기간의 끝에 지표의 정착 기간을 더한 시점과 비교하고, 피드가 그 시점에 못 미치면, 행이 아직 적재되지 않았든 아직 발생하지 않았든, stale로 거절한다. 각 정착 기간은 이미 본 이벤트를 모두 포괄하는 지연으로서 자신의 데이터에서 측정한다. 적재 시각은 자신의 적재 열이나 적재 로그에서 읽고 테이블 메타데이터에서는 읽지 않으며, 각 테이블을 그 최신성을 결정하는 피드에 대응시킨다. 기간이 없는 질문에는 답하되, 출처 정보에 그 데이터의 기준 시점을 표시한다.
  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. 에이전트가 볼 수 있는 범위를 역할별로 제한하기

읽는 데 약 56분, 8개 예제.

이 장을 마치면 각 역할의 행 필터, 열 마스크, 최소 그룹 크기를 에이전트 아래에서, 곧 해당 역할의 자체 데이터베이스에서 강제할 수 있다. 의미 계층의 재작성과 가드는 심층 방어로 함께 쓰므로, 어떤 프롬프트도 접근 범위를 넓힐 수 없다. 또한 프롬프트에 적어 둔 접근 규칙이 왜 실패하는지 보일 수 있고, 작은 그룹으로 사람이 식별되는 일을 막을 수 있으며, 데이터 안에 들어 있는 텍스트가 지시로 작동하지 못하게 할 수 있다。

강의 개요: 10절
  1. A rule in the prompt is not a control
    • 실행 prompt-rule-bypassed.py
    • 작업 규칙 Never enforce access in a prompt. Decide what a role may see in code, from the role your sign-in system gives you, and apply it to the SQL that runs. Keep access rules out of the prompt, so nobody mistakes it for the control, and test the control with questions that try every way around it: other regions by name, totals, rankings, and questions that claim an exception.
  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. Treat text in the data as data
    • 실행 injected-product-name.py
    • 작업 규칙 Treat every value the model reads as untrusted, and never let a model's prose be the only form of an answer. Return the table with its provenance, show a summary only after code has checked it against the table, and keep the role and the policy out of anything the model can write. Marking data as data in the prompt is not a control.
  7. Measure access on the golden questions
    • 실행 role-scope-score.py
    • 작업 규칙 Score every policy change on golden questions that name their asker's role, with forbidden questions in both splits, and read how each was declined, not only whether. Decide whether a role should be told that a rule applies or only that no answer exists, and make every decline say it the same way.
  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. 답변을 평가하고 회귀를 잡아내기

읽는 데 약 64분, 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로 시맨틱 계층 제공하기

읽는 데 약 48분, 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. Return answers with their provenance
    • 실행 tool-result-with-provenance.py
    • 작업 규칙 Return a pydantic model from every tool, so that each answer travels as structured content with its rows, its role, its filters and its data's freshness, and a host's code can check them. Raise a tool error for a request the model can fix, with a message that says how. Return a refusal for access as an answer that declines, with its reason, so the host ends the run instead of letting the model try another way in.
  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 버전을 고정하고, SDK가 바뀔 때마다 호스트를 통해 골든 질문을 다시 실행한다. 각 호스트에는 시맨틱 계층당 서버를 하나만 두고, 응답마다 감사 항목을 기록하며, 한 사람보다 많은 사용자가 공유하는 것으로 보이는 주체가 있는지 감사 항목을 읽어 확인한다.
  7. 이 장이 내린 결정

퀴즈 모음

인증된 교육자를 위해 모든 장의 질문과 정답 해설을 제공한다. 각 답은 해당 절과 연결된다. 증명을 얻는 방법