Skip to content

fix(spring-ai): preserve reasoning content across model turns - #1913

Open
zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/spring-ai-reasoning-metadata
Open

zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/spring-ai-reasoning-metadata

Conversation

@zhangxiangnan

@zhangxiangnan zhangxiangnan commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

Related to #1616; original report and proposed branch.

Preserve Spring AI reasoningContent as plain ADK thought parts through JSON persistence, then restore thought text on subsequent assistant turns, including turns without tools. No private marker is stored in partMetadata, so the same session can switch to Gemini Vertex; Spring AI OpenAI sends the restored field as reasoning_content, including when the provider originally returned reasoning.

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

  • Spring AI module on JDK 21: 309 passed, 20 skipped, no failures/errors (329 discovered), after rebasing onto 0239ff08 in commit c8687c4f.
  • Tests remain in existing MessageConverterTest, SpringAITest, SpringAIIntegrationTest and StreamingResponseAggregatorTest: all 125 pass, included in the module total (including the two upstream portable-options warning tests).
  • Before this rebase, the original 123 cases produced 11 failed tests against the upstream baseline (548d0a13) and 11 against the previous PR implementation (c99de7d0), in separate comparison runs.
  • Coverage includes JSON replay, interleaved streams/resubscription, repeated incremental thoughts, changing response IDs, the public converter/aggregator, and a same-session switch to Vertex.
  • OpenAI HTTP/SSE and Vertex requests use local fixtures; no live provider or external session backend was used.
  • Rebase preserved the upstream portable-options warning change and both tests. The only manual conflict resolution combined the logger and parameterized-test imports; the seven-file PR patch is otherwise unchanged. Guava factory scan and git diff --check pass.
./mvnw -pl contrib/spring-ai -am \
  '-Dtest=com.google.adk.models.springai.**' \
  -Dsurefire.failIfNoSpecifiedTests=false test-compile surefire:test

@zhangxiangnan
zhangxiangnan marked this pull request as ready for review November 24, 2026 03:54
@hemasekhar-p hemasekhar-p self-assigned this Nov 26, 2026
@hemasekhar-p

Copy link
Copy Markdown
Contributor

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 damianmomotgoogle left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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".

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.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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. */

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.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

Renamed both converter tests to the suggested method_scenario_outcome style in 5f31a1d.

@damianmomotgoogle damianmomotgoogle added waiting on author Awaiting response from author. Failing that, maintainers will eventually closed it as stale. waiting on reporter Waiting for reaction by reporter. Failing that, maintainers will eventually closed it as stale. and removed needs review waiting on author Awaiting response from author. Failing that, maintainers will eventually closed it as stale. labels Nov 27, 2026
@zhangxiangnan
zhangxiangnan force-pushed the fix/spring-ai-reasoning-metadata branch from c99de7d to 5f31a1d Compare November 27, 2026 12:08
@zhangxiangnan

Copy link
Copy Markdown
Contributor Author

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.
@zhangxiangnan
zhangxiangnan force-pushed the fix/spring-ai-reasoning-metadata branch from 5f31a1d to c8687c4 Compare December 4, 2026 15:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting on reporter Waiting for reaction by reporter. Failing that, maintainers will eventually closed it as stale.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants