Repository navigation
Closed
Description
Problem
After calling ReActAgent.doCall(msgs, structuredOutputClass), the returned Msg has usage == null, even though the underlying model call did return token usage information.
Root Cause
Two issues in ReActAgent.java:
Issue 1 — wrapNativeStructuredResult (native path, line ~1378)
Rebuilds a Msg but drops the usage field entirely:
// ReActAgent.java ~line 1378
return Msg.builderForRole(result.getRole())
.id(result.getId())
.name(result.getName())
.content(result.getContent())
.metadata(metadata)
.timestamp(result.getTimestamp())
// ← missing .usage(result.getUsage())
.build();result (from doCallInner) carries the usage, but it is lost in the reconstruction.
Issue 2 — mergeCollectedMetadata (fallback path, line ~1592)
Writes ChatUsage into metadata but does not set Msg.usage:
private Msg mergeCollectedMetadata(Msg msg, ChatUsage chatUsage, ThinkingBlock thinking) {
Map<String, Object> metadata = ...;
if (chatUsage != null) {
metadata.put(MessageMetadataKeys.CHAT_USAGE, chatUsage); // metadata only
}
return Msg.builderForRole(msg.getRole())
...
.build(); // ← missing .usage(chatUsage)
}getChatUsage() has a metadata fallback, so that method still returns something — but getUsage() (the canonical accessor) is null.
Expected Behavior
Both the native path (doNativeStructuredCall) and the fallback path (doFallbackStructuredCall) should preserve the ChatUsage on the returned Msg via the usage field, consistent with non-structured doCall.
Suggested Fix
// wrapNativeStructuredResult — add .usage()
return Msg.builderForRole(result.getRole())
.id(result.getId())
.name(result.getName())
.content(result.getContent())
.metadata(metadata)
.timestamp(result.getTimestamp())
.usage(result.getUsage()) // ← add this
.build();
// mergeCollectedMetadata — pass usage to builder
return Msg.builderForRole(msg.getRole())
...
.usage(chatUsage) // ← add this
.build();Environment
- Branch: main (commit d588528)
- Version: 2.0.3-SNAPSHOT
Metadata
Metadata
Assignees
Labels
No labels
Activity
xihongshichaojidan8 commentedon Sep 3, 2026
Hi, I'd like to work on this issue.
I've verified both affected paths against the current code:
wrapNativeStructuredResultrebuilds the native structured-output message without copyingresult.getUsage(), whilemergeCollectedMetadataonly stores the aggregated usage in metadata, so the existinggetChatUsage()fallback masks the fact that canonicalgetUsage()remains null.I plan to keep the fix focused by propagating usage through both builders and adding regression coverage for the native and fallback structured-output paths that asserts
Msg.getUsage()retains the expected values. I'll run the structured-output tests, the full core suite, and Spotless checks.fix(core): preserve usage in structured output messages (#2966)