0Pricing
AI Agents with LangChain & Autonomous Workflows · レッスン

トークン使用量とコストの監視

エージェントが消費するトークン数とコストをリアルタイムで測定し、予算を設定し、費用の大きい処理を見つけて本番環境の支出を最適化します。

「トークン使用量とコストの監視」はCoddyKit上の無料AI Agents with LangChain & Autonomous Workflowsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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_callback and usage_metadata
  • Estimate with tiktoken and 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時間対応のAIチューター)、AI Agents with LangChain & Autonomous Workflowsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agents with LangChain & Autonomous Workflowsコースには全4レッスンが含まれています。

「トークン使用量とコストの監視」で何を学びますか?

エージェントが消費するトークン数とコストをリアルタイムで測定し、予算を設定し、費用の大きい処理を見つけて本番環境の支出を最適化します。 ブラウザで直接実行するハンズオンコードでAI Agents with LangChain & Autonomous Workflowsを演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. トレーシングと監視のためのLangSmith
  2. エージェントの思考プロセスのデバッグ
  3. エージェントのパフォーマンス評価
  4. トークン使用量とコストの監視
← AI Agents with LangChain & Autonomous Workflowsに戻る