Repository navigation
fix(core): retain reasoning details from all streaming chunks - #3128
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Fixes streaming loss of OpenAI reasoning_details by accumulating records across chunks and adding regression coverage.
Changes:
- Accumulates reasoning details in order and clears them on reset.
- Adds core accumulator tests and an end-to-end OpenAI replay test.
- Preserves existing metadata behavior.
File summaries
| File | Description |
|---|---|
| agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/formatter/StreamingReasoningDetailsReplayTest.java | Updated as part of this pull request. |
| agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ThinkingAccumulatorReasoningDetailsTest.java | Updated as part of this pull request. |
| agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ThinkingAccumulator.java | Updated as part of this pull request. |
Review details
- Files reviewed: 3/3 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if (!metadata.isEmpty()) { | ||
| builder.metadata(metadata); | ||
| Map<String, Object> aggregatedMetadata = new HashMap<>(metadata); | ||
| if (!reasoningDetails.isEmpty()) { |
There was a problem hiding this comment.
Fixed in 958190b. The accumulator now tracks whether any list was received, independently of its size, and copies even an empty accumulated list on every build. The new regression reproduces the bug on the previous head: expected [] but got [late mutation] after the caller mutated its originally empty list. It now passes. Reset also clears the list-seen flag. Re-ran the selected core/OpenAI suites: 134 passed, 1 existing upstream skip; scoped Spotless and diff checks pass.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Good, well-scoped fix for #3127: ThinkingAccumulator previously let metadata.putAll overwrite reasoningDetails on every chunk, so only the last chunk's encrypted records survived the stream. Accumulating the list in received order plus copying it into a fresh metadata map per buildAggregated() is the right shape, and the two-layer test (unit + parse→accumulate→convert regression) demonstrates the original [rs_1] failure convincingly. LGTM — approving with two non-blocking notes.
Findings
- [Info]
ThinkingAccumulator.java:51— unconditional concatenation assumes per-chunk incremental payloads; a cumulative-snapshot gateway (or a re-sent detailid) would now produce duplicates that are replayed and persisted. - [Info]
ThinkingAccumulator.java:76— asymmetric handling between the accumulated list and the last-valueputAllwhen a chunk carries a non-Listvalue under the same key.
What I verified locally
ThinkingBlock.METADATA_REASONING_DETAILSis the only metadata key with list semantics; all read sites (OpenAIMessageConverter:342,OpenAIMultiAgentFormatter:166) already guard withinstanceof List, so making the value always aListis backward compatible for consumers.ThinkingBlockcopies the metadata map but not its values, so the per-buildnew ArrayList<>(reasoningDetails)is what keeps already-emitted blocks stable — the added independence test covers this properly.- No public API change;
reset()clears all three fields consistently.
Suggestions
If you want to harden the incremental assumption without dragging provider DTOs into core, LinkedHashMap-style keying on (id, index) for Map entries would be enough, with a fallback to plain append for unknown shapes.
Automated review by github-manager-bot
| Object details = block.getMetadata().get(ThinkingBlock.METADATA_REASONING_DETAILS); | ||
| if (details instanceof List<?> list) { | ||
| // Each streaming chunk carries only its own reasoning details, not a snapshot. | ||
| reasoningDetails.addAll(list); |
There was a problem hiding this comment.
The accumulation is an unconditional concatenation, so it assumes each chunk carries only its own (incremental) reasoning_details. That holds for the current OpenAIResponseParser, which emits the per-chunk list. If an OpenAI-compatible gateway instead sends a cumulative snapshot per chunk, or re-sends the same detail id, this now produces duplicate entries that get replayed to the model and persisted in agent state. A cheap guard would be to skip items whose identity was already accumulated (for map-shaped entries, id + index are available without depending on provider DTOs), or to state the incremental-chunk assumption explicitly in the class javadoc so future providers cannot break it silently.
There was a problem hiding this comment.
Addressed via the documentation option in 958190b. The class Javadoc explicitly requires incremental records and tells snapshot-emitting providers to normalize before accumulation. I kept the received order without identity-based deduplication: repeated identifiers can represent distinct streaming fragments, and deduplicating them in provider-neutral core could discard valid data.
| builder.metadata(metadata); | ||
| Map<String, Object> aggregatedMetadata = new HashMap<>(metadata); | ||
| if (!reasoningDetails.isEmpty()) { | ||
| aggregatedMetadata.put( |
There was a problem hiding this comment.
Two one-sided cases here: (1) metadata.putAll() still keeps last-value semantics for the same key, so if a chunk carries a non-List value under METADATA_REASONING_DETAILS (single object / JSON string), the accumulated list silently wins in the aggregated block and the scalar is lost. (2) Conversely, a chunk that carries an empty list last still leaves the previous records in place, which is the desired outcome but is only documented in the inline comment. Consider normalising: if the incoming value is not a List, either log at debug or wrap it into the accumulated list, so the aggregated block never drops provider payload.
There was a problem hiding this comment.
Clarified and tested in 958190b. Once any list (including an empty one) has been received, later non-list metadata cannot replace its accumulated records. Before the first list, non-list values retain the existing last-value behavior; reset restores that initial state. The added regression covers those transitions. I avoided wrapping malformed scalar payloads into a reasoning record because readers expect actual detail objects/maps and wrapping would not establish valid semantics. The class Javadoc now states both the empty-list and non-list rules.
|
@jujn Thanks for generalizing the metadata merge in 4004cfe. I kept that design and added a small snapshot follow-up in ac48a30.
details(accumulator.buildAggregated()).clear();
assertEquals(List.of("a", "b"), details(accumulator.buildAggregated()));fails on 4004cfe: The follow-up copies each list value when building the returned metadata snapshot. Generic list accumulation and scalar last-write-wins remain as in your update. The extended test and selected core/OpenAI suites now pass: 134 passed, 1 existing upstream skip; scoped Spotless and diff checks pass. I also updated the PR description to describe the generalized implementation. |
ac48a30 to
4004cfe
Compare
AgentScope-Java Version
2.0.3-SNAPSHOT, based on main7399ed61b2ea22b25e2ead4dec9d59df6a77785c.Description
Fixes #3127.
When OpenAI-compatible streaming responses carry
reasoning_detailsin multiple chunks,ThinkingAccumulatorreplaces each earlier list viametadata.putAll. The final stored/replayed assistant message therefore contains only the last chunk's records. A local parser -> accumulator -> converter regression receives two distinct encrypted records and reproduces[rs_1]instead of[rs_0, rs_1]on unmodified main.List-valued metadata is now accumulated in stream order, with copies both when accepting input lists and when building aggregated output. Empty lists receive the same isolation. Scalar values use last-write-wins, including when replacing an earlier list; a list following a scalar starts a new accumulated list. Reset clears the accumulated metadata. The change preserves opaque list elements without introducing provider-specific DTO dependencies in core.
Tests cover multi-chunk order, empty lists, thinking text, scalar/list transitions, caller-list mutation, independence of older and current aggregated snapshots, and reset. The integration regression uses the actual JSON parser and message converter with synthetic local response chunks and no model API calls.
Validation
expected: <[rs_0, rs_1]> but was: <[rs_1]>(1 failure, 0 errors).expected: <[a, b]> but was: <[]>). It passes after copying list values inbuildAggregated().Spotless apply/check passed for the changed files; the final follow-up was checked with:
git diff --cached --checkpassed. Environment: Windows 11, Temurin 17.0.15, Maven 3.9.12. The full multi-module suite and live provider APIs were not run locally.Checklist
mvn test(not run locally).AI assistance was used for source review, implementation and tests. The reported reproduction and validation commands were executed locally.