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¶
# 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 |
int
|
Estimated input tokens for the assembled request. |
context_window |
int | None
|
Provider/model context window when known, else |
remaining_tokens |
int | None
|
|
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; |
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
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
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
component(key)
¶
Return the component with key, or None when it is absent.
nagents.context_stats.ContextComponent
dataclass
¶
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
|
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
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
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.