Repository navigation
fix(spring-ai): preserve reasoning content across model turns - #1913
zhangxiangnan wants to merge 1 commit into
Conversation
|
Hi @zhangxiangnan, Thank you for your contribution and for taking the time to submit this pull request. Our team is currently reviewing your changes and we will reach out if we need any further information. |
damianmomotgoogle
left a comment
There was a problem hiding this comment.
CL (LOW): The description is about 590 words, mostly test tables, local Maven setup, and process notes. It also says "Fixes #1616" while the commit says "Related to #1616". It omits two user-visible effects: later requests include reasoning_content on every earlier assistant turn, and stored events include a springAiReasoningContent marker. Two or three sentences summarizing the before-and-after behavior would cover it.
| Part.builder() | ||
| .text(reasoningText) | ||
| .thought(true) | ||
| .partMetadata(Map.of(REASONING_CONTENT_MARKER, true)) |
There was a problem hiding this comment.
BREAKING (HIGH): If the same agent later serves a session written by this bridge on Gemini via Vertex AI (after a model change or through a fallback BaseLlm), every request fails with IllegalArgumentException: partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode. ADK sends an agent's own thought parts to its model unchanged (Gemini.java:296), and google-genai rejects Part.partMetadata in Vertex mode. VertexAiSessionService also sends the marker to Agent Engine (VertexAiSessionService.java:348). ADK Python strips part_metadata there because that API rejects it (vertex_ai_session_service.py:136).
Repro (local servers, no credentials):
// Turn 1: LlmAgent "assistant" on new SpringAI(openAiChatModel); the server returns "reasoning_content".
// Turn 2: a new LlmAgent "assistant" on the same InMemorySessionService, with this model:
new Gemini("gemini-2.5-flash", Client.builder().vertexAI(true).project("p").location("us-central1")
.credentials(GoogleCredentials.create(new AccessToken("fake", null))).build());
// Head: turn 2 throws before any HTTP request. Base: turn 2 succeeds.Fix: Store a plain thought part and replay every text thought part as reasoningContent, like ADK Python (lite_llm.py:1866, lite_llm.py:1947). Among the Anthropic, Google GenAI, Ollama, and OpenAI providers, only OpenAI reads that key. Detect the cumulative stream from provider metadata instead of a stored marker.
There was a problem hiding this comment.
Removed the persisted marker in 5f31a1d. Reasoning is now stored as plain thought parts and replayed from text thoughts, following the Python approach. Added a same-agent/same-session SpringAI-to-Gemini-Vertex test using a local HTTP server: the old PR throws the reported partMetadata exception before sending, while the fix sends the history successfully. JSON round-trip tests also assert that no partMetadata marker is stored.
| private Content convertAssistantMessageToContent(AssistantMessage assistantMessage) { | ||
| List<Part> parts = new ArrayList<>(); | ||
| Object reasoning = assistantMessage.getMetadata().get(REASONING_CONTENT_KEY); | ||
| if (reasoning instanceof String reasoningText && !reasoningText.isEmpty()) { |
There was a problem hiding this comment.
BREAKING (HIGH): Streaming Spring AI OpenAI through the public toLlmResponse(chatResponse, true) and aggregating chunks with the public StreamingResponseAggregator now corrupts the answer text. Spring AI repeats the full reasoning on every chunk (OpenAiChatModel.java:339). Each chunk now includes a cumulative thought part, and the aggregator appends every text part (StreamingResponseAggregator.java:65).
Repro: Run a real OpenAiChatModel against a local server streaming reasoning "Think", " hard", then content "It is", " sunny.". Base: It is sunny. Head: ThinkThink hardThink hardIt isThink hard sunny.Think hard.
There was a problem hiding this comment.
Fixed in 5f31a1d: StreamingResponseAggregator now excludes thought parts from answer aggregation. Added coverage in its existing test class through the public converter, and extended the real OpenAiChatModel SSE fixture to exercise toLlmResponse(chunk, true) plus the public aggregator. The previous PR reproduces the repeated-reasoning answer; the fix preserves answer text and tool calls.
| properties.put(THOUGHT_SIGNATURES_KEY, thoughtSignatures); | ||
| } | ||
| if (!reasoning.isEmpty()) { | ||
| properties.put(REASONING_CONTENT_KEY, reasoning.toString()); |
There was a problem hiding this comment.
DESIGN (MEDIUM): Every later request now sends reasoning_content on every earlier assistant turn, with or without tools. It also sends reasoning_content to providers that returned reasoning, because Spring AI reads both into reasoningContent and always writes reasoning_content back (OpenAiChatModel.java:680). DeepSeek only needs it when the request includes tools. For example, a second turn without tools changes from {"role":"assistant","content":"Hi."} to {"role":"assistant","content":"Hi.","reasoning_content":"Greet back"}.
ADK Python sends it for every non-Anthropic provider, lite_llm.py:1951) and state it in the description.
There was a problem hiding this comment.
Adopted the plain-thought replay behavior and documented it explicitly in 5f31a1d: later requests restore reasoning on earlier assistant turns both with and without tools. The description also calls out Spring AI's outgoing reasoning_content field when the provider originally returned reasoning. The converter round-trip test covers both tool/no-tool variants.
| && Boolean.TRUE.equals( | ||
| part.partMetadata() | ||
| .orElse(Map.of()) | ||
| .get(MessageConverter.REASONING_CONTENT_MARKER))) { |
There was a problem hiding this comment.
TEST (MEDIUM): Deleting this marker condition breaks no tests: all 105 tests in SpringAITest, MessageConverterTest, and SpringAIIntegrationTest still pass. No test guards unmarked thought streams (Google GenAI isThought, Anthropic thinking) against prefix stripping. Add a streaming test with two equal unmarked thought chunks ("a", "a") that expects "aa".
There was a problem hiding this comment.
Updated the existing mixed-thought streaming test in 5f31a1d to include two ordinary thought chunks "a", "a", alongside cumulative reasoning. Both ordinary chunks are retained. Cumulative normalization now operates on provider response metadata before conversion, so it no longer strips prefixes from ordinary thought parts.
| .get(MessageConverter.REASONING_CONTENT_MARKER))) { | ||
| String current = part.text().get(); | ||
| String delta = | ||
| current.startsWith(reasoning) ? current.substring(reasoning.length()) : current; |
There was a problem hiding this comment.
EDGE CASE (LOW): When reasoning arrives as plain deltas, a delta equal to the previous one is dropped and a delta starting with it loses that prefix, so "Wait", ".", ".", ". Done" is stored as Wait. Done. This happens with a custom StreamingChatModel or a server that changes the chunk id mid-stream, because Spring AI accumulates per id:index (OpenAiChatModel.java:339): two "a" chunks with ids chunk-1 and chunk-2 are stored as a. Limit prefix stripping to Spring AI OpenAI's cumulative output, or document that reasoningContent must be cumulative.
There was a problem hiding this comment.
Fixed in 5f31a1d by tracking cumulative reasoning per id:index instead of across the entire stream. Without that metadata pair, reasoning remains incremental. Added both no-ID and changing-ID cases for "Wait", ".", ".", ". Done"; both preserve "Wait... Done". The streaming contract is also documented in the class Javadoc.
|
|
||
| private Content convertAssistantMessageToContent(AssistantMessage assistantMessage) { | ||
| List<Part> parts = new ArrayList<>(); | ||
| Object reasoning = assistantMessage.getMetadata().get(REASONING_CONTENT_KEY); |
There was a problem hiding this comment.
EDGE CASE (LOW): If an AssistantMessage subclass returns null from getMetadata(), this line now throws NullPointerException. Base handled it, and the method still checks metadata != null at line 785. Spring AI's contract says metadata is non-null, so only a misbehaving subclass hits this. Reading metadata once under the existing guard fixes it and avoids the second lookup.
There was a problem hiding this comment.
Moved the reasoning lookup under the existing nullable metadata handling and reused the metadata variable for answer conversion in 5f31a1d. Added an AssistantMessage subclass returning null metadata: it reproduces the old PR's NPE and now preserves the answer.
| List<Part> parts = new ArrayList<>(); | ||
| Object reasoning = assistantMessage.getMetadata().get(REASONING_CONTENT_KEY); | ||
| if (reasoning instanceof String reasoningText && !reasoningText.isEmpty()) { | ||
| parts.add( |
There was a problem hiding this comment.
BUG (LOW): With content logging enabled (includeContent), the non-streaming "Response from" debug log now prints reasoning instead of the answer. This thought part comes first, and extractTextFromResponse returns the first non-empty text (SpringAI.java:470). Code trace only. Skip thought parts there.
There was a problem hiding this comment.
extractTextFromResponse now skips thought parts in 5f31a1d. Added a non-streaming test through generateContent that verifies the observability handler receives "Answer", not "Think"; the test fails on the old PR and passes with the fix.
| for (Part part : content.parts().orElse(List.of())) { | ||
| if (part.thought().orElse(false) | ||
| && part.text().isPresent() | ||
| && Boolean.TRUE.equals( |
There was a problem hiding this comment.
CLEANUP (LOW): This marker check duplicates MessageConverter.java:579, which is why the constant is package-private. If you keep the marker, share a package-private isReasoningPart(Part) in MessageConverter and make the constant private. If you remove it (see the Vertex comment), both checks disappear.
There was a problem hiding this comment.
Removed the marker constant and both checks in 5f31a1d. No marker or marker-specific aggregation state remains.
| .build()); | ||
| } | ||
|
|
||
| /** Spring AI OpenAI emits cumulative reasoning even while answer text remains incremental. */ |
There was a problem hiding this comment.
CLEANUP (LOW): This Javadoc describes the provider behavior instead of what the method does (Google Java Style 7.2). Suggestion: /** Trims each marked reasoning part to the text not yet emitted, since Spring AI OpenAI repeats the accumulated reasoning on every chunk. */
There was a problem hiding this comment.
Updated the Javadoc in 5f31a1d to describe the operation: trimming cumulative reasoning metadata to text not yet emitted for each choice. Normalization now precedes conversion and uses response ID/choice metadata.
|
|
||
| @ParameterizedTest | ||
| @ValueSource(booleans = {false, true}) | ||
| void reasoningContent_roundTripsThroughJsonWithoutBecomingAnswerText(boolean withToolCall) { |
There was a problem hiding this comment.
CLEANUP (LOW): This test name and the one at line 1183 do not follow the file's method_scenario_outcome pattern (for example, toLlmResponse_multipleCandidates_keepsOnlyFirstCandidate). Suggestion: toLlmResponse_reasoningContent_roundTripsThroughJsonWithoutBecomingAnswerText and toAdkContent_emptyOrNonStringReasoning_doesNotCreateThoughtPart.
There was a problem hiding this comment.
Renamed both converter tests to the suggested method_scenario_outcome style in 5f31a1d.
c99de7d to
5f31a1d
Compare
|
Thanks for the detailed review, @damianmomotgoogle. Addressed the inline comments in 5f31a1d and shortened the description to the final behavior and validation. The description and commit now both use “Related to #1616”; the stored marker has been removed, and replay on ordinary as well as tool-call turns is explicit. Validation: the Spring AI module passes 307 tests, with 20 skipped and no failures/errors. All 123 tests in the four affected existing test classes pass. Separate runs against upstream and the previous PR implementation each produce 11 failed tests, covering the original defect and review regressions. Provider requests were exercised against local HTTP/SSE fixtures, not live services. |
Preserve reasoningContent as plain thought parts and replay thought text on assistant turns. Normalize cumulative reasoning per response and choice within each subscription, without persisting provider markers. Keep thought text out of public answer aggregation and response logging. Cover JSON replay, Vertex model switching, cumulative and incremental streams, and public conversion/aggregation in existing test classes. Related to google#1616.
5f31a1d to
c8687c4
Compare
Description of Change
Related to #1616; original report and proposed branch.
Preserve Spring AI
reasoningContentas plain ADK thought parts through JSON persistence, then restore thought text on subsequent assistant turns, including turns without tools. No private marker is stored inpartMetadata, so the same session can switch to Gemini Vertex; Spring AI OpenAI sends the restored field asreasoning_content, including when the provider originally returnedreasoning.Normalize cumulative reasoning per OpenAI response ID and choice within each stream subscription; reasoning without that metadata remains incremental. Exclude thought parts from the public streaming aggregator's answer and from response logging; the SpringAI adapter retains them as separate thought parts. Anthropic signed-block replay remains separate (#1912).
Validation
0239ff08in commitc8687c4f.MessageConverterTest,SpringAITest,SpringAIIntegrationTestandStreamingResponseAggregatorTest: all 125 pass, included in the module total (including the two upstream portable-options warning tests).548d0a13) and 11 against the previous PR implementation (c99de7d0), in separate comparison runs.git diff --checkpass../mvnw -pl contrib/spring-ai -am \ '-Dtest=com.google.adk.models.springai.**' \ -Dsurefire.failIfNoSpecifiedTests=false test-compile surefire:test