Skip to content

Context Statistics API

Context statistics distinguish a provider-backed context budget from a heuristic breakdown of the next input. The library provider owns the calculation; Agent.context_stats(session_id) assembles the session and delegates to it. ngn's context indicator, agent status pane and token-based compaction use the same budget.

Context budget and reasoning

context_tokens uses the last matching provider measurement: input plus generated output, including reasoning exactly once. Estimated user/tool messages added afterward and an unsaved streaming reply become pending_context_tokens. Without a matching measurement it falls back to the estimated next input.

Reasoning already included in a provider's output is not added again. Separately reported reasoning is added once. An unknown inclusion relationship does not justify double counting; the source reflects incomplete information. observed_reasoning_tokens is None when absent and preserves a reported zero.

context_tokens_source is provider, mixed or estimated. remaining_tokens subtracts context_tokens from the model window, and can be negative. These numbers describe a response budget, not cumulative session billing or a promise that every earlier hidden reasoning item will be retained in the next request. See provider context accounting.

Provider.context_stats(...) is synchronous and makes no HTTP request. Agent.context_stats(...) may resolve bounded model metadata, but never asks a model to generate a response. It accounts for current instructions, tool schemas, skills, history and streamed text. Explicit $skill activation is request-local and is not part of an idle session's saved history.

Estimated next-input components

total_tokens and components estimate the assembled next input. Components appear in stable order and sum exactly to total_tokens; they do not partition the provider-measured context_tokens total.

The heuristic uses roughly four characters per text token and a size-based approximation for base64 media. Provider framing and attachment tokenization can differ. These component estimates are not tokenizer counts or billed usage.

Key Label
system_prompt System prompt
instructions Request instructions
tools Tool definitions
skills Skills
history_user Conversation history (user)
history_assistant Conversation history (assistant)
history_tool Conversation history (tool)
history_other Conversation history (other)
media Media and attachments

Loaded skill bodies returned by skill(name) appear under skills; their media remains under media. estimate_context_stats is the pure function for callers that already have assembled inputs; a library Agent supplies matching provider usage, history and streaming state automatically.

Python

context_stats.py
# After running an ordinary Agent:
stats = await agent.context_stats("session-123")
print(f"Context: {stats.context_tokens} ({stats.context_tokens_source})")
print(f"Estimated next input: {stats.total_tokens}")
for component in stats.components:
    print(f"{component.label}: {component.tokens}")
if stats.context_window is not None:
    print(f"Remaining: {stats.remaining_tokens} of {stats.context_window}")
if stats.observed_reasoning_tokens is not None:
    print(f"Last reported reasoning: {stats.observed_reasoning_tokens}")

The provider resolves the model window from explicit configuration, matching provider metadata or a heuristic fallback. context_window_source identifies which one was used. The pure estimator can leave the window as None when no limit is supplied. A model, connection, instructions, tool or saved-context change invalidates a previous measurement rather than applying it to unrelated input.

nagents.context_stats.ContextStats dataclass

Estimated breakdown of what a request carries.

Attributes:

Name Type Description
components tuple[ContextComponent, ...]

Stable, ordered components that sum to total_tokens.

total_tokens int

Estimated input tokens for the assembled request.

context_window int | None

Provider/model context window when known, else None.

remaining_tokens int | None

context_window - context_tokens when the window is known, else None. It can be negative when the budget is exceeded.

observed_prompt_tokens int | None

Last provider-reported input tokens, when the agent has seen a real usage event for the session.

observed_completion_tokens int | None

Last provider-reported output tokens.

observed_reasoning_tokens int | None

Last reported reasoning count, including a reported zero; None when the breakdown was not supplied.

observed_context_tokens int | None

Input and generated output for the last measured response, including reported reasoning exactly once.

pending_context_tokens int

Estimated new data beyond that response.

provider str

Provider identifier the estimate was computed for.

model str

Model identifier the estimate was computed for.

estimate_method str

Human-readable note describing the heuristic.

Source code in src/nagents/context_stats.py
@dataclass(frozen=True)
class ContextStats:
    """Estimated breakdown of what a request carries.

    Attributes:
        components: Stable, ordered components that sum to ``total_tokens``.
        total_tokens: Estimated input tokens for the assembled request.
        context_window: Provider/model context window when known, else ``None``.
        remaining_tokens: ``context_window - context_tokens`` when the window is
            known, else ``None``. It can be negative when the budget is exceeded.
        observed_prompt_tokens: Last provider-reported input tokens, when the
            agent has seen a real usage event for the session.
        observed_completion_tokens: Last provider-reported output tokens.
        observed_reasoning_tokens: Last reported reasoning count, including a
            reported zero; ``None`` when the breakdown was not supplied.
        observed_context_tokens: Input and generated output for the last
            measured response, including reported reasoning exactly once.
        pending_context_tokens: Estimated new data beyond that response.
        provider: Provider identifier the estimate was computed for.
        model: Model identifier the estimate was computed for.
        estimate_method: Human-readable note describing the heuristic.
    """

    components: tuple[ContextComponent, ...]
    total_tokens: int
    context_window: int | None = None
    remaining_tokens: int | None = None
    observed_prompt_tokens: int | None = None
    observed_completion_tokens: int | None = None
    provider: str = ""
    model: str = ""
    estimate_method: str = ESTIMATE_METHOD
    context_window_source: ContextWindowSource = "heuristic"
    compaction: CompactionSnapshot | None = None
    observed_reasoning_tokens: int | None = None
    observed_reasoning_in_output: Literal["included", "separate", "unknown"] = "unknown"
    observed_context_tokens: int | None = None
    observed_context_source: ContextTokenSource = "provider"
    pending_context_tokens: int = 0

    @property
    def context_tokens(self) -> int:
        """Last measured response context plus explicitly estimated new data.

        With no matching measurement, use the estimated next input. Never
        confuse either quantity with accumulated tokens billed over a session.
        """
        if self.observed_context_tokens is not None:
            return self.observed_context_tokens + self.pending_context_tokens
        return self.total_tokens

    @property
    def context_tokens_source(self) -> ContextTokenSource:
        if self.observed_context_tokens is None:
            return "estimated"
        if self.pending_context_tokens:
            return "mixed"
        return self.observed_context_source

    def component(self, key: str) -> ContextComponent | None:
        """Return the component with ``key``, or ``None`` when it is absent."""
        for component in self.components:
            if component.key == key:
                return component
        return None

    def as_dict(self) -> dict[str, object]:
        """Return a JSON-serializable mapping for HTTP or logging surfaces."""
        return {
            "components": [asdict(component) for component in self.components],
            "total_tokens": self.total_tokens,
            "context_window": self.context_window,
            "context_window_source": self.context_window_source,
            **({"compaction": self.compaction} if self.compaction is not None else {}),
            "remaining_tokens": self.remaining_tokens,
            "observed_prompt_tokens": self.observed_prompt_tokens,
            "observed_completion_tokens": self.observed_completion_tokens,
            "observed_reasoning_tokens": self.observed_reasoning_tokens,
            "observed_reasoning_in_output": self.observed_reasoning_in_output,
            "observed_context_tokens": self.observed_context_tokens,
            "pending_context_tokens": self.pending_context_tokens,
            "context_tokens": self.context_tokens,
            "context_tokens_source": self.context_tokens_source,
            "provider": self.provider,
            "model": self.model,
            "estimate_method": self.estimate_method,
        }

context_tokens property

Last measured response context plus explicitly estimated new data.

With no matching measurement, use the estimated next input. Never confuse either quantity with accumulated tokens billed over a session.

as_dict()

Return a JSON-serializable mapping for HTTP or logging surfaces.

Source code in src/nagents/context_stats.py
def as_dict(self) -> dict[str, object]:
    """Return a JSON-serializable mapping for HTTP or logging surfaces."""
    return {
        "components": [asdict(component) for component in self.components],
        "total_tokens": self.total_tokens,
        "context_window": self.context_window,
        "context_window_source": self.context_window_source,
        **({"compaction": self.compaction} if self.compaction is not None else {}),
        "remaining_tokens": self.remaining_tokens,
        "observed_prompt_tokens": self.observed_prompt_tokens,
        "observed_completion_tokens": self.observed_completion_tokens,
        "observed_reasoning_tokens": self.observed_reasoning_tokens,
        "observed_reasoning_in_output": self.observed_reasoning_in_output,
        "observed_context_tokens": self.observed_context_tokens,
        "pending_context_tokens": self.pending_context_tokens,
        "context_tokens": self.context_tokens,
        "context_tokens_source": self.context_tokens_source,
        "provider": self.provider,
        "model": self.model,
        "estimate_method": self.estimate_method,
    }

component(key)

Return the component with key, or None when it is absent.

Source code in src/nagents/context_stats.py
def component(self, key: str) -> ContextComponent | None:
    """Return the component with ``key``, or ``None`` when it is absent."""
    for component in self.components:
        if component.key == key:
            return component
    return None

nagents.context_stats.ContextComponent dataclass

One labeled part of the estimated request context.

Source code in src/nagents/context_stats.py
@dataclass(frozen=True)
class ContextComponent:
    """One labeled part of the estimated request context."""

    key: str
    label: str
    tokens: int

nagents.estimate_context_stats(*, system_prompt='', instructions='', tools=(), skill_manifest='', skill_text='', messages=(), context_window=None, context_window_source='heuristic', compaction=None, provider='', model='', observed=None, additional_messages=(), streaming_reply='')

Estimate a request breakdown from its assembled inputs.

Callers pass the same values they would send to the provider: the system prompt, request-local instructions, tool schemas, rendered skill text (the catalog manifest and any loaded bodies), and the conversation history. Skill tool results in messages are counted under skills instead of history.

Parameters:

Name Type Description Default
system_prompt str

The agent's base system prompt.

''
instructions str

Request-local instructions separable from the system prompt.

''
tools Sequence[ToolDefinition]

Tool definitions whose JSON schemas are sent to the provider.

()
skill_manifest str

Rendered available-skills catalog text.

''
skill_text str

Loaded skill body text included in the request.

''
messages Sequence[Message]

Conversation history, excluding the base system prompt.

()
context_window int | None

Known model context window, or None when unknown.

None
provider str

Provider identifier for reporting.

''
model str

Model identifier for reporting.

''
observed TokenUsage | None

Last real provider usage, scoped to one matching response.

None
additional_messages Sequence[Message]

Messages appended after the measured response's assistant output, such as tool results and a new user message.

()
streaming_reply str

An unsaved visible response; measured output usage already covering these tokens is not added again.

''
Source code in src/nagents/context_stats.py
def estimate_context_stats(
    *,
    system_prompt: str = "",
    instructions: str = "",
    tools: Sequence[ToolDefinition] = (),
    skill_manifest: str = "",
    skill_text: str = "",
    messages: Sequence[Message] = (),
    context_window: int | None = None,
    context_window_source: ContextWindowSource = "heuristic",
    compaction: CompactionSnapshot | None = None,
    provider: str = "",
    model: str = "",
    observed: TokenUsage | None = None,
    additional_messages: Sequence[Message] = (),
    streaming_reply: str = "",
) -> ContextStats:
    """Estimate a request breakdown from its assembled inputs.

    Callers pass the same values they would send to the provider: the system
    prompt, request-local instructions, tool schemas, rendered skill text (the
    catalog manifest and any loaded bodies), and the conversation history. Skill
    tool results in ``messages`` are counted under ``skills`` instead of history.

    Args:
        system_prompt: The agent's base system prompt.
        instructions: Request-local instructions separable from the system prompt.
        tools: Tool definitions whose JSON schemas are sent to the provider.
        skill_manifest: Rendered available-skills catalog text.
        skill_text: Loaded skill body text included in the request.
        messages: Conversation history, excluding the base system prompt.
        context_window: Known model context window, or ``None`` when unknown.
        provider: Provider identifier for reporting.
        model: Model identifier for reporting.
        observed: Last real provider usage, scoped to one matching response.
        additional_messages: Messages appended after the measured response's
            assistant output, such as tool results and a new user message.
        streaming_reply: An unsaved visible response; measured output usage
            already covering these tokens is not added again.
    """
    values = {key: 0 for key, _ in COMPONENT_LABELS}
    values[SYSTEM_PROMPT_KEY] = estimate_tokens(system_prompt)
    values[INSTRUCTIONS_KEY] = estimate_tokens(instructions)
    values[TOOLS_KEY] = estimate_tool_tokens(tools)
    values[SKILLS_KEY] = estimate_tokens(skill_manifest) + estimate_tokens(skill_text)
    for key, tokens in _history_tokens(messages).items():
        values[key] += tokens

    components = tuple(ContextComponent(key, label, values[key]) for key, label in COMPONENT_LABELS)
    streaming = estimate_tokens(streaming_reply) + 4 if streaming_reply else 0
    if streaming:
        components = (*components, ContextComponent("streaming_reply", "Streaming reply (not yet saved)", streaming))
    total = sum(component.tokens for component in components)
    observed_context: int | None = None
    source: ContextTokenSource = "provider"
    pending = 0
    if observed is not None:
        observed_context, source = reported_context_tokens(observed)
        pending = sum(_history_tokens(additional_messages).values())
        # Cumulative output usage can arrive while text is still streaming.
        # Count an unsaved visible draft only beyond what usage already covers.
        measured_output = max(0, observed_context - observed.prompt_tokens)
        pending += max(0, streaming - measured_output)
    result = ContextStats(
        components=components,
        total_tokens=total,
        context_window=context_window,
        context_window_source=context_window_source,
        compaction=compaction,
        observed_prompt_tokens=observed.prompt_tokens if observed is not None else None,
        observed_completion_tokens=observed.completion_tokens if observed is not None else None,
        observed_reasoning_tokens=observed.reasoning_tokens
        if observed is not None and observed.reasoning_reported
        else None,
        observed_reasoning_in_output=observed.reasoning_in_output if observed is not None else "unknown",
        observed_context_tokens=observed_context,
        observed_context_source=source,
        pending_context_tokens=pending,
        provider=provider,
        model=model,
    )
    return replace(
        result, remaining_tokens=context_window - result.context_tokens if context_window is not None else None
    )

nagents.estimate_tool_tokens(tools)

Estimate tokens for the JSON tool schemas sent to the provider.

The neutral name/description/parameters payload is used for every provider. Provider-specific wrapper keys add a constant, negligible overhead.

Source code in src/nagents/context_stats.py
def estimate_tool_tokens(tools: Sequence[ToolDefinition]) -> int:
    """Estimate tokens for the JSON tool schemas sent to the provider.

    The neutral ``name``/``description``/``parameters`` payload is used for every
    provider. Provider-specific wrapper keys add a constant, negligible overhead.
    """
    total = 0
    for tool in tools:
        schema = json.dumps(
            {"name": tool.name, "description": tool.description, "parameters": tool.parameters},
            ensure_ascii=False,
        )
        total += estimate_tokens(schema)
    return total