Skip to content

feat: After the conversation stops halfway, the token usage is displayed as 0 - #8042

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_token
Nov 19, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_token

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: After the conversation stops halfway, the token usage is displayed as 0

message_tokens += count_local_tokens(self._base_messages, "")[0] if self._base_messages else 0
message_tokens += len(tokenizer.encode(before)) if before else 0
answer_tokens += len(tokenizer.encode(reply)) if reply else 0
return message_tokens, answer_tokens

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of token_ledger.py

Correctness / Logic

  1. summarize fallback is over-triggered. The condition

    if split < len(self._contents) or (isinstance(last, UsageContent) and not last.usage):

    adds the local estimate on top of already counted usage whenever there is a trailing reply and real usage exists. That's intended, but note it also fires when the trailing "reply" is an empty ToolContent — fine — yet it will also fire when the only contents are replies with no preceding usage at all, which is probably desired. Just make the intent explicit in the docstring/test.

  2. _base_messages counted only in the fallback branch. If all calls returned usage, base messages come from the model's input_tokens, so no double count — OK. But if the first call returned usage and a later one was interrupted, the fallback adds _base_messages again, even though they were already included in the first call's input_tokens. This is a double-counting bug for the interrupted-later-call case.

  3. before text vs. messages mismatch. message_tokens += _base_messages token count + tokens(before) assumes the whole prior conversation is serialized as plain text. In reality prior tool results / reasoning are fed as structured messages to the model; a raw concatenation ("".join) is only a rough approximation and may drift from actual prompt size.

  4. split scanning stops at any UsageContent or tool-result, per the comment. Verify record() actually keeps the UsageContent that marks the completed call boundary — since empty-usages are recorded too, a "call start" marker can be mistaken for a boundary. The loop while split and _is_reply(...) doesn't stop at UsageContent explicitly; it relies on _is_reply being False for UsageContent, which works, but the last-element special case (not last.usage) then treats a trailing empty usage as an unfinished call even if real output followed it. Order matters here.

  5. usage["input_tokens"] KeyError risk (minor). sum(usage["input_tokens"] ...) is safe because you always set both fields via the for field in (...) loop — but only for content.id keys where at least one chunk had truthy usage. OK. Still, prefer .get(field, 0) for robustness.

  6. max() accumulation assumption. Taking per-field max across chunks assumes chunks carry cumulative totals. If a provider sends incremental per-chunk deltas, this silently under-counts. This should be verified per provider / documented.

  7. content.id grouping. Multiple distinct logical calls must have distinct ids. If id is reused (e.g., None or shared), usages merge incorrectly. Consider guarding against falsy ids.

  8. _text for ToolContent uses arguments + content, but _is_reply treats tool content with content as input (not reply). That's consistent, but the concatenation order and separators (none) may inflate/deflate token counts slightly. Minor.

  9. Empty ToolContent counted as reply. If a tool call has neither arguments nor content, _text returns "", record() skips it (fine), but _is_reply would return True for such content — however it never gets stored, so consistent. Still fragile; add a comment or assert.

Robustness / Style

  1. Type hints. __init__ params untyped; set_base_messages(messages) unclear type. Add types.
  2. tuple[int, int] requires Python 3.9+; confirm target version.
  3. Private helpers without types (_text, _is_reply) — add signatures and docstrings.
  4. No tests visible for: empty ledger, all-usage, all-interrupted, mixed, multiple concurrent call ids.
  5. Locale: file mixes Chinese comments with English identifiers — acceptable but keep consistent.
  6. TokenizerManage.get_tokenizer() called inside summarize each time; cache it if summarize is hot.
  7. Docstring says "从末尾往前…遇到用量或工具结果为止" — aligns with code; keep it accurate if logic changes (see feat: 添加issues 模版 #4).

Suggested fixes (priority order)

def to_dict(self):
result = super().to_dict()
result["usage"] = self.usage
return result

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of usage_content.py

Potential issues

  1. Mutable default risk / shallow defensive copy
    dict(usage or {}) makes a shallow copy, so nested dicts (e.g. LangChain's usage_metadata with nested token detail objects) are still shared with the caller. If that metadata is later mutated elsewhere, this object changes silently. Consider deepcopy if nested structures exist.

  2. Hard-coded Status.RUNNING in the constructor
    The class claims to represent "token usage for one model call", but it always sets status to RUNNING. There's no way to mark completion/failure. Either:

    • accept a status parameter, or
    • document clearly that this content object is transient and only ever emitted during execution.
  3. Untyped _id and **kwargs
    _id has no type hint, and **kwargs is passed straight through to super().__init__. If the base class doesn't accept arbitrary kwargs this will fail at runtime; if it does, unknown keys can be silently swallowed. Sugges entering explicit keyword args or validating.

  4. Docstring says "not output to frontend" but to_dict() serializes usage
    Contradiction: the comment says it's internal-only, yet to_dict() exposes the data. If to_dict() is used by any serializer that reaches the frontend, the intent is violated. Clarify whether to_dict is used only internally, or remove/exclude usage from the serialized form.

  5. No validation of usage shape
    Any dict is accepted. If downstream code expects specific keys (input_tokens, output_tokens, etc.), invalid input will surface far from the source. A light validation or a typed dataclass would help.

  6. Encoding declaration redundant
    # coding=utf-8 is unnecessary in Python 3 and just adds noise (PEP 3120).

  7. File header formatting
    Mixed full-width/inside punctuation (@file: uses a full-width colon) — minor, but inconsistent with standard headers.

Optimization suggestions

  • Add type annotations: _id: str, usage: Optional[Dict[str, Any]], -> None.
  • Replace manual super().to_dict() mutation with a cleaner pattern:
    return {**super().to_dict(), "usage": self.usage}
  • Make usage immutable or store a deep copy to preserve value semantics.
  • Consider making this a frozen/slot-based object if instances are numerous (nodes may create many per request).
  • Expose read-only access via a property if you want to prevent accidental mutation:
    @property
    def usage(self): return self._usage
  • If the "internal only" intent is real, split into two methods (e.g. to_internal_dict() vs to_dict()), or gate behind a flag.

Minor

  • Docstring language inconsistency (Chinese docs, English identifiers) is fine but pick one convention for the team.

@shaohuzhang1
shaohuzhang1 merged commit ee6391e into v3 Nov 19, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_token branch November 19, 2026 11:16
BREAK = "BREAK"
FORM = "FORM"
PROGRESS = "PROGRESS"
USAGE = "USAGE"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The diff itself is trivial and mostly harmless, but here are some notes:

Correctness / consistency

  • USAGE = "USAGE" matches the existing naming convention (member name == value), so it's consistent with the other enum members. Good.
  • If this enum is used to build DB values, API contracts, or serialized payloads (e.g., stored strings, JSON keys, i18n lookups), adding a new member is a backward-compatible addition but you must update all match/if chains or mapping tables that switch on ContentType. Any exhaustive match without a default branch will now fail (or silently mishandle USAGE).
  • Verify there's no code doing len(ContentType) or relying on member order/count — adding a member can break such assumptions.

Ordering / semantics

  • Placement after PROGRESS looks fine alphabetically-ish by intent, but if the enum order matters (numeric index, UI ordering), confirm USAGE should be last.
  • Consider whether USAGE semantically belongs grouped with related types (e.g., near FORM/PROGRESS) for readability.

Optimization / style

  • Nothing to optimize performance-wise; enums are compile-time constants.
  • If many new members are expected, ensure the enum doesn't grow into an unmaintainable catch-all — consider sub-enums or namespacing.
  • Add a docstring/comment if USAGE meaning isn't obvious from context.

Testing

  • Add/update tests covering serialization round-trip and any switch over ContentType to include USAGE.

No real bugs in the change itself; the main risk is downstream exhaustive handling of the enum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant