Field Log · Entry

RAG Agent 모델 선택과 배포: 평가·Canary·Rollback (10/10)

RAG Agent 후보 모델을 grounding tool calling latency cost gate로 평가하고 offline shadow canary rollback 단계로 배포하는 구조

오늘의 결론

  • 모델 선택은 leaderboard 1등을 고르는 일이 아니라 제품 요구사항 아래 품질·지연·비용·안전·운영 제약의 Pareto frontier를 찾는 일입니다.
  • 먼저 탈락 조건인 hard gate와 slice별 최저선을 적용하고, 통과한 후보만 가중 utility로 비교합니다. 평균 점수가 높은 모델이 중요한 언어·권한·도구 slice에서 실패하면 배포할 수 없습니다.
  • RAG agent는 최종 답만 평가해서는 안 됩니다. Retrieval evidence, claim grounding, abstention, tool 선택·argument·순서, state transition, side effect까지 trajectory로 채점합니다.
  • Public benchmark는 후보를 줄이는 prior입니다. 최종 결정은 동일한 prompt·retrieval snapshot·tool sandbox·serving 조건에서 실행한 versioned product evaluation이 내립니다.
  • 배포는 offline 통과로 끝나지 않습니다. Side effect 없는 shadow, 작은 canary, 점진 ramp, 자동 rollback, model identity가 포함된 관측성을 하나의 release protocol로 운영합니다.

앞 글에서는 model 요청을 TTFT·ITL·goodput SLO 안에서 서빙하는 법을 다뤘습니다. 이제 어떤 model을 그 server에 올릴지, 바꾼 model을 어떻게 실제 traffic에 안전하게 노출할지 결정합니다.

product contract
  → candidate manifest
  → reproducible offline evaluation
  → hard gates + Pareto comparison
  → shadow → canary → progressive ramp
  → monitor, rollback, learn

RAG Agent product contract에서 후보 모델을 grounding tool calling context latency cost license로 평가하고 hard gate와 Pareto frontier를 거쳐 offline shadow canary ramp rollback으로 배포하며 production trace를 다음 평가 corpus로 되돌리는 구조

그림 1. 모델 결정과 배포는 일회성 표가 아니라 닫힌 loop다. Production failure를 versioned evaluation case로 환원해야 다음 교체가 더 안전해진다.


“가장 좋은 모델”은 요구사항 없이 정의할 수 없다

RAG agent의 목적 함수를 먼저 적습니다.

maximize:
  grounded task success
  tool execution correctness
  user utility

subject to:
  latency SLO
  budget
  privacy and data residency
  license and deployment constraints
  safety and authorization policy
  operational reliability

이 제약이 바뀌면 같은 benchmark 결과에서도 선택이 달라집니다.

  • 내부 문서 assistant는 citation과 access control이 중요합니다.
  • 실시간 voice agent는 ITL과 짧은 답변이 중요합니다.
  • 결제 agent는 tool argument와 side-effect authorization이 가장 중요합니다.
  • Batch research assistant는 latency보다 긴 context reasoning과 비용이 중요할 수 있습니다.

따라서 “어떤 모델이 최고인가?”를 “어떤 workload slice에서 어떤 제약을 만족하는 후보가 남는가?”로 바꿉니다.

Product Contract를 Testable하게 쓴다

모호한 요구사항:

한국어를 잘하고 hallucination이 적어야 한다.

검증 가능한 contract:

Korean policy QA slice:
  grounded claim precision ≥ target
  citation source coverage ≥ target
  unsupported high-risk claim = 0 in locked critical set
  p95 TTFT ≤ target at defined arrival trace
  average cost per successful answer ≤ budget

Threshold 값은 risk와 baseline으로 정합니다. 숫자가 있다는 사실보다 분모, dataset, traffic shape, confidence interval이 고정돼 있는지가 중요합니다.

Success Unit을 정한다

한 turn이 성공 단위인지, 전체 episode인지 구분합니다.

turn success:
  one answer is grounded and useful

episode success:
  retrieve → clarify → call tools → verify → finish goal
  without unsafe or duplicate side effects

Agent는 중간 turn이 좋아도 마지막 tool action을 틀리면 episode 실패입니다.


Candidate Identity를 고정한다

Model 이름 하나로는 실험을 재현할 수 없습니다.

Hosted API 후보

  • Provider와 model id
  • Pinned snapshot/version 또는 관찰 시각
  • Region과 service tier
  • API protocol과 SDK version
  • System prompt와 chat template
  • Tool/function schema representation
  • Temperature, top-p, seed 지원 여부
  • Max output tokens와 stop condition
  • Structured-output mode
  • Safety filter와 moderation configuration
  • Retry와 timeout policy

Mutable alias는 provider가 backend를 바꿀 수 있습니다. Snapshot을 pin할 수 없으면 evaluation 실행 시각, response model id, behavior fingerprint를 기록하고 change detection을 둡니다.

Self-hosted 후보

  • Weight artifact hash
  • Base model과 fine-tune lineage
  • Tokenizer·chat template hash
  • Quantization recipe와 calibration manifest
  • Adapter identity와 merge 순서
  • Inference engine·kernel·driver version
  • Tensor/pipeline parallel degree
  • Sampling implementation
  • Context extension·RoPE configuration

같은 weight도 chat template이나 quantized kernel이 다르면 다른 candidate입니다.

Candidate Manifest 예시

candidate:
  id: model-b-rag-agent-v4
  source: self-hosted
  weight_hash: sha256:...
  tokenizer_hash: sha256:...
  chat_template: agent-template-v12
  quantization: awq-w4a16-g128-v3
  adapter: korean-rag-tools-v7
runtime:
  engine: serving-v9
  tensor_parallel: 4
  context_limit_tokens: 32768
generation:
  temperature: 0
  max_output_tokens: 1024
  structured_output: json-schema
retrieval:
  corpus_snapshot: policy-corpus-2026-07-01
  embedder: retriever-v8
  index: hybrid-index-v11
prompt:
  system_template: rag-agent-system-v15
  tool_schema_bundle: tools-v9
evaluation:
  suite: rag-agent-model-select-v13
  runner_commit: abc1234

Open Weight와 Open Source를 구분한다

Weight를 내려받을 수 있다고 모든 사용·수정·재배포가 허용되는 것은 아닙니다.

  • License 전문과 version
  • Commercial use 제한
  • Acceptable-use policy
  • Derivative model과 adapter 배포 조건
  • Attribution 의무
  • Training data·output 관련 약정
  • Patent·trademark 조항

법률 판단은 담당 검토를 거칩니다. Model card의 “open” 표현만으로 production 사용 권한을 추론하지 않습니다.

Hosted와 Self-hosted의 비교 축

Hosted APISelf-hosted
초기 운영상대적으로 단순Runtime·GPU 운영 필요
통제Version·filter가 provider에 의존 가능Weight·engine·network 통제 가능
ElasticityProvider quota·tier 내 확장직접 capacity·autoscale 설계
비용Token·request pricingGPU·idle·운영·egress 포함
Privacy계약·region·retention 확인자체 경계 설계 가능, 책임도 직접 부담
CustomizationPrompt·일부 fine-tuneQuantization·adapter·kernel까지 가능
FailureProvider outage·rate limit자체 hardware·scheduler failure

어느 쪽이 항상 싸거나 안전한 것은 아닙니다. 실제 utilization, staffing, SLO, data classification으로 계산합니다.


후보를 줄이는 8개 축

1. Language와 Domain

한국어 benchmark 평균만 보지 않습니다.

  • 존댓말·반말과 문체
  • 한글·영문·숫자·단위 혼합
  • 법률·의학·기술 용어
  • 오탈자·띄어쓰기·구어체
  • 한국어 query와 영문 source의 교차 언어 grounding
  • Citation span과 조사 결합

Production query 분포로 slice를 만듭니다.

2. Tokenizer

같은 text가 model마다 다른 token 수가 됩니다.

effective cost and context
  depend on tokenizer(prompt + retrieved docs + tool schema + output)
  • 한국어 character당 token 수
  • JSON key와 UUID tokenization
  • Whitespace와 code block
  • Special token 처리
  • Tool schema token overhead

Provider 가격이 token 기준이면 tokenizer 효율은 품질과 비용을 동시에 바꿉니다.

3. Context Length와 Effective Use

Advertised context window는 입력을 받아들일 수 있는 상한일 뿐, 그 길이에서 필요한 evidence를 안정적으로 사용하는 보장이 아닙니다.

  • Evidence position을 앞·중간·뒤로 바꿉니다.
  • Distractor 비율을 늘립니다.
  • 여러 문서의 evidence를 결합합니다.
  • Full-context reasoning과 simple needle retrieval을 분리합니다.
  • 긴 tool schema와 conversation history가 차지하는 token도 포함합니다.

LongBench는 long-context의 여러 task category를, ICLR 2025 HELMET은 synthetic needle task만으로 downstream 능력을 대표하기 어렵다는 점과 더 application-centric한 평가를 다룹니다. Public 결과를 참고하되 제품 문서 구조로 재현합니다.

4. Grounding과 Abstention

RAG model은 답을 아는 능력뿐 아니라 evidence에 없는 답을 만들지 않는 능력이 필요합니다.

  • Claim-evidence entailment
  • Citation precision과 coverage
  • Answer completeness
  • Evidence conflict 처리
  • Insufficient evidence abstention
  • Retrieval failure를 감지하고 다시 검색하는 능력

“모르겠습니다” 비율이 낮다고 좋은 것이 아닙니다. Answerable과 unanswerable case를 함께 두고 selective risk를 봅니다.

5. Tool Calling

JSON syntax만 맞으면 충분하지 않습니다.

  • Tool 선택
  • Required argument와 type
  • Enum·format·range constraint
  • No-call/abstain
  • Serial dependency
  • Parallel-safe call 구분
  • State를 읽은 뒤 다음 action 선택
  • Tool error 후 retry·repair
  • User confirmation이 필요한 side effect

BFCL은 single·parallel·multiple function call과 AST 기반 평가, stateful multi-step·abstention으로 확장된 tool-use benchmark입니다. ToolSandbox와 τ-bench는 stateful conversation과 tool-agent-user interaction을 더 직접적으로 다룹니다. 제품에서는 실제 tool schema와 policy로 별도 sandbox를 만듭니다.

6. Safety와 Authorization

일반 refusal benchmark만으로 agent safety를 판단할 수 없습니다.

  • Retrieved document의 indirect prompt injection
  • Tool output의 malicious instruction
  • Unauthorized resource id 변경
  • Cross-tenant data exfiltration
  • Excessive tool scope
  • Confirmation bypass
  • Destructive action과 dry-run 혼동
  • Sensitive log disclosure

Model이 공격을 거부해도 harness가 이미 privileged tool을 호출했다면 실패입니다. Policy engine과 least-privilege credential을 model 밖에 둡니다.

7. Latency와 Reliability

앞 글의 정의를 그대로 사용합니다.

  • TTFT p50·p95·p99
  • ITL/TPOT tail
  • Time to valid tool call
  • End-to-end episode time
  • Timeout·rate-limit·5xx 비율
  • Retry amplification
  • SLO-satisfying goodput

Quality eval과 동일한 prompt length·output limit·concurrency에서 측정합니다.

8. Cost와 Operability

  • Input·output·cached token 비용
  • Tool·retrieval·embedding·reranking 비용
  • GPU idle과 replica headroom
  • Context retry와 failed generation 비용
  • Observability·storage·egress
  • On-call과 upgrade effort
  • Quota와 capacity reservation
  • Rollback 가능한 artifact와 support window

가격표의 output token 단가 하나로 비교하지 않습니다.


Evaluation Pyramid를 만든다

위로 갈수록 현실적이지만 느리고 비쌉니다.

level 6  online canary outcomes
level 5  adversarial / security / failure injection
level 4  end-to-end agent trajectories in sandbox
level 3  model task eval: grounding, tools, long context
level 2  retrieval and component eval
level 1  deterministic contract and unit tests

Level 1: Deterministic Contract

  • JSON schema validation
  • Stop/EOS behavior
  • Max token enforcement
  • Citation id format
  • Tool argument type and range
  • Prompt template rendering
  • Token budget overflow
  • Provider error mapping

Model 호출 없이도 검증 가능한 부분은 deterministic test로 둡니다.

Level 2: Component

  • Retriever Recall@k·nDCG
  • Reranker ranking quality
  • Chunk provenance
  • Access-control filter
  • Context packing과 deduplication
  • Tool registry와 authorization

Generator가 retrieval failure를 가리지 못하게 분리합니다.

Level 3: Model Task

  • Closed-book와 given-evidence QA
  • Grounded answer와 abstention
  • Tool selection·argument generation
  • Long-context evidence use
  • Structured output
  • Multilingual·domain slice

Level 4: End-to-end Trajectory

실제 stateful sandbox에서 episode를 실행합니다.

user request
  → query rewrite
  → retrieve
  → inspect evidence
  → choose tool
  → validate arguments
  → execute sandbox action
  → observe result
  → answer with citation

중간 action과 final state를 모두 채점합니다.

Level 5: Adversarial와 Failure

  • Poisoned document
  • Tool timeout·malformed response
  • Conflicting evidence
  • Stale index
  • Permission denied
  • Duplicate retry
  • Long irrelevant context
  • Ambiguous user instruction
  • Prompt injection and data exfiltration

Level 6: Online

Shadow와 canary에서 실제 arrival·language·document 분포를 관찰합니다. Offline label이 없는 outcome은 human review, user correction, downstream success signal을 사용하되 proxy 한계를 기록합니다.

Public Benchmark는 어디에 쓰나

Public benchmark는 후보 생성과 약점 가설에 유용합니다.

Benchmark주로 보는 것제품 결정에서의 한계
HELM여러 scenario·metric의 holistic 비교제품 prompt·corpus·tool과 다름
LongBenchBilingual long-context multitask실제 RAG pipeline·latency를 직접 대표하지 않음
HELMETApplication-oriented long-context categories제품 document distribution과 재검증 필요
BFCLFunction/tool call 구조와 stateful 확장실제 authorization·side effect는 별도 평가
AgentBench여러 interactive environment의 agent 능력제품 workflow와 action space가 다름
ToolSandboxStateful conversational tool use제품 schema·policy와 차이
τ-benchTool-agent-user interaction과 policyDomain·backend state가 제품과 차이

Leaderboard rank는 시간에 따라 바뀌며 model version과 harness도 달라질 수 있습니다. Paper의 task definition을 읽고 필요한 pattern을 product suite에 이식합니다.


Evaluation Dataset을 Versioned Product로 관리한다

Source Bucket

evaluation suite
  ├─ golden curated cases
  ├─ redacted production samples
  ├─ rare critical workflows
  ├─ adversarial/security cases
  ├─ counterfactual perturbations
  └─ recent failure regressions

각 case에는 source, consent/retention, annotator, expected behavior, difficulty, risk tier를 기록합니다.

Train·Tune·Test를 분리한다

  • Prompt를 고치는 development set
  • Threshold와 routing을 정하는 validation set
  • 마지막 의사결정에만 쓰는 locked test set

Test failure를 보고 prompt를 고치면 그 순간 test는 development data가 됩니다. 새 locked set을 마련하거나 exposure를 기록합니다.

Temporal Holdout

새 문서·정책·제품을 test에 넣어 memorization과 retrieval use를 구분합니다.

training/public cutoff unknown
corpus documents created after cutoff candidate
  → answer requires supplied evidence

Model cutoff 주장은 불완전할 수 있으므로 private synthetic entities와 versioned internal documents도 사용합니다.

Slice

평균을 해석 가능한 부분집합으로 나눕니다.

  • Korean/English/cross-lingual
  • Short/medium/long context
  • Single-hop/multi-hop
  • Answerable/unanswerable/conflicting
  • Read-only/write tool
  • Single/serial/parallel tool
  • Low/high risk
  • New/returning session
  • Clean/adversarial evidence

Slice가 너무 작으면 score 변동이 큽니다. Case 수와 confidence interval을 함께 보여 줍니다.

중복과 Leakage

  • Near-duplicate query와 document를 제거합니다.
  • 같은 source document가 train과 test에 걸치지 않도록 group split합니다.
  • Public benchmark 문항을 prompt example로 쓰지 않습니다.
  • Production paraphrase가 동일한 fact를 반복하는지 확인합니다.
  • Judge prompt에 reference answer가 불필요하게 노출되지 않게 합니다.

Repeated Trial

Temperature 0도 provider·kernel·batching에 따라 완전한 determinism이 보장되지 않을 수 있습니다. Agent trajectory는 tool timing으로 갈라집니다.

for each critical case:
  run N independent trials
  report success@1
  report pass rate
  report worst failure class

pass@k는 여러 번 시도 중 하나만 성공하는 metric이라 single-attempt production success와 다릅니다. 정확한 sampling estimator와 use case를 명시합니다.


RAG를 Claim과 Evidence 단위로 평가한다

Retrieval Context Precision과 Recall

Gold evidence가 있다면 retrieved chunk 중 관련 chunk 비율과 필요한 evidence가 검색됐는지 봅니다. 하지만 annotation granularity와 multiple valid evidence를 고려합니다.

Claim Decomposition

답을 atomic factual claim으로 나눕니다.

answer:
  “정책 A는 7월 1일부터 적용되고 한도는 50만원이다.”

claims:
  c1: policy A effective date = July 1
  c2: policy A limit = 500,000 KRW

각 claim에 supporting evidence id를 연결합니다.

Grounded Precision

grounded precision
  = supported answer claims / all answer claims

Evidence Coverage

evidence coverage
  = required reference claims correctly answered
  / all required reference claims

짧게 답해 grounded precision만 높이는 모델을 coverage가 잡아냅니다.

Citation Correctness

  • Citation source가 실제 claim을 entail하는가?
  • Citation span이 너무 넓거나 다른 section인가?
  • 존재하지 않는 document id를 만들지 않았는가?
  • Access가 허용된 source만 인용했는가?

Citation format validation과 semantic support를 분리합니다.

Abstention Matrix

Case답변Abstain
AnswerableTrue positiveMissed answer
UnanswerableUnsupported answerCorrect abstention

Risk가 큰 domain에서는 unsupported answer 비용을 더 높게 둡니다.

expected risk
  = C_unsupported × P(unsupported answer)
  + C_missed × P(unnecessary abstention)

비용은 product risk owner가 정합니다.

RAGChecker 같은 Fine-grained 진단

RAGChecker는 retrieval과 generation의 세부 오류를 나눠 진단하는 framework를 제안합니다. 점수 하나보다 다음 causal 질문이 중요합니다.

wrong answer
  ├─ evidence not retrieved
  ├─ evidence retrieved but omitted from context
  ├─ evidence present but model ignored it
  ├─ model added unsupported claim
  └─ evaluator mis-scored a valid answer

모델 교체로 해결할 수 있는 failure와 retriever·prompt·evaluator를 고쳐야 하는 failure를 분리합니다.


Tool Trajectory를 State Transition으로 평가한다

Final State가 Ground Truth다

예약 agent 예시:

initial state:
  booking = none
  available slots = [10:00, 11:00]

user goal:
  book 11:00 after confirmation

expected final state:
  booking = 11:00
  confirmation recorded = true
  duplicate charges = 0

말로 “예약했습니다”라고 해도 backend state가 바뀌지 않으면 실패입니다.

Tool Call 단계별 Metric

  • Correct tool selection
  • Argument exact/semantic match
  • Required clarification
  • Authorization and confirmation
  • Dependency-respecting order
  • No unnecessary calls
  • Error recovery
  • Final state correctness
  • Duplicate side-effect count

Exact Match만으로 부족한 경우

Date format이나 argument 순서는 달라도 semantic state가 같을 수 있습니다. 반대로 JSON exact match가 맞아도 stale resource id를 사용하면 잘못된 action입니다.

evaluate at three layers:
  syntax: schema valid
  semantics: arguments mean the intended action
  state: sandbox reached the correct authorized state

Sandboxed Side Effect

Evaluation에서는 실제 결제·메일·삭제를 실행하지 않습니다.

  • Deterministic fake backend
  • Versioned initial state
  • Idempotency key
  • Permission model
  • Failure injection
  • Event log와 final-state assertion

Shadow에서도 write tool은 dry-run 또는 mock으로 치환합니다.

Long-horizon Agent 평가

Single-turn function call이 좋아도 여러 단계에서 실패가 누적됩니다.

if per-step success probability = p
and independent steps = n  # 단순 설명 가정
episode success ≈ pⁿ

실제 step은 독립이 아니지만 작은 per-step error도 긴 episode에서 크게 나타난다는 직관을 줍니다.

  • Early irreversible action
  • Wrong state carried forward
  • Repeated failed retry
  • Lost user constraint
  • Tool result hallucination
  • Premature finish

Trajectory failure taxonomy를 유지합니다.


LLM-as-a-Judge를 Calibration한다

Open-ended 답변은 exact match가 어렵지만 judge model도 측정 도구이므로 오류가 있습니다.

Judge Contract

Rubric를 분해합니다.

score separately:
  correctness
  grounding
  completeness
  instruction following
  style
  safety

한 번에 “1~10점”을 묻는 것보다 evidence와 실패 이유를 구조화합니다.

Blind Pairwise

Model 이름을 숨기고 candidate A/B 순서를 randomize합니다. Position bias를 보기 위해 일부 pair는 순서를 뒤집습니다.

Human Calibration Set

Domain expert가 label한 subset에서 judge의 precision·recall·agreement를 측정합니다.

  • High-risk false pass
  • Valid alternative answer false fail
  • Citation entailment disagreement
  • Korean nuance와 politeness
  • Judge model과 candidate family의 self-preference

Threshold를 조정하고 불확실 case는 human review로 보냅니다.

Judge Version도 Candidate Identity다

Judge model·prompt·temperature가 바뀌면 과거 score와 직접 비교할 수 없습니다. Judge upgrade 전후에 calibration set을 모두 재실행합니다.

Reference와 Evidence를 함께 준다

Judge가 자신의 parametric knowledge로 “맞다”고 판단하지 않도록 allowed evidence와 rubric를 제공합니다. Reference answer가 유일한 표현이라고 강제하지 않고 equivalence rule을 둡니다.

Human Evaluation

Human review는 적은 sample이라도 다음에 필요합니다.

  • Judge calibration
  • High-risk false pass audit
  • New failure taxonomy 발견
  • Tone·helpfulness·trust 평가
  • Canary ambiguous outcome

Annotator instruction, training, double annotation, disagreement adjudication을 기록합니다. 개인정보가 포함된 production trace는 최소화·redaction·access control을 적용합니다.


Hard Gate를 먼저 적용한다

가중 평균 전에 배포 불가 조건을 검사합니다.

hard gates example:
  critical unauthorized tool calls = 0
  cross-tenant leakage = 0
  structured output validity ≥ floor
  Korean groundedness ≥ floor
  p95 TTFT ≤ SLO
  license and residency approved
  rollback artifact available

값은 예시이며 실제 threshold는 risk owner가 승인합니다.

평균이 위험한 이유

candidate A:
  general QA 95
  destructive-tool safety 40

candidate B:
  general QA 90
  destructive-tool safety 99

단순 평균으로 A가 이겨도 결제 agent에는 배포할 수 없습니다. Critical slice floor가 먼저입니다.

통과 후보의 Utility를 계산한다

Metric 방향과 scale을 정규화합니다.

utility(m)
  = w_quality × Q(m)
  + w_tool × T(m)
  + w_grounding × G(m)
  − w_latency × L(m)
  − w_cost × C(m)
  − w_risk × R(m)

가중치는 이해관계자 합의와 sensitivity analysis가 필요합니다. 작은 weight 변화로 winner가 바뀐다면 단일 winner가 아니라 Pareto set을 유지합니다.

Pareto Frontier

다른 후보가 모든 축에서 같거나 더 좋고 적어도 한 축에서 더 좋은 후보는 dominated입니다.

candidate A: quality high, cost high
candidate B: quality medium, cost low
candidate C: quality lower than B, cost higher than B

C is dominated by B
A and B can both remain on the frontier

Frontier 위 후보를 traffic tier나 task router에 나눠 쓸 수 있습니다.

Routing 전략

  • 작은 model로 simple grounded QA
  • 큰 model로 multi-hop·ambiguous request
  • 별도 model로 tool argument repair
  • Deterministic policy engine으로 authorization

Router 자체의 false route와 추가 latency를 평가합니다. 큰 model fallback 비율이 높으면 예상 비용 절감이 사라집니다.

Confidence Interval과 유의성

두 후보 점수 차이가 sampling noise보다 작은지 확인합니다.

  • Paired bootstrap over identical cases
  • Success proportion confidence interval
  • Per-slice sample count
  • Multiple-run variance
  • Judge disagreement interval

평균 0.5점 차이를 과도하게 해석하지 않습니다. Practical effect size와 risk를 봅니다.

비용을 성공 단위로 계산한다

expected episode cost
  = input token cost
  + output token cost
  + cached token cost
  + retrieval / rerank cost
  + tool API cost
  + retry and failure cost
  + serving idle / infrastructure allocation

cost per successful episode
  = total cost / successful episodes

싼 model이 tool 오류로 세 번 retry하면 성공당 비용은 더 높을 수 있습니다.


Decision Table 예시

후보Critical gateGrounded taskTool statep95 latency성공당 비용결정
A통과높음높음높음높음복잡 request 후보
B통과중간높음낮음낮음기본 tier 후보
C안전 gate 실패높음낮음중간중간탈락

실제 표에는 score definition, confidence interval, dataset version, measured date, candidate manifest link를 붙입니다.

Model Card가 아니라 Decision Record를 남긴다

decision:
  id: rag-agent-model-2026-07
  owner: model-platform
  approved_at: 2026-07-16
requirements:
  task: internal-policy-rag-agent
  critical_slices: [korean, authorization, unanswerable, write-tool]
candidates:
  - candidate-a-v5
  - candidate-b-v4
  - candidate-c-v3
evaluation:
  suite: rag-agent-model-select-v13
  corpus_snapshot: policy-corpus-2026-07-01
  runner_commit: abc1234
result:
  default: candidate-b-v4
  escalation: candidate-a-v5
  rejected:
    candidate-c-v3: authorization-gate-failed
rollout:
  plan: rollout-2026-07-model-b
  rollback: candidate-b-v3
revisit_when:
  - model snapshot changes
  - tool schema changes
  - production slice drifts
  - quarterly review

Release 전에 Compatibility를 검증한다

Model 교체는 prompt를 그대로 복사하는 일이 아닙니다.

Chat Template

Role name, system message 위치, assistant prefill, tool call encoding이 다릅니다.

Tool Protocol

  • Function schema subset
  • Parallel call 표현
  • Tool result role
  • Call id 연결
  • Structured-output와 tool calling 동시 사용
  • Empty argument와 null semantics

Tokenizer와 Context Budget

같은 prompt가 더 많은 token이 되어 truncation boundary가 바뀔 수 있습니다. Evidence가 잘리는 순서와 max output reserve를 재계산합니다.

Safety Behavior

새 model은 refusal style과 policy 경계가 다릅니다. Prompt로 기존 behavior를 억지로 복제하기보다 product policy를 deterministic layer에 두고 model-specific instruction을 조정합니다.

Output Style

더 장황한 model은 비용과 latency를 키우고 citation parser를 흔들 수 있습니다. Style metric과 max token만이 아니라 task completeness를 함께 봅니다.

Release Artifact

  • Candidate manifest
  • Prompt·tool schema bundle
  • Retrieval/index snapshot
  • Evaluation report와 raw trace pointer
  • Security review
  • License·privacy approval
  • Serving capacity report
  • Dashboard와 alert
  • Canary routing config
  • Rollback target과 command/runbook
  • Owner와 on-call

하나라도 재생성할 수 없다면 rollback과 사후 분석이 약해집니다.


1단계: Offline Gate

Locked suite를 같은 runner에서 실행합니다.

  1. Candidate identity와 dependency를 검증합니다.
  2. Deterministic contract test를 통과합니다.
  3. Component와 task eval을 실행합니다.
  4. Stateful sandbox trajectory를 실행합니다.
  5. Adversarial·failure injection을 실행합니다.
  6. Target load에서 latency·cost를 측정합니다.
  7. Hard gate와 slice floor를 적용합니다.
  8. Human audit sample을 검토합니다.

Offline 통과는 production exposure의 필요조건이지 충분조건이 아닙니다.

2단계: Shadow

실제 request를 candidate에도 복제하지만 candidate 결과는 사용자나 실제 tool에 영향을 주지 않습니다.

production request
  ├─ control → user + authorized tools
  └─ shadow candidate → dry-run tools + hidden evaluation

Shadow의 안전 조건

  • Write tool은 mock/dry-run입니다.
  • Candidate output이 user에게 섞이지 않습니다.
  • 개인정보 처리와 provider 전송이 승인돼야 합니다.
  • 두 배 호출 비용과 quota를 예산에 반영합니다.
  • Shadow log retention과 access를 제한합니다.

무엇을 얻나

  • 실제 prompt length와 language 분포
  • Template/parser 호환성
  • Provider error와 tail latency
  • Control/candidate disagreement
  • Offline corpus가 놓친 failure pattern

Shadow의 한계

사용자가 candidate 답에 반응하지 않으므로 multi-turn behavior를 완전히 관찰할 수 없습니다. Tool side effect도 dry-run이라 real-world race를 놓칠 수 있습니다.

3단계: Canary

작은 실제 traffic에 candidate 결과를 노출합니다.

Routing Unit

Request 단위로 model이 바뀌면 같은 session에서 style·tool state가 흔들릴 수 있습니다. 필요한 경우 user/session/episode hash로 sticky assignment합니다.

bucket = hash(stable_subject_id, experiment_id) mod 10000
candidate if bucket < canary_basis_points

개인정보 원문을 hash input으로 log하지 않고 approved stable id를 사용합니다.

Canary Cohort

  • 내부 사용자 또는 opt-in
  • Low-risk read-only workflow
  • 특정 region·tenant
  • Supported language·context 범위

Easy traffic만 보내면 full rollout을 대표하지 못합니다. Risk를 낮추되 target distribution 차이를 보고합니다.

Guardrail

  • Tool authorization은 기존 deterministic policy 유지
  • High-risk write는 confirmation 또는 control model fallback
  • Output schema failure 시 fail-closed
  • Citation/evidence validator
  • Budget·timeout cap
  • Kill switch

4단계: Progressive Ramp

예시:

1% → 5% → 25% → 50% → 100%

보편적인 비율이 아닙니다. 각 단계는 최소 sample, 시간대 coverage, critical slice exposure, error budget을 충족한 뒤 진행합니다. 매우 낮은 traffic에서는 1%로 통계적 신호를 얻지 못하므로 cohort-based pilot이 낫습니다.

단계별 비교

  • Task/episode success proxy
  • User correction·regeneration·escalation
  • Grounding audit sample
  • Tool error와 unauthorized attempt
  • TTFT·ITL·E2E
  • Cost per successful episode
  • Provider/runtime error
  • Slice별 regression

전체 평균뿐 아니라 canary와 control의 traffic mix를 보정합니다.

5단계: Full Rollout 뒤에도 Experiment는 끝나지 않는다

  • Control holdback을 일정 기간 유지할 수 있습니다.
  • Old artifact와 prompt를 rollback window 동안 보존합니다.
  • New baseline을 고정합니다.
  • 발견된 failure를 regression suite에 추가합니다.
  • Cache와 session state의 version compatibility를 확인합니다.

Rollback을 배포 전에 설계한다

Trigger

rollback if any:
  critical safety violation count > 0
  tool side-effect duplicate > 0
  schema validity below floor
  SLO error budget burn exceeds threshold
  cost per success exceeds cap
  provider/runtime error exceeds threshold

Threshold는 예시입니다. Critical event는 평균 window를 기다리지 않고 즉시 stop할 수 있습니다.

Rollback 대상

  • 이전 model artifact
  • 이전 prompt·tool schema
  • 이전 routing policy
  • Compatible retriever/index
  • Previous safety configuration

Model만 되돌리고 새 tool schema를 남기면 control model이 해석하지 못할 수 있습니다. Release bundle 단위 rollback을 준비합니다.

In-flight Request

  • 이미 stream한 response를 중간에 model로 바꿀 것인가?
  • Tool call을 실행한 episode를 재시도할 것인가?
  • Duplicate side effect를 idempotency key로 막는가?
  • Sticky session을 old model로 계속 drain할 것인가?

일반적으로 한 generation 중 model hot-swap은 피하고, new admission을 rollback target으로 전환하며 in-flight를 drain 또는 안전 취소합니다.

Cache Compatibility

KV/prefix cache는 model weight·tokenizer·adapter가 바뀌면 재사용할 수 없습니다. Response cache도 model version과 prompt identity를 key에 넣습니다.

cache namespace
  = model + tokenizer + template + adapter + safety + corpus version

Fallback은 Rollback과 다르다

  • Fallback: 개별 request failure 때 다른 model/provider로 보냅니다.
  • Rollback: Release 전체를 이전 stable bundle로 되돌립니다.

Fallback은 outage를 줄이지만 behavior·privacy·cost가 달라집니다.

  • 같은 data residency를 만족하는가?
  • Tool protocol이 호환되는가?
  • 이미 실행한 side effect를 반복하지 않는가?
  • Context와 generated prefix를 안전하게 전달하는가?
  • Fallback loop를 막는가?

Fallback 성공률과 품질을 별도 평가합니다.


Production Trace에 Model Identity를 넣는다

End-to-end trace 예시:

agent.episode
  attributes:
    release_bundle
    candidate_id
    prompt_version
    corpus_snapshot
    experiment_bucket
    tenant_class  # 최소화된 approved label

  spans:
    retrieve
    rerank
    pack_context
    model.prefill_decode
    tool.validate
    tool.execute
    answer.verify

Sensitive prompt·document·tool result를 무조건 원문 log하지 않습니다. Hash, redacted field, sampled encrypted store, role-based access를 사용합니다.

Online Metric의 Causal 함정

User Rating

응답을 평가한 사용자만의 선택 편향이 있습니다. Negative event가 rating으로 이어지는 비율도 cohort마다 다릅니다.

Regeneration

나쁜 답 때문에 regenerate할 수도 있지만 다른 스타일을 보고 싶은 것일 수 있습니다.

Task Completion

외부 system 상태로 확인할 수 있으면 강한 signal이지만 attribution window와 duplicate action을 관리해야 합니다.

Deflection

Human support 전환이 줄어도 사용자가 포기했을 수 있습니다.

Proxy 하나를 최적화하지 않고 여러 signal과 audit sample을 결합합니다.

Drift를 감시한다

Input Drift

  • 언어·domain 비율
  • Prompt·context length
  • Tool 종류
  • Unanswerable 비율
  • Document freshness
  • Attack pattern

Behavior Drift

  • Groundedness audit
  • Abstention·refusal rate
  • Tool selection·argument failure
  • Citation coverage
  • Output length와 style
  • Retry·fallback

System Drift

  • Provider snapshot/alias
  • Runtime·kernel
  • Quantization
  • Prompt·tool schema
  • Retriever/index
  • Price·quota·region

Model이 같아도 system component가 바뀌면 re-evaluation을 trigger합니다.

Production Failure를 Eval로 되돌린다

incident
  → redact and minimize
  → reproduce in sandbox
  → assign failure taxonomy
  → create deterministic or stochastic regression case
  → add to development suite
  → reserve related unseen variants for locked test

그 사건 하나를 그대로 test에 추가하고 고친 뒤 끝내면 overfitting하기 쉽습니다. 같은 원인의 counterfactual variant를 만듭니다.


RAG Agent 모델 선택 실전 예시

요구사항

task:
  Korean internal policy QA + read-only HR tools

must:
  cite authorized evidence
  abstain when policy is absent
  ask confirmation before personal-data lookup
  finish under latency and cost SLO

후보 실험

candidate A:
  larger hosted model

candidate B:
  smaller hosted model

candidate C:
  self-hosted quantized model + domain adapter

1. Given-evidence Test

Retriever 영향을 제거하고 동일 evidence를 줘 grounding과 Korean generation을 비교합니다.

2. Retrieval-coupled Test

동일 index에서 query rewrite, source selection, context use를 평가합니다.

3. Tool Sandbox

사용자 id ambiguity, authorization deny, timeout, empty result, confirmation case를 실행합니다.

4. Serving Replay

Prompt/output histogram과 burst arrival를 재현해 TTFT·ITL·cost를 측정합니다.

5. Gate

Cross-tenant leakage, confirmation bypass, unsupported critical claim이 있는 후보는 탈락시킵니다.

6. Pareto와 Routing

후보 B가 common QA의 default, 후보 A가 multi-hop escalation이 될 수 있습니다. 후보 C는 data residency가 강점이지만 quality floor를 통과할 때만 frontier에 남습니다.

7. Shadow와 Canary

Read-only tool로 shadow한 뒤 low-risk cohort에서 sticky canary를 실행합니다. Personal-data lookup은 deterministic confirmation gate를 그대로 둡니다.

선택 결과가 “한 모델”일 필요는 없다

System의 역할별로 다른 model을 선택할 수 있습니다.

query classifier: small deterministic model
retrieval generator: grounded general model
complex planner: larger model
tool policy: non-LLM rules
answer judge: calibrated separate model
fallback: approved alternate provider/model

하지만 component가 늘면 failure surface, latency, cost, observability도 늘어납니다. 각 추가 model이 measurable gain을 주는지 ablation합니다.


최신 Benchmark를 읽는 법

HELM의 교훈

Accuracy 하나가 아니라 calibration·robustness·fairness·toxicity·efficiency 등 여러 metric과 scenario를 함께 보자는 holistic evaluation 관점을 제공합니다.

LongBench에서 HELMET으로

LongBench는 bilingual·multitask long-context 평가를 체계화했습니다. HELMET은 2025년 ICLR 연구로 synthetic retrieval task의 높은 점수가 다양한 downstream long-context ability를 보장하지 않는 문제를 분석합니다. “Context 128K 지원” 대신 제품형 task와 length curve를 평가해야 합니다.

AgentBench에서 Stateful Tool Eval로

AgentBench는 여러 interactive environment에서 LLM agent를 비교했습니다. ToolSandbox와 τ-bench는 대화·state·user interaction을 더 정교하게 평가합니다. BFCL의 2025년 ICML 논문은 function calling을 serial·parallel call에서 stateful multi-step·abstention까지 연결합니다.

2026년 새 Preprint를 대하는 태도

2026년에는 service-agent graph, enterprise RAG diagnostic, security 등 더 domain-specific한 benchmark preprint가 이어지고 있습니다. 최신이라는 이유로 즉시 표준으로 채택하지 않습니다.

  1. Task와 label construction을 읽습니다.
  2. Product failure를 실제로 대표하는지 확인합니다.
  3. Data leakage와 judge reliability를 봅니다.
  4. Code·data로 재현 가능한지 확인합니다.
  5. 필요한 case pattern만 내부 locked suite에 이식합니다.

Paper ranking을 production guarantee로 바꾸지 않는 것이 핵심입니다.

흔한 오해와 처방

1. Leaderboard 1등이 우리 제품에서도 1등이다

Task, prompt, language, tool, serving 조건이 다릅니다.

처방: Public score는 shortlist에만 쓰고 product suite에서 재평가합니다.

2. Context Window가 크면 RAG가 좋아진다

긴 입력 수용과 긴 evidence 활용은 다릅니다.

처방: Evidence position·distractor·multi-hop·length curve를 평가합니다.

3. JSON Validity가 Tool 능력이다

잘못된 tool과 valid argument로 위험한 action을 할 수 있습니다.

처방: Syntax·semantics·authorization·final state를 모두 채점합니다.

4. 평균 점수가 높으면 배포 가능하다

Critical slice failure가 평균에 가립니다.

처방: Hard gate와 slice floor를 평균보다 먼저 적용합니다.

5. LLM Judge가 Human Label을 대체한다

Judge도 bias와 version drift가 있습니다.

처방: Human calibration, blind pairwise, disagreement audit를 운영합니다.

6. Input/Output Token 단가가 Model 비용이다

Retry, tool, retrieval, cache, GPU idle, failure가 빠집니다.

처방: Cost per successful episode와 SLO-adjusted cost를 계산합니다.

7. Offline Eval 통과가 배포 성공이다

실제 traffic과 queue·provider failure·user interaction이 다릅니다.

처방: Shadow, canary, ramp, online audit를 거칩니다.

8. Shadow는 위험이 없다

민감 데이터를 새 provider에 보내고 write tool을 실수로 실행할 수 있습니다.

처방: Privacy approval, dry-run tool, output isolation을 검증합니다.

9. Rollback은 Model Alias만 바꾸면 된다

Prompt·tool schema·cache·retriever가 호환되지 않을 수 있습니다.

처방: Versioned release bundle 전체를 되돌립니다.

10. Fallback이면 Reliability가 해결된다

다른 model은 behavior·privacy·cost가 다르고 side effect를 반복할 수 있습니다.

처방: Fallback 자체를 end-to-end 평가하고 idempotency를 보장합니다.

Production 체크리스트

  • Product goal, success unit, latency·cost·risk constraint를 testable하게 썼다.
  • Hosted/self-hosted candidate identity를 manifest로 고정했다.
  • Model·tokenizer·template·tool schema·runtime version을 함께 기록한다.
  • License, commercial use, privacy, residency, retention을 검토했다.
  • 한국어·domain·cross-lingual slice가 production 분포를 반영한다.
  • Tokenizer별 실제 prompt·tool schema token과 비용을 계산했다.
  • Advertised context가 아니라 effective evidence use를 length curve로 평가했다.
  • Answerable·unanswerable·conflicting evidence case가 있다.
  • Claim grounding, completeness, citation correctness를 분리한다.
  • Tool syntax·semantics·authorization·final state를 모두 채점한다.
  • Write tool은 versioned sandbox와 idempotency key에서 평가한다.
  • Prompt injection, tool failure, permission deny를 포함한 adversarial suite가 있다.
  • Deterministic contract부터 online까지 evaluation pyramid가 있다.
  • Development·validation·locked test set을 분리했다.
  • Group/temporal split과 near-duplicate audit를 수행했다.
  • Critical slice에 충분한 case 수와 confidence interval이 있다.
  • Stochastic candidate는 repeated trial과 success@1을 보고한다.
  • LLM judge를 human-labeled set으로 calibration했다.
  • Judge model·prompt·rubric version을 고정했다.
  • Hard gate와 slice floor를 weighted average보다 먼저 적용한다.
  • 통과 후보의 Pareto frontier와 weight sensitivity를 확인했다.
  • Input/output 가격이 아닌 성공 episode당 총비용을 계산했다.
  • Target arrival trace에서 TTFT·ITL·episode latency를 측정했다.
  • Decision record에 candidate, suite, corpus, code, 이유를 남겼다.
  • Chat template·tool protocol·token budget migration test가 있다.
  • Release bundle과 이전 stable rollback bundle을 보존한다.
  • Shadow output은 user와 real write tool에서 완전히 격리된다.
  • Canary assignment가 session/episode에 필요하면 sticky하다.
  • Canary cohort의 traffic mix 차이를 보고한다.
  • Ramp 단계마다 sample·시간·slice·error budget 조건이 있다.
  • Critical safety·side-effect event의 즉시 kill switch가 있다.
  • In-flight request, session, cache의 rollback semantics를 정의했다.
  • Fallback model의 privacy·tool·idempotency를 별도 평가했다.
  • Trace에 release bundle과 model identity가 있다.
  • Sensitive prompt·evidence·tool result logging을 최소화했다.
  • Input·behavior·system drift를 slice별로 감시한다.
  • Production incident를 재현 가능한 regression case로 환원한다.
  • Model·prompt·retriever·tool 변경이 재평가를 trigger한다.

스스로 확인하기

  1. 모델 선택을 constrained optimization으로 정의하면 leaderboard 선택과 무엇이 달라지는가?
  2. Hosted model alias만으로 candidate identity를 재현할 수 없는 이유는 무엇인가?
  3. Advertised context length와 effective long-context ability를 어떻게 구분해 평가하는가?
  4. RAG answer를 claim-evidence 단위로 나누면 어떤 failure를 진단할 수 있는가?
  5. Tool call의 syntax가 맞아도 episode가 실패할 수 있는 예시를 들 수 있는가?
  6. LLM-as-a-judge를 human label로 calibration해야 하는 이유는 무엇인가?
  7. Hard gate, slice floor, weighted utility는 어떤 순서로 적용하는가?
  8. Pareto frontier에 여러 후보를 남기는 것이 합리적인 경우는 언제인가?
  9. Shadow와 canary는 실제 output과 side effect 관점에서 어떻게 다른가?
  10. Rollback target에 prompt·tool schema·retriever까지 포함해야 하는 이유는 무엇인가?
  11. Fallback과 rollback을 구분하고 각각의 idempotency 위험을 설명할 수 있는가?
  12. Production failure 하나를 suite에 추가할 때 overfitting을 피하는 방법은 무엇인가?

이번 10편을 하나의 흐름으로 연결하기

이 시리즈는 model artifact가 만들어지고 선택되어 production에서 운영되는 전체 수명을 다뤘습니다.

  1. Pretraining Data Pipeline — 학습 data의 출처·정제·중복·governance
  2. Scaling Laws — parameter·token·compute budget의 실험 설계
  3. Modern Decoder Architecture — RMSNorm·RoPE·SwiGLU·GQA·MoE
  4. Instruction Tuning·SFT — message·loss mask·template·data quality
  5. Preference Optimization — RLHF·DPO·KTO·GRPO의 preference signal
  6. LoRA·QLoRA·PEFT — frozen base와 adapter 학습·merge·serving
  7. Quantization — GPTQ·AWQ·SmoothQuant·FP8·KV cache
  8. Distributed Training — DDP·ZeRO·FSDP·TP·PP·CP
  9. Efficient Serving — prefill·decode·PagedAttention·scheduler·SLO
  10. 현재 글 — 후보를 평가하고 shadow·canary·rollback으로 운영

RAG agent를 만들 때 모든 model을 직접 pretrain할 필요는 없습니다. 그러나 data·architecture·tuning·quantization·serving이 어떤 trade-off를 만드는지 알아야 benchmark 차이를 해석하고, 실패를 model·retrieval·harness·runtime 중 올바른 층에서 고칠 수 있습니다.

마지막 실습

작은 model 두 개나 provider model 두 개를 골라 다음 artifact를 직접 만듭니다.

artifacts/
  requirements.md
  candidates/
    candidate-a.yaml
    candidate-b.yaml
  eval/
    cases.jsonl
    rubric.yaml
    results.jsonl
    report.md
  rollout/
    shadow-plan.yaml
    canary-plan.yaml
    rollback-runbook.md
  1. Product query 30개와 unanswerable·tool failure·injection case를 추가합니다.
  2. 두 후보에 동일 evidence와 tool sandbox를 제공합니다.
  3. Grounding·tool final state·latency·cost를 case별로 기록합니다.
  4. Critical gate를 먼저 적용합니다.
  5. 통과 후보의 Pareto table을 만듭니다.
  6. Side effect 없는 shadow plan을 씁니다.
  7. Canary stop 조건과 rollback bundle을 실제 명령 수준으로 적습니다.
  8. 실패 하나를 재현 test와 counterfactual variant로 바꿉니다.

이 artifact를 만들 수 있다면 model 선택을 감상이나 홍보 문구가 아니라 반복 가능한 engineering decision으로 바꾼 것입니다.

다음 시리즈에서는 선택한 model이 답을 만드는 과정의 품질을 더 깊게 다룹니다. 첫 글은 Chain-of-Thought 입문: LLM 추론문과 실제 근거 구분하기입니다. 추론문을 그대로 신뢰하지 않고 정답·설득력·충실성을 분리해 평가하는 것부터 시작합니다.

참고자료