토큰 사용량 및 비용 모니터링
에이전트가 실시간으로 소비하는 토큰 수와 비용을 측정하고, 예산을 설정하며, 비용이 많이 드는 단계를 찾아 프로덕션 지출을 최적화합니다.
토큰 사용량 및 비용 모니터링은(는) CoddyKit의 무료 AI Agents with LangChain & Autonomous Workflows 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents with LangChain & Autonomous Workflows 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Track Tokens and Cost
Agents that loop, retry, or use long context can quietly become expensive. Without visibility you only discover the bill at month end.
Token and cost monitoring turns spend into a metric you can watch, alert on, and optimize.
Prompt vs Completion Tokens
Every call splits into:
- Prompt tokens: everything you send in (system prompt, context, history)
- Completion tokens: what the model generates
They are usually priced differently, so track them separately.
The Callback Approach
LangChain exposes usage via callbacks. get_openai_callback aggregates tokens and cost for everything inside its context block.
from langchain_community.callbacks import get_openai_callback
with get_openai_callback() as cb:
result = agent.invoke({'input': 'Summarize the report'})
print(cb.total_tokens, cb.total_cost)Reading the Breakdown
The callback object also exposes the split, which is what you log per request.
print('prompt:', cb.prompt_tokens)
print('completion:', cb.completion_tokens)
print('cost USD:', cb.total_cost)Usage Inside Responses
Many chat models also attach a usage_metadata field to the response, useful when you call the model directly without a callback.
resp = llm.invoke('Hello there')
print(resp.usage_metadata)Estimating Before You Send
To stay under a budget, estimate tokens before calling the model using a tokenizer like tiktoken. This catches oversized prompts early.
import tiktoken
enc = tiktoken.encoding_for_model('gpt-4o-mini')
n = len(enc.encode(prompt_text))
print('approx tokens:', n)Setting Budgets
Define a per-request and per-user token budget. If an estimate exceeds it, trim context, lower k in retrieval, or reject the request before paying for it.
MAX_TOKENS = 6000
if n > MAX_TOKENS:
raise ValueError('Request exceeds token budget')Per-Step Attribution
Agents make many sub-calls: tool selection, tool output processing, final answer. Wrapping each step's callback shows which step dominates cost, so you optimize the right one.
Logging to a Dashboard
Emit tokens and cost as structured logs or metrics (e.g. to Prometheus or LangSmith). Tag them with user, model, and route so you can slice spend.
log.info('llm_usage', extra={
'tokens': cb.total_tokens,
'cost': cb.total_cost,
'route': 'support_agent'
})Common Savings
Once you can see spend, the biggest wins are usually:
- Smaller models for simple steps
- Caching repeated calls
- Trimming history and retrieved context
- Stopping runaway agent loops with iteration limits
Alerting on Anomalies
Set alerts for sudden cost spikes — often a sign of a prompt-injection loop or a misbehaving tool. Catching it in minutes beats finding it on the invoice.
Quick Check
Test your cost monitoring knowledge.
Recap
You learned to observe agent spend:
- Split prompt vs completion tokens
- Use
get_openai_callbackandusage_metadata - Estimate with
tiktokenand enforce budgets - Attribute cost per agent step
- Log to dashboards and alert on spikes
Visibility into cost is the foundation for optimizing production agents.
자주 묻는 질문
“토큰 사용량 및 비용 모니터링” 강의는 무료인가요?
네 — “토큰 사용량 및 비용 모니터링” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents with LangChain & Autonomous Workflows 강의 전체를 잠금 해제할 수 있습니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
“토큰 사용량 및 비용 모니터링”에서 뭘 배우나요?
에이전트가 실시간으로 소비하는 토큰 수와 비용을 측정하고, 예산을 설정하며, 비용이 많이 드는 단계를 찾아 프로덕션 지출을 최적화합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents with LangChain & Autonomous Workflows을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents with LangChain & Autonomous Workflows을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents with LangChain & Autonomous Workflows은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“토큰 사용량 및 비용 모니터링” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents with LangChain & Autonomous Workflows 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents with LangChain & Autonomous Workflows 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 추적과 모니터링을 위한 LangSmith
- 에이전트 사고 과정 디버깅
- 에이전트 성능 평가
- 토큰 사용량 및 비용 모니터링