Token-Nutzung und Kostenüberwachung
Messen Sie in Echtzeit, wie viele Tokens Ihre Agents verbrauchen und welche Kosten dabei entstehen, legen Sie Budgets fest und ermitteln Sie die teuren Schritte, um die Ausgaben in der Produktion zu optimieren.
Token-Nutzung und Kostenüberwachung ist eine kostenlose AI Agents with LangChain & Autonomous Workflows-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des AI Agents with LangChain & Autonomous Workflows-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der AI Agents with LangChain & Autonomous Workflows-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Token-Nutzung und Kostenüberwachung“ kostenlos?
Ja — der vollständige Text von „Token-Nutzung und Kostenüberwachung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des AI Agents with LangChain & Autonomous Workflows-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der AI Agents with LangChain & Autonomous Workflows-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Token-Nutzung und Kostenüberwachung“?
Messen Sie in Echtzeit, wie viele Tokens Ihre Agents verbrauchen und welche Kosten dabei entstehen, legen Sie Budgets fest und ermitteln Sie die teuren Schritte, um die Ausgaben in der Produktion zu… Du übst AI Agents with LangChain & Autonomous Workflows mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um AI Agents with LangChain & Autonomous Workflows zu starten?
Keine Vorkenntnisse erforderlich. AI Agents with LangChain & Autonomous Workflows auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Token-Nutzung und Kostenüberwachung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser AI Agents with LangChain & Autonomous Workflows-Lektion Code schreiben und ausführen?
Ja. Jede AI Agents with LangChain & Autonomous Workflows-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- LangSmith für Tracing und Monitoring
- Denkprozesse von Agenten debuggen
- Agenten-Performance bewerten
- Token-Nutzung und Kostenüberwachung