Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -93,6 +94,8 @@ public class MessageConverter {
*/
private static final String THOUGHT_SIGNATURES_KEY = "thoughtSignatures";

private static final String REASONING_CONTENT_KEY = "reasoningContent";

/** Metadata key the Spring AI Google GenAI provider uses to flag a generation as thought text. */
private static final String IS_THOUGHT_KEY = "isThought";

Expand Down Expand Up @@ -574,6 +577,7 @@ private ImmutableList<Message> handleUserContent(Content content) {

private AssistantMessage handleAssistantContent(Content content) {
StringBuilder textBuilder = new StringBuilder();
StringBuilder reasoning = new StringBuilder();
List<AssistantMessage.ToolCall> toolCalls = new ArrayList<>();
List<byte[]> thoughtSignatures = new ArrayList<>();
List<Media> mediaList = new ArrayList<>();
Expand All @@ -582,6 +586,8 @@ private AssistantMessage handleAssistantContent(Content content) {
if (part.text().isPresent()) {
if (!part.thought().orElse(false)) {
textBuilder.append(part.text().get());
} else {
reasoning.append(part.text().get());
}
} else if (part.functionCall().isPresent()) {
FunctionCall functionCall = part.functionCall().get();
Expand All @@ -600,11 +606,16 @@ private AssistantMessage handleAssistantContent(Content content) {
}

String text = textBuilder.toString();
if (toolCalls.isEmpty() && mediaList.isEmpty()) {
Map<String, Object> properties = new LinkedHashMap<>();
if (!thoughtSignatures.isEmpty()) {
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.

}
if (toolCalls.isEmpty() && mediaList.isEmpty() && properties.isEmpty()) {
return new AssistantMessage(text);
}
Map<String, Object> properties =
thoughtSignatures.isEmpty() ? Map.of() : Map.of(THOUGHT_SIGNATURES_KEY, thoughtSignatures);
return AssistantMessage.builder()
.content(text)
.properties(properties)
Expand Down Expand Up @@ -767,9 +778,13 @@ private FinishReason toAdkFinishReason(String finishReason) {

private Content convertAssistantMessageToContent(AssistantMessage assistantMessage) {
List<Part> parts = new ArrayList<>();
Map<String, Object> metadata = assistantMessage.getMetadata();
Object reasoning = metadata == null ? null : metadata.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.

parts.add(Part.builder().text(reasoningText).thought(true).build());
}

if (assistantMessage.getText() != null && !assistantMessage.getText().isEmpty()) {
Map<String, Object> metadata = assistantMessage.getMetadata();
boolean isThought =
metadata != null
&& (Boolean.TRUE.equals(metadata.get(IS_THOUGHT_KEY))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,16 @@
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jspecify.annotations.Nullable;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.model.StreamingChatModel;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
Expand All @@ -44,6 +49,9 @@
*
* <p>This adapter allows Spring AI models to be used within the ADK framework by converting between
* ADK's LlmRequest/LlmResponse format and Spring AI's Prompt/ChatResponse format.
*
* <p>Streaming {@code reasoningContent} with OpenAI's {@code id}/{@code index} metadata is
* cumulative per response and choice. Without that pair, reasoning text is treated as incremental.
*/
public class SpringAI extends BaseLlm {

Expand Down Expand Up @@ -240,14 +248,16 @@ private final class StreamAggregation {
private final List<Part> parts = new ArrayList<>();
private final StringBuilder text = new StringBuilder();
private boolean textIsThought;
private final Map<String, String> reasoning = new HashMap<>();
private @Nullable GenerateContentResponseUsageMetadata usage;
private @Nullable String modelVersion;
private @Nullable LlmResponse finishingChunk;
private boolean receivedChunk;

private Flowable<LlmResponse> processChunk(ChatResponse chatResponse) {
receivedChunk = true;
LlmResponse chunk = withFunctionCallIds(messageConverter.toLlmResponse(chatResponse));
LlmResponse chunk =
withFunctionCallIds(messageConverter.toLlmResponse(reasoningDelta(chatResponse)));
chunk.usageMetadata().ifPresent(chunkUsage -> usage = chunkUsage);
chunk.modelVersion().ifPresent(version -> modelVersion = version);
if (chunk.finishReason().isPresent()) {
Expand Down Expand Up @@ -280,6 +290,34 @@ private Flowable<LlmResponse> processChunk(ChatResponse chatResponse) {
.build());
}

/** Trims OpenAI cumulative reasoning metadata to the text not yet emitted for each choice. */
private ChatResponse reasoningDelta(ChatResponse response) {
List<Generation> generations = new ArrayList<>();
for (Generation generation : response.getResults()) {
AssistantMessage message = generation.getOutput();
Map<String, Object> metadata = message == null ? null : message.getMetadata();
if (metadata != null
&& metadata.get("id") instanceof String id
&& !id.isEmpty()
&& metadata.get("index") instanceof Number index
&& metadata.get("reasoningContent") instanceof String current) {
String key = id + ":" + index;
String previous = reasoning.getOrDefault(key, "");
String delta =
current.startsWith(previous) ? current.substring(previous.length()) : current;
reasoning.put(key, current);
Map<String, Object> properties = new LinkedHashMap<>(metadata);
properties.put("reasoningContent", delta);
generations.add(
new Generation(
message.mutate().properties(properties).build(), generation.getMetadata()));
} else {
generations.add(generation);
}
}
return new ChatResponse(generations, response.getMetadata());
}

private void flushText() {
if (text.isEmpty()) {
return;
Expand Down Expand Up @@ -433,6 +471,7 @@ private int extractOutputTokenCount(ChatResponse chatResponse) {
private String extractTextFromResponse(LlmResponse response) {
if (response.content().isPresent() && response.content().get().parts().isPresent()) {
return response.content().get().parts().get().stream()
.filter(part -> !part.thought().orElse(false))
.map(part -> part.text().orElse(""))
.filter(text -> text != null && !text.isEmpty())
.findFirst()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* Aggregates streaming responses from Spring AI models.
* Aggregates answer text and tool calls from Spring AI streaming responses, excluding thoughts.
*
* <p>This class helps manage the accumulation of partial responses in streaming mode, ensuring that
* text content is properly concatenated and tool calls are correctly handled.
Expand Down Expand Up @@ -61,6 +61,9 @@ public LlmResponse processStreamingResponse(LlmResponse response) {
try {
// Process each part in the response
for (Part part : content.parts().get()) {
if (part.thought().orElse(false)) {
continue;
}
if (part.text().isPresent()) {
textAccumulator.append(part.text().get());
} else if (part.functionCall().isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import com.google.adk.models.LlmRequest;
import com.google.adk.models.LlmResponse;
import com.google.adk.tools.BaseTool;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.genai.types.Content;
import com.google.genai.types.FinishReason;
import com.google.genai.types.FunctionCall;
Expand All @@ -44,6 +46,8 @@
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
Expand Down Expand Up @@ -1194,6 +1198,71 @@ void toAdkContent_assistantMessageWithMediaAndToolCalls_roundTripsWithToSpringAi
assertThat(roundTripped.getToolCalls()).hasSize(1);
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
void toLlmResponse_reasoningContent_roundTripsThroughJsonWithoutBecomingAnswerText(
boolean withToolCall) {
AssistantMessage.Builder builder =
AssistantMessage.builder()
.content("Answer")
.properties(ImmutableMap.of("reasoningContent", "Check first", "index", 0));
if (withToolCall) {
builder.toolCalls(
ImmutableList.of(new AssistantMessage.ToolCall("call_1", "function", "inspect", "{}")));
}
LlmResponse response =
messageConverter.toLlmResponse(
new ChatResponse(
ImmutableList.of(
new Generation(builder.build()),
new Generation(
AssistantMessage.builder()
.content("Other candidate")
.properties(
ImmutableMap.of("reasoningContent", "Other reasoning", "index", 1))
.build()))));
Content restored = Content.fromJson(response.content().orElseThrow().toJson());
List<Part> parts = restored.parts().orElseThrow();
assertThat(parts.get(0).thought()).contains(true);
assertThat(parts.get(0).text()).contains("Check first");
assertThat(parts.get(0).partMetadata()).isEmpty();
assertThat(parts.get(1).text()).contains("Answer");
AssistantMessage replayed =
(AssistantMessage) messageConverter.toSpringAiMessages(restored).get(0);
assertThat(replayed.getText()).isEqualTo("Answer");
assertThat(replayed.getMetadata()).containsEntry("reasoningContent", "Check first");
assertThat(replayed.getToolCalls()).hasSize(withToolCall ? 1 : 0);
if (withToolCall) {
assertThat(replayed.getToolCalls().get(0).id()).isEqualTo("call_1");
}
}

@Test
void toAdkContent_nullMetadata_preservesAnswer() {
AssistantMessage message =
new AssistantMessage("Answer") {
@Override
public Map<String, Object> getMetadata() {
return null;
}
};
assertThat(messageConverter.toAdkContent(message).parts().orElseThrow())
.containsExactly(Part.fromText("Answer"));
}

@Test
void toAdkContent_emptyOrNonStringReasoning_doesNotCreateThoughtPart() {
for (Object reasoning : ImmutableList.of("", 42)) {
Content content =
messageConverter.toAdkContent(
AssistantMessage.builder()
.content("Answer")
.properties(ImmutableMap.of("reasoningContent", reasoning))
.build());
assertThat(content.parts().orElseThrow()).containsExactly(Part.fromText("Answer"));
}
}

@Test
void toLlmResponse_multipleCandidates_keepsOnlyFirstCandidate() {
Generation firstChoice =
Expand Down Expand Up @@ -1564,7 +1633,7 @@ void toLlmResponse_finishReasonsAndMultiGeneration_mapsFinishReasonsAndMergesPar
}

@Test
void toSpringAiMessages_assistantContentWithThoughtAndIdlessFunctionCall_filtersThought() {
void toSpringAiMessages_assistantContentWithThoughtAndIdlessFunctionCall_separatesReasoning() {
Content assistantContent =
Content.builder()
.role("model")
Expand All @@ -1582,6 +1651,8 @@ void toSpringAiMessages_assistantContentWithThoughtAndIdlessFunctionCall_filters
assertThat(messages).hasSize(1);
AssistantMessage assistantMessage = (AssistantMessage) messages.get(0);
assertThat(assistantMessage.getText()).isEqualTo("Visible answer.");
assertThat(assistantMessage.getMetadata())
.containsEntry("reasoningContent", "internal thought");
assertThat(assistantMessage.getToolCalls()).hasSize(1);
assertThat(assistantMessage.getToolCalls().get(0).id()).isEmpty();
}
Expand Down
Loading