0Pricing
AI Agents with LangChain & Autonomous Workflows · Lezione

Utilizzo dei token e monitoraggio dei costi

Misurate in tempo reale quanti token consumano i vostri agenti e quanto costano, impostate budget e individuate i passaggi più costosi per ottimizzare la spesa in produzione.

Utilizzo dei token e monitoraggio dei costi è una lezione AI Agents with LangChain & Autonomous Workflows gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Agents with LangChain & Autonomous Workflows, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Agents with LangChain & Autonomous Workflows include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Utilizzo dei token e monitoraggio dei costi» è gratuita?

Sì — il testo completo di «Utilizzo dei token e monitoraggio dei costi» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Agents with LangChain & Autonomous Workflows, passa a CoddyKit PRO. Il corso AI Agents with LangChain & Autonomous Workflows include 4 lezioni in totale.

Cosa imparerò in «Utilizzo dei token e monitoraggio dei costi»?

Misurate in tempo reale quanti token consumano i vostri agenti e quanto costano, impostate budget e individuate i passaggi più costosi per ottimizzare la spesa in produzione. Eserciti AI Agents with LangChain & Autonomous Workflows con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Agents with LangChain & Autonomous Workflows?

Non è richiesta alcuna esperienza precedente. AI Agents with LangChain & Autonomous Workflows su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Utilizzo dei token e monitoraggio dei costi»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Agents with LangChain & Autonomous Workflows?

Sì. Ogni lezione AI Agents with LangChain & Autonomous Workflows include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. LangSmith per tracing e monitoraggio
  2. Debugging dei processi di ragionamento degli agenti
  3. Valutare le prestazioni degli agenti
  4. Utilizzo dei token e monitoraggio dei costi
← Torna a AI Agents with LangChain & Autonomous Workflows