> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Task Metrics

> Track tokens, cost, requests, tool calls, and timing for a single task execution.

## Overview

Every task exposes a single read-only **`task.usage`** property. It returns an `AggregatedUsage` view derived from the [centralized usage registry](/concepts/usage-registry) on each access, scoped to this task's `task_usage_id`.

For wall-clock task length, compute `task.end_time - task.start_time`. The figure on `task.usage.duration` is the **sum of per-call model durations**, not wall-clock.

When printing is enabled (`print_do` / `print_do_async`), a **Task Metrics** panel is displayed after each execution.

## Accessing Task Metrics

Read **`task.usage`** on any `Task` instance after execution. It always returns an `AggregatedUsage` — zero-valued before any model call, populated thereafter.

### Token Metrics

| Property             | Type  | Description                           |
| -------------------- | ----- | ------------------------------------- |
| `input_tokens`       | `int` | Prompt tokens for this task           |
| `output_tokens`      | `int` | Completion tokens for this task       |
| `total_tokens`       | `int` | Sum of `input_tokens + output_tokens` |
| `cache_read_tokens`  | `int` | Tokens read from prompt cache         |
| `cache_write_tokens` | `int` | Tokens written to prompt cache        |
| `reasoning_tokens`   | `int` | Reasoning (chain-of-thought) tokens   |

### Request & Tool Metrics

| Property     | Type  | Description                                 |
| ------------ | ----- | ------------------------------------------- |
| `requests`   | `int` | Number of LLM API requests for this task    |
| `tool_calls` | `int` | Number of tool calls executed for this task |

### Timing Metrics

| Property                 | Type            | Description                                              |
| ------------------------ | --------------- | -------------------------------------------------------- |
| `duration`               | `float`         | Sum of per-call durations recorded on entries (seconds)  |
| `model_execution_time`   | `float`         | Total time spent inside LLM API calls (seconds)          |
| `tool_execution_time`    | `float`         | Total time spent executing tools (seconds)               |
| `upsonic_execution_time` | `float`         | Framework overhead = `duration − model − tool` (seconds) |
| `time_to_first_token`    | `float \| None` | Earliest TTFT across contributing entries                |

### Cost Metrics

| Property | Type            | Description                                                                                                |
| -------- | --------------- | ---------------------------------------------------------------------------------------------------------- |
| `cost`   | `float \| None` | Sum of `cost_usd` across contributing entries. `None` if no entry was priced; `0.0` means priced and free. |

### Aggregation Metadata

| Property      | Type        | Description                                                      |
| ------------- | ----------- | ---------------------------------------------------------------- |
| `entry_count` | `int`       | Number of underlying `UsageEntry` rows contributing to this view |
| `models`      | `list[str]` | Distinct model identifiers that contributed (first-seen order)   |

### Task Identity & Wall-Clock Timing

| Property        | Type            | Description                                               |
| --------------- | --------------- | --------------------------------------------------------- |
| `task_id`       | `str`           | Stable identifier for the task                            |
| `task_usage_id` | `str`           | Scope tag used to filter the usage registry for this task |
| `start_time`    | `float \| None` | Unix timestamp when the task started                      |
| `end_time`      | `float \| None` | Unix timestamp when the task finished                     |

## Example

```python theme={null}
from upsonic import Agent, Task

agent = Agent("anthropic/claude-sonnet-4-5")
task = Task("Summarize the key benefits of AI agents in production systems")

agent.print_do(task)

u = task.usage
print(f"Requests:        {u.requests}")
print(f"Input tokens:    {u.input_tokens}")
print(f"Output tokens:   {u.output_tokens}")
print(f"Tool calls:      {u.tool_calls}")
if u.cost is not None:
    print(f"Cost:            ${u.cost:.6f}")
print(f"Model time:      {u.model_execution_time:.2f}s")
print(f"Tool time:       {u.tool_execution_time:.2f}s")
print(f"Framework time:  {u.upsonic_execution_time:.2f}s")
print(f"Models used:     {u.models}")

# Wall-clock task length
if task.start_time and task.end_time:
    print(f"Wall-clock:      {(task.end_time - task.start_time):.2f}s")
```

## Printed Panel

When you use `print_do` or `print_do_async`, the **Task Metrics** panel displays after the task:

```
╭──────────────────── Task Metrics ─────────────────────╮
│  Task Usage ID:         a1b2c3d4-e5f6-...             │
│                                                       │
│  Input Tokens:          762                           │
│  Output Tokens:         408                           │
│  Total Estimated Cost:  $0.0004                       │
│  Model Execution Time:  7.99 seconds                  │
│  Tool Execution Time:   1.00 seconds                  │
│  Framework Overhead:    1.56 seconds                  │
╰───────────────────────────────────────────────────────╯
```

## Scope & Propagation

* **Per-task isolation** — Each task has its own `task_usage_id`. Two tasks executed by the same agent never mix their `task.usage` figures.
* **Agent rollup** — The same entries that contribute to `task.usage` also contribute to `agent.usage` (and `chat.usage` / `team.usage` if applicable) because every entry carries multiple scope tags.
* **Sub-pipeline rollup** — Reliability validator/editor, culture, policy, and sub-agent calls dispatched during this task inherit `task_usage_id` and roll into `task.usage` automatically.
* **Retry idempotency** — The registry is keyed by `entry_id`. Retried requests replace their prior entry instead of double-counting.
* **JSON snapshot** — Call `task.usage.to_dict()` for a flat dict suitable for logs and dashboards.

## Legacy Migration

<Note>
  Legacy task-level properties have been removed in favour of `task.usage`:

  | Legacy                                                                                 | Replacement                                                                               |
  | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
  | `task.total_cost`                                                                      | `task.usage.cost`                                                                         |
  | `task.total_input_token`                                                               | `task.usage.input_tokens`                                                                 |
  | `task.total_output_token`                                                              | `task.usage.output_tokens`                                                                |
  | `task.price_id`, `Task.price_id_`                                                      | `task.task_usage_id`                                                                      |
  | `task.get_total_cost()`                                                                | `task.usage.to_dict()`                                                                    |
  | `task.duration`                                                                        | `task.end_time - task.start_time` (wall-clock) or `task.usage.duration` (sum of per-call) |
  | `task.model_execution_time`, `task.tool_execution_time`, `task.upsonic_execution_time` | `task.usage.X`                                                                            |
</Note>

## Related Documentation

* [Usage Registry](/concepts/usage-registry) — Architecture, scope tags, persistence
* [Agent Metrics](/concepts/agents/metrics) — Accumulated agent-level view
* [Chat Metrics](/concepts/chat/metrics) — Per-session scoped view
* [Team Metrics](/concepts/team/metrics) — Per-team scoped view
* [Task Caching](/concepts/tasks/task-caching) — Reduce costs with caching
