Claude Architect · 강의

토큰, 컨텍스트 창 및 비용

매 턴마다 전체 이력을 전송하는 이유와 그 비용을 알아봅니다

레슨 4/413개 단계

토큰, 컨텍스트 창 및 비용은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Claude Has No Memory

Here is the most important idea in this lesson: the Claude API keeps NO state between turns.

The model does not remember your last message. Each API call starts fresh. So how do chatbots seem to remember?

You send the full conversation history in every single request. The messages field carries the whole back-and-forth, every time.

What a Request Carries

A Claude API request has a few key fields:

  • model — which Claude model to use
  • max_tokens — the cap on the reply length
  • system — the system prompt
  • messages — the FULL history every turn
  • tools / tool_choice — optional tool config

Notice messages grows over time. Turn 1 sends 1 message. Turn 10 sends all 19 prior messages plus the new one.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="You are a support agent.",
    messages=[
        {"role": "user", "content": "My order is late."},
        {"role": "assistant", "content": "I can help. What is your order ID?"},
        {"role": "user", "content": "It's #4821."},
    ],
)

What Is a Token?

Models do not read characters or whole words. They read tokens — small chunks of text.

A rough guide: one token is about 4 characters of English, or roughly 3/4 of a word. "unhappiness" might split into "un", "happiness". Punctuation and spaces count too.

Tokens matter because you pay per token and the context window is measured in tokens, not words.

Input vs Output Tokens

Every request has two token counts that are billed differently:

  • Input tokens — everything you send: system + tools + the full messages history.
  • Output tokens — what the model generates in its reply.

Output tokens usually cost more per token than input tokens. But because the full history is resent each turn, input tokens are what quietly balloon in long conversations.

The Context Window

The context window is the maximum number of tokens a model can handle in one request — input plus output combined.

If your full history plus the requested max_tokens exceeds the window, the request fails. The window is a hard ceiling, not a suggestion.

This is why long-running chats and big tool outputs eventually hit a wall: the resent history keeps growing toward the limit.

Cost Grows With History

Because you resend the whole history each turn, cost does not grow linearly with the conversation — it grows roughly with the square of its length.

Turn 1 bills a few tokens. Turn 20 bills all 19 prior turns again, plus the new one. A 10-message chat re-bills the early messages 10 times over its life.

For an architect, this means: a chatty agent that never trims its history is an expensive agent.

# Rough illustration of resent input growing each turn
history = []
for turn in range(1, 6):
    history.append({"role": "user", "content": user_msg(turn)})
    resp = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=512,
        messages=history,  # ENTIRE history resent every turn
    )
    history.append({"role": "assistant", "content": resp.content})
    print("turn", turn, "input_tokens", resp.usage.input_tokens)

Measure Before You Optimize

Every response includes a usage object reporting input_tokens and output_tokens. This is your ground truth for cost.

You can also count tokens before sending, so you can predict cost and check you are under the window — without paying for a full generation.

Rule of thumb: instrument token usage in production. Aggregate cost numbers hide which conversations or tool calls are the expensive ones.

count = client.messages.count_tokens(
    model="claude-sonnet-4-5",
    system="You are a support agent.",
    messages=history,
)
print("input tokens before send:", count.input_tokens)

resp = client.messages.create(model="claude-sonnet-4-5", max_tokens=512, messages=history)
print("billed:", resp.usage.input_tokens, resp.usage.output_tokens)

Tool Output Bloats Context

In agentic loops, tool results are appended to the history and resent on every following turn. A verbose tool that returns a 5,000-token JSON blob keeps costing you for the rest of the conversation.

The fix is to trim verbose tool output to the relevant fields before appending it. Do not store a whole API dump in context when three fields are all the model needs.

raw = lookup_order(order_id)  # huge JSON
# Trim to what the model actually needs
tool_result = {
    "order_id": raw["id"],
    "status": raw["status"],
    "eta": raw["estimated_delivery"],
}
history.append({
    "role": "user",
    "content": [{"type": "tool_result", "tool_use_id": tu_id,
                 "content": json.dumps(tool_result)}],
})

Summarize to Stay in Budget

For long conversations, you can replace old turns with a compact progressive summary to keep the history small and under the window.

But beware: summarization makes numbers, percentages, and dates vague. The model rewrites "refund of $482.10 on 2026-03-14" into "a refund last spring."

The architect's fix: pull transactional facts into a separate verbatim "case facts" block kept outside the summary, so exact values never get blurred.

Lost in the Middle

A bigger context window is not a free pass. Models attend most strongly to the start and the end of the input, and least to the middle. This is the "lost-in-the-middle" effect.

So burying a critical instruction or fact in the middle of a giant history risks it being ignored — even though you paid full price to send it.

Keep key instructions and the current task near the edges; trim the bulky middle.

Batch API for Non-Blocking Jobs

One cost lever: the Message Batches API. It is about 50% cheaper than standard requests, with up to a 24-hour processing window.

The trade-offs: there is no latency SLA, and multi-turn tool calling is NOT supported. Use custom_id to correlate requests; re-submit only the failures.

Use Batch for overnight reports and large audits. Never use it for blocking, time-sensitive, or pre-merge checks — a user is waiting on those.

batch = client.messages.batches.create(requests=[
    {"custom_id": "doc-001", "params": {
        "model": "claude-sonnet-4-5", "max_tokens": 1024,
        "messages": [{"role": "user", "content": classify(doc_1)}]}},
    {"custom_id": "doc-002", "params": {
        "model": "claude-sonnet-4-5", "max_tokens": 1024,
        "messages": [{"role": "user", "content": classify(doc_2)}]}},
])  # ~50% cheaper, up to 24h, no latency SLA

Quick Check

A production support chatbot's per-conversation cost is climbing fast as sessions get longer, even though each user reply is short. What is the primary cause, and the right architect-grade fix?

Recap: Tokens, Context & Cost

Key takeaways:

  • The API keeps no state — you resend the full messages history every turn.
  • Billing is per token, split into input (system + tools + history) and output.
  • The context window caps input + output; resent history grows toward it and cost grows roughly with the square of conversation length.
  • Measure with usage and count_tokens; trim verbose tool output to relevant fields.
  • Summarize to stay in budget, but keep exact numbers/dates in a verbatim case-facts block; watch the lost-in-the-middle effect.
  • Batch API = ~50% cheaper for non-blocking jobs only — never for time-sensitive checks.
무료로 시작

AI 튜터와 함께 Python을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
26
레슨
104

자주 묻는 질문

“토큰, 컨텍스트 창 및 비용” 강의는 무료인가요?

네 — “토큰, 컨텍스트 창 및 비용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

“토큰, 컨텍스트 창 및 비용”에서 뭘 배우나요?

매 턴마다 전체 이력을 전송하는 이유와 그 비용을 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Claude Architect을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“토큰, 컨텍스트 창 및 비용” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Claude 모델 제품군
  2. API 요청의 구조
  3. 중지 이유 이해하기
  4. 토큰, 컨텍스트 창 및 비용
← Claude Architect(으)로 돌아가기