Repository navigation
feat: After the conversation stops halfway, the token usage is displayed as 0 - #8042
Conversation
| 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 |
There was a problem hiding this comment.
Review of token_ledger.py
Correctness / Logic
-
summarizefallback is over-triggered. The conditionif 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. -
_base_messagescounted only in the fallback branch. If all calls returned usage, base messages come from the model'sinput_tokens, so no double count — OK. But if the first call returned usage and a later one was interrupted, the fallback adds_base_messagesagain, even though they were already included in the first call'sinput_tokens. This is a double-counting bug for the interrupted-later-call case. -
beforetext 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. -
splitscanning stops at anyUsageContentor tool-result, per the comment. Verifyrecord()actually keeps theUsageContentthat marks the completed call boundary — since empty-usages are recorded too, a "call start" marker can be mistaken for a boundary. The loopwhile split and _is_reply(...)doesn't stop atUsageContentexplicitly; it relies on_is_replybeing False forUsageContent, 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. -
usage["input_tokens"]KeyError risk (minor).sum(usage["input_tokens"] ...)is safe because you always set both fields via thefor field in (...)loop — but only forcontent.idkeys where at least one chunk had truthyusage. OK. Still, prefer.get(field, 0)for robustness. -
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. -
content.idgrouping. Multiple distinct logical calls must have distinctids. Ifidis reused (e.g.,Noneor shared), usages merge incorrectly. Consider guarding against falsy ids. -
_textforToolContentusesarguments + content, but_is_replytreats tool content withcontentas input (not reply). That's consistent, but the concatenation order and separators (none) may inflate/deflate token counts slightly. Minor. -
Empty
ToolContentcounted as reply. If a tool call has neitherargumentsnorcontent,_textreturns"",record()skips it (fine), but_is_replywould return True for such content — however it never gets stored, so consistent. Still fragile; add a comment or assert.
Robustness / Style
- Type hints.
__init__params untyped;set_base_messages(messages)unclear type. Add types. tuple[int, int]requires Python 3.9+; confirm target version.- Private helpers without types (
_text,_is_reply) — add signatures and docstrings. - No tests visible for: empty ledger, all-usage, all-interrupted, mixed, multiple concurrent call ids.
- Locale: file mixes Chinese comments with English identifiers — acceptable but keep consistent.
TokenizerManage.get_tokenizer()called insidesummarizeeach time; cache it ifsummarizeis hot.- Docstring says "从末尾往前…遇到用量或工具结果为止" — aligns with code; keep it accurate if logic changes (see feat: 添加issues 模版 #4).
Suggested fixes (priority order)
- Fix double counting (build(deps): bump the pip group across 1 directory with 1 update #2): track whether base messages were already reflected in recorded usage; only add them in fallback if no completed first call covered them.
- Harden
summarize(关于页面优化 #5):usage.get("input_tokens", 0). - Validate id uniqueness (修改密码页面优化 #7) and document cumulative-vs-delta semantics (创建模型时,添加 Ollama 供应商报错。 #6).
- Clarify
splitboundary with an explicit check forUsageContent/tool-result instead of relying on_is_reply(feat: 添加issues 模版 #4). - Add unit tests covering the four states above.
| def to_dict(self): | ||
| result = super().to_dict() | ||
| result["usage"] = self.usage | ||
| return result |
There was a problem hiding this comment.
Review of usage_content.py
Potential issues
-
Mutable default risk / shallow defensive copy
dict(usage or {})makes a shallow copy, so nested dicts (e.g. LangChain'susage_metadatawith nested token detail objects) are still shared with the caller. If that metadata is later mutated elsewhere, this object changes silently. Considerdeepcopyif nested structures exist. -
Hard-coded
Status.RUNNINGin the constructor
The class claims to represent "token usage for one model call", but it always sets status toRUNNING. There's no way to mark completion/failure. Either:- accept a
statusparameter, or - document clearly that this content object is transient and only ever emitted during execution.
- accept a
-
Untyped
_idand**kwargs
_idhas no type hint, and**kwargsis passed straight through tosuper().__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. -
Docstring says "not output to frontend" but
to_dict()serializesusage
Contradiction: the comment says it's internal-only, yetto_dict()exposes the data. Ifto_dict()is used by any serializer that reaches the frontend, the intent is violated. Clarify whetherto_dictis used only internally, or remove/excludeusagefrom the serialized form. -
No validation of
usageshape
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. -
Encoding declaration redundant
# coding=utf-8is unnecessary in Python 3 and just adds noise (PEP 3120). -
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
usageimmutable 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()vsto_dict()), or gate behind a flag.
Minor
- Docstring language inconsistency (Chinese docs, English identifiers) is fine but pick one convention for the team.
| BREAK = "BREAK" | ||
| FORM = "FORM" | ||
| PROGRESS = "PROGRESS" | ||
| USAGE = "USAGE" |
There was a problem hiding this comment.
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/ifchains or mapping tables that switch onContentType. Any exhaustive match without a default branch will now fail (or silently mishandleUSAGE). - 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
PROGRESSlooks fine alphabetically-ish by intent, but if the enum order matters (numeric index, UI ordering), confirmUSAGEshould be last. - Consider whether
USAGEsemantically belongs grouped with related types (e.g., nearFORM/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
USAGEmeaning isn't obvious from context.
Testing
- Add/update tests covering serialization round-trip and any
switchoverContentTypeto includeUSAGE.
No real bugs in the change itself; the main risk is downstream exhaustive handling of the enum.
feat: After the conversation stops halfway, the token usage is displayed as 0