LogoCua Documentation

Usage Tracking

How to track token usage and cost in ComputerAgent and agent loops.

Tracking usage is important for monitoring costs and optimizing your agent workflows. The ComputerAgent API provides easy access to token and cost usage for every run.

Accessing Usage Data

Whenever you run an agent loop, each result contains a usage dictionary with token and cost information:

async for result in agent.run(...):
    print(result["usage"])
    # Example output:
    # {
    #     "prompt_tokens": 150,
    #     "completion_tokens": 75,
    #     "total_tokens": 225,
    #     "response_cost": 0.01,
    # }
  • prompt_tokens: Number of tokens in the prompt
  • completion_tokens: Number of tokens in the agent's response
  • total_tokens: Total tokens used
  • response_cost: Estimated cost (USD) for this turn

Tracking Total Usage

You can accumulate usage across multiple turns:

total_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "response_cost": 0.0}
async for result in agent.run(...):
    for k in total_usage:
        total_usage[k] += result["usage"].get(k, 0)
print("Total usage:", total_usage)

Using Callbacks for Usage Tracking

You can also use a callback to automatically track usage. Implement the on_usage method in your callback class:

from agent.callbacks import AsyncCallbackHandler

class UsageTrackerCallback(AsyncCallbackHandler):
    async def on_usage(self, usage):
        print("Usage update:", usage)

agent = ComputerAgent(
    ..., 
    callbacks=[UsageTrackerCallback()]
)

See also: Budget Manager Callbacks

See Also