Token Lab검색

← 모든 튜토리얼
개발자 가이드 / 03

컨텍스트 초과 디버깅: 실전 RAG 예산

요청을 분리하고 생성 공간을 예약해 컨텍스트 증가의 주요 원인을 찾습니다.

전체 예산부터 계산

요청은 마지막 사용자 메시지만이 아닙니다. 시스템 지침, 대화 기록, 검색 문서, 사용자 텍스트, 메시지와 도구의 오버헤드를 포함하고 출력 공간도 확보해야 합니다.

예제는 8,192 중 8,096을 사용해 96이 남습니다. 500토큰 문서를 추가하면 404만큼 초과합니다. 이는 설명용 숫자이며 특정 모델의 사양이 아닙니다.

Study guide & lesson outlineLEARNING CONTRACT

Understand → implement → investigate

Goal: explain the mechanism in this lesson, reproduce one example and test a failure case. Reading alone does not mark mastery.

  • Understand: state assumptions, shapes/units and a counterexample.
  • Implement: reproduce a numerical example and inspect boundaries.
  • Investigate: compare one alternative under a matched budget.

가장 큰 부분 찾기

컨텍스트 예산 도구에 각 부분을 따로 입력하면 인코딩 결과와 비중을 볼 수 있습니다. 한도 초과 예제를 불러와 경고와 큰 RAG 부분을 확인하세요.

개별 인코딩은 원인 분석에 유용하지만 최종 요청을 정확히 재현하지는 않습니다. 구분자, 메시지 형식, 도구 스키마, 미디어가 실제 사용량을 바꿀 수 있습니다. 여유를 두고 API usage와 비교하세요.

context_limit = 8192
system        =  400
history       = 1800
retrieval     = 3600
user          =  120
extra         =  128  # estimate
output        = 2048  # reserve

allocated = 400 + 1800 + 3600 + 120 + 128 + 2048
remaining = 8192 - allocated  # 96 tokens
도구에서 실행 →

작업을 유지하면서 줄이기

검색 결과가 크면 먼저 중복을 제거하고 재정렬한 뒤 관련 구절과 출처를 남기세요. 오래된 대화는 결정 사항을 유지하며 요약하고 최근 대화는 원문을 보존하세요.

수정 후 다시 계산하고 대표 질문으로 품질을 검사하세요. 시스템 제약을 조용히 잘라내지 마세요. 컨텍스트 한도와 별도로 출력 한도도 확인해야 합니다. 큰 컨텍스트가 같은 크기의 출력을 허용하는 것은 아닙니다.

참고 자료 및 구현

MATHEMATICAL REVIEW · 2026-10-26

Assumptions, implementation & acceptance

8096 of 8192 leaves 96 tokens. Adding 500 overflows by 404; to also preserve a 256-token reserve, remove 660. Provider template overhead must be measured separately.

Shared code, English mathematical explanation and key multilingual numeric passages reviewed. This is not a full translation proofread.

System + history + retrieval + user → Add template estimate + output reserve → Compare allocated total with limit → Trim retrieval while retaining reserve
Mechanism map: follow the transformations from top to bottom.

Before running: predict a boundary case

8096 of 8192 leaves 96 tokens. Adding 500 overflows by 404; to also preserve a 256-token reserve, remove 660. Provider template overhead must be measured separately.

Hint: isolate the assumption

Keep the baseline input fixed, change one parameter or boundary, and compare both the numerical result and the claimed units. A passing example verifies this fixture only.

Minimal executable example

Save the example and linked modules in one folder. Use Node.js 22 or newer, then run node context-budget-rag.mjs. No third-party runtime dependencies.

const allocated=400+1800+3600+120+128+2048;
console.log(allocated,8192-allocated,allocated+500-8192); // 8096 96 404
console.assert(allocated+500-660+256===8192);

Test and transfer

8096 of 8192 leaves 96 tokens. Adding 500 overflows by 404; to also preserve a 256-token reserve, remove 660. Provider template overhead must be measured separately.

Record input, code version, expected result and observed result in the notebook below. Then construct a counterexample that violates the assumption above and explain why the original conclusion no longer follows.

Download complete kit (.tar.gz) · Complete reference kit and regression checks

Predict, test and keep evidence

Before revealing an answer, predict one result. After the exercise, record the discrepancy and a transfer test. Saved locally across language editions.

Open notebook / export / clear →

The mathematical review scope is recorded per lesson. It does not establish empirical paper reproduction; report suspected errors in your notes. Review scope