From 2eae191dcaee16faeebf40092399f1640276437a Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Tue, 1 Dec 2026 03:45:23 -0800 Subject: [PATCH] fix(models): use the shared StreamingResponseAggregator in Spring AI PiperOrigin-RevId: 1033408940 --- .../google/adk/models/springai/SpringAI.java | 144 ++++----------- .../springai/StreamingResponseAggregator.java | 3 + .../adk/models/springai/SpringAITest.java | 169 +++++++++++++++++- .../StreamingResponseAggregatorTest.java | 1 + ...ingResponseAggregatorThreadSafetyTest.java | 1 + .../models/StreamingResponseAggregator.java | 61 ++++--- .../StreamingResponseAggregatorTest.java | 61 +++++++ 7 files changed, 300 insertions(+), 140 deletions(-) diff --git a/contrib/spring-ai/src/main/java/com/google/adk/models/springai/SpringAI.java b/contrib/spring-ai/src/main/java/com/google/adk/models/springai/SpringAI.java index abf161edce..3db7fe8e48 100644 --- a/contrib/spring-ai/src/main/java/com/google/adk/models/springai/SpringAI.java +++ b/contrib/spring-ai/src/main/java/com/google/adk/models/springai/SpringAI.java @@ -18,20 +18,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.adk.models.BaseLlm; import com.google.adk.models.BaseLlmConnection; -import com.google.adk.models.FunctionCallIds; import com.google.adk.models.LlmRequest; import com.google.adk.models.LlmResponse; import com.google.adk.models.springai.error.SpringAIErrorMapper; import com.google.adk.models.springai.observability.SpringAIObservabilityHandler; import com.google.adk.models.springai.properties.SpringAIProperties; import com.google.genai.types.Content; -import com.google.genai.types.FunctionCall; -import com.google.genai.types.GenerateContentResponseUsageMetadata; import com.google.genai.types.Part; import io.reactivex.rxjava3.core.Flowable; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Optional; import org.jspecify.annotations.Nullable; import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.chat.model.ChatResponse; @@ -233,126 +231,52 @@ private Flowable streamResponses(LlmRequest llmRequest) { .concatWith(Flowable.defer(aggregation::aggregatedResponse)); } - /** The state of one stream, used to build its aggregated response. */ + /** The state of one stream: the shared aggregator and what Spring AI's final response adds. */ private final class StreamAggregation { - // Parts in stream order. Consecutive text, or consecutive thought text, merges into one part; - // function calls, media and other parts are kept as they arrived. - private final List parts = new ArrayList<>(); - private final StringBuilder text = new StringBuilder(); - private boolean textIsThought; - private @Nullable GenerateContentResponseUsageMetadata usage; + private final com.google.adk.models.StreamingResponseAggregator aggregator = + new com.google.adk.models.StreamingResponseAggregator(); private @Nullable String modelVersion; - private @Nullable LlmResponse finishingChunk; - private boolean receivedChunk; private Flowable processChunk(ChatResponse chatResponse) { - receivedChunk = true; - LlmResponse chunk = withFunctionCallIds(messageConverter.toLlmResponse(chatResponse)); - chunk.usageMetadata().ifPresent(chunkUsage -> usage = chunkUsage); + LlmResponse chunk = messageConverter.toLlmResponse(chatResponse); chunk.modelVersion().ifPresent(version -> modelVersion = version); - if (chunk.finishReason().isPresent()) { - finishingChunk = chunk; - } - List chunkParts = chunk.content().flatMap(Content::parts).orElse(List.of()); - if (chunkParts.isEmpty()) { - return Flowable.empty(); - } - for (Part part : chunkParts) { - if (part.text().isPresent()) { - boolean isThought = part.thought().orElse(false); - if (isThought != textIsThought) { - flushText(); - } - textIsThought = isThought; - text.append(part.text().get()); - } else { - flushText(); - parts.add(part); - } - } - // As in Gemini, only the aggregated response reports an error. - return Flowable.just( - chunk.toBuilder() - .partial(true) - .turnComplete(null) - .errorCode(null) - .errorMessage(null) - .build()); - } - - private void flushText() { - if (text.isEmpty()) { - return; - } - Part.Builder part = Part.builder().text(text.toString()); - if (textIsThought) { - part.thought(true); - } - parts.add(part.build()); - text.setLength(0); + // As in Gemini, only the aggregated response reports an error or completes the turn. + return Flowable.fromOptional( + aggregator + .processResponse(chunk) + .map(partial -> + partial.toBuilder() + .turnComplete(null) + .errorCode(null) + .errorMessage(null) + .build())); } private Flowable aggregatedResponse() { - if (!receivedChunk) { - return Flowable.empty(); - } - flushText(); - LlmResponse.Builder aggregated = - LlmResponse.builder().partial(false).turnComplete(true).modelVersion(modelVersion); - // A stream without content still ends with a response, as Gemini's does. - if (!parts.isEmpty()) { - aggregated.content(Content.builder().role("model").parts(parts).build()); - } - if (usage != null) { - aggregated.usageMetadata(usage); - } - // Report how the stream ended, from the last chunk that said so, as ADK Python does. - if (finishingChunk != null) { - aggregated - .finishReason(finishingChunk.finishReason().orElse(null)) - .errorCode(finishingChunk.errorCode().orElse(null)) - .errorMessage(finishingChunk.errorMessage().orElse(null)); - } - return Flowable.just(aggregated.build()); + return Flowable.fromOptional(aggregator.aggregate().map(this::toFinalResponse)); } - } - /** - * Gives each function call without an id a client-side one, so the partial and aggregated - * responses carrying it share the same id. - */ - private static LlmResponse withFunctionCallIds(LlmResponse response) { - if (response.content().isEmpty()) { - return response; - } - Content content = response.content().get(); - List parts = content.parts().orElse(List.of()); - if (parts.stream() - .noneMatch(part -> part.functionCall().filter(SpringAI::lacksId).isPresent())) { - return response; + private LlmResponse toFinalResponse(LlmResponse aggregated) { + LlmResponse.Builder response = + aggregated.toBuilder().partial(false).turnComplete(true).modelVersion(modelVersion); + Content content = aggregated.content().orElse(null); + List parts = content == null ? List.of() : content.parts().orElse(List.of()); + // The aggregator keeps a content without parts as a stream terminator; drop it. + if (parts.isEmpty()) { + return response.content(null).build(); + } + // Mutable, like the aggregator's own parts: callbacks may edit them. + List finalParts = new ArrayList<>(parts.size()); + parts.forEach(part -> finalParts.add(withoutThoughtFalse(part))); + return response.content(content.toBuilder().parts(finalParts).build()).build(); } - return response.toBuilder() - .content( - content.toBuilder() - .parts(parts.stream().map(SpringAI::withFunctionCallId).toList()) - .build()) - .build(); - } - - private static Part withFunctionCallId(Part part) { - return part.functionCall() - .filter(SpringAI::lacksId) - .map( - call -> - part.toBuilder() - .functionCall( - call.toBuilder().id(FunctionCallIds.generateClientFunctionCallId()).build()) - .build()) - .orElse(part); } - private static boolean lacksId(FunctionCall call) { - return call.id().map(String::isEmpty).orElse(true); + // As in ADK Python, plain text carries no thought flag; the aggregator sets it to false. + private static Part withoutThoughtFalse(Part part) { + return part.thought().equals(Optional.of(false)) + ? part.toBuilder().clearThought().build() + : part; } @Override diff --git a/contrib/spring-ai/src/main/java/com/google/adk/models/springai/StreamingResponseAggregator.java b/contrib/spring-ai/src/main/java/com/google/adk/models/springai/StreamingResponseAggregator.java index da07104933..79e790f497 100644 --- a/contrib/spring-ai/src/main/java/com/google/adk/models/springai/StreamingResponseAggregator.java +++ b/contrib/spring-ai/src/main/java/com/google/adk/models/springai/StreamingResponseAggregator.java @@ -33,7 +33,10 @@ *

Thread Safety: This class is thread-safe. All public methods are synchronized to ensure * safe concurrent access. The internal state is protected using a combination of thread-safe data * structures and synchronization locks. + * + * @deprecated {@link SpringAI} no longer uses this class; it aggregates its streams itself. */ +@Deprecated public class StreamingResponseAggregator { private final StringBuffer textAccumulator = new StringBuffer(); diff --git a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/SpringAITest.java b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/SpringAITest.java index 538dc90b54..a5b835d88e 100644 --- a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/SpringAITest.java +++ b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/SpringAITest.java @@ -21,8 +21,15 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.adk.agents.LlmAgent; +import com.google.adk.agents.RunConfig; +import com.google.adk.events.Event; import com.google.adk.models.LlmRequest; import com.google.adk.models.LlmResponse; +import com.google.adk.models.springai.integrations.tools.WeatherTool; +import com.google.adk.runner.InMemoryRunner; +import com.google.adk.sessions.Session; +import com.google.adk.tools.FunctionTool; import com.google.genai.types.Blob; import com.google.genai.types.Content; import com.google.genai.types.FinishReason; @@ -317,11 +324,26 @@ void generateContent_streaming_emitsPartialChunksThenAggregatedResponse() { .extracting(response -> response.content().get().text()) .containsExactly("Hello there.", " How are", " you?"); LlmResponse aggregated = responses.get(3); - assertThat(aggregated.partial().orElse(false)).isFalse(); + assertThat(aggregated.partial()).hasValue(false); assertThat(aggregated.turnComplete()).hasValue(true); assertThat(aggregated.content().get().text()).isEqualTo("Hello there. How are you?"); } + @Test + void generateContent_streaming_aggregatedPartsAreMutable() { + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn(Flux.just(createStreamingChatResponse("Hello"))); + SpringAI springAI = new SpringAI(mockStreamingChatModel); + + TestSubscriber testObserver = springAI.generateContent(testRequest, true).test(); + + testObserver.awaitDone(5, TimeUnit.SECONDS); + List parts = + testObserver.values().get(testObserver.values().size() - 1).content().get().parts().get(); + parts.add(Part.fromText(" there")); + assertThat(parts).hasSize(2); + } + @Test void generateContent_streaming_aggregatedResponseCarriesLastUsage() { when(mockStreamingChatModel.stream(any(Prompt.class))) @@ -359,7 +381,10 @@ void generateContent_streamingCutShort_aggregatedResponseCarriesFinishReasonAndE testObserver.awaitDone(5, TimeUnit.SECONDS); List responses = testObserver.values(); assertThat(responses.subList(0, responses.size() - 1)) - .allSatisfy(response -> assertThat(response.errorCode()).isEmpty()); + .allSatisfy(response -> { + assertThat(response.errorCode()).isEmpty(); + assertThat(response.errorMessage()).isEmpty(); + }); LlmResponse aggregated = responses.get(responses.size() - 1); assertThat(aggregated.partial().orElse(false)).isFalse(); assertThat(aggregated.finishReason().map(FinishReason::knownEnum)) @@ -407,9 +432,9 @@ void generateContent_streamingThoughts_aggregatedResponseKeepsThoughtsApartFromT List parts = testObserver.values().get(testObserver.values().size() - 1).content().get().parts().get(); assertThat(parts) - .extracting(part -> part.text().get()) - .containsExactly("Let me think.", "Hello there."); - assertThat(parts).extracting(part -> part.thought().orElse(false)).containsExactly(true, false); + .containsExactly( + Part.builder().text("Let me think.").thought(true).build(), + Part.fromText("Hello there.")); } @Test @@ -570,6 +595,140 @@ void generateContent_streamingCancelled_cancelsUnderlyingStream() { assertThat(cancelled).isTrue(); } + @Test + void generateContent_streamingCallRepeatingAProviderId_aggregatedKeepsTheFirst() { + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn( + Flux.just( + createToolCallChatResponse("call_1", "get_weather"), + createToolCallChatResponse("call_1", "get_time"))); + SpringAI springAI = new SpringAI(mockStreamingChatModel); + + TestSubscriber testObserver = springAI.generateContent(testRequest, true).test(); + + testObserver.awaitDone(5, TimeUnit.SECONDS); + LlmResponse aggregated = testObserver.values().get(testObserver.values().size() - 1); + assertThat(onlyFunctionCall(aggregated).name()).hasValue("get_weather"); + } + + @Test + void generateContent_streamingCallWithEmptyName_aggregatedLeavesItOut() { + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn( + Flux.just( + createStreamingChatResponse("Checking."), + createToolCallChatResponse("call_1", ""))); + SpringAI springAI = new SpringAI(mockStreamingChatModel); + + TestSubscriber testObserver = springAI.generateContent(testRequest, true).test(); + + testObserver.awaitDone(5, TimeUnit.SECONDS); + LlmResponse aggregated = testObserver.values().get(testObserver.values().size() - 1); + assertThat(aggregated.content().get().parts().get()) + .containsExactly(Part.fromText("Checking.")); + } + + @Test + void generateContent_streamingUsageOnlyLastChunk_aggregatedIsTurnComplete() { + ChatResponse usageOnly = + new ChatResponse( + List.of(), ChatResponseMetadata.builder().usage(new DefaultUsage(3, 1, 4)).build()); + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn(Flux.just(createStreamingChatResponse("Hi"), usageOnly)); + SpringAI springAI = new SpringAI(mockStreamingChatModel); + + TestSubscriber testObserver = springAI.generateContent(testRequest, true).test(); + + testObserver.awaitDone(5, TimeUnit.SECONDS); + LlmResponse aggregated = testObserver.values().get(testObserver.values().size() - 1); + assertThat(aggregated.turnComplete()).hasValue(true); + assertThat(aggregated.usageMetadata().get().totalTokenCount()).hasValue(4); + } + + @Test + void generateContent_streamingModelVersionOnEarlierChunk_aggregatedKeepsIt() { + ChatResponse firstChunk = + new ChatResponse( + List.of(new Generation(new AssistantMessage("Hi"))), + ChatResponseMetadata.builder().model("gemini-test-001").build()); + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn(Flux.just(firstChunk, createStreamingChatResponse(" there"))); + SpringAI springAI = new SpringAI(mockStreamingChatModel); + + TestSubscriber testObserver = springAI.generateContent(testRequest, true).test(); + + testObserver.awaitDone(5, TimeUnit.SECONDS); + LlmResponse aggregated = testObserver.values().get(testObserver.values().size() - 1); + assertThat(aggregated.modelVersion()).hasValue("gemini-test-001"); + } + + @Test + void runner_sseTurnWithACallRepeatingAProviderId_runsTheToolOnce() { + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn( + Flux.just( + createToolCallChatResponse("call_1", "getWeather"), + createToolCallChatResponse("call_1", "getWeather"))) + .thenReturn(Flux.just(createStreamingChatResponse("Sunny."))); + InMemoryRunner runner = + new InMemoryRunner( + LlmAgent.builder() + .name("agent") + .model(new SpringAI(mockStreamingChatModel)) + .tools(FunctionTool.create(WeatherTool.class, "getWeather")) + .build(), + "test-app"); + Session session = runner.sessionService().createSession("test-app", "user").blockingGet(); + + List events = + runner + .runAsync( + "user", + session.id(), + Content.fromParts(Part.fromText("hello")), + RunConfig.builder().streamingMode(RunConfig.StreamingMode.SSE).build()) + .toList() + .blockingGet(); + + assertThat(events.stream().flatMap(event -> event.functionResponses().stream())) + .extracting(response -> response.id().get()) + .containsExactly("call_1"); + } + + @Test + void runner_sseTurnCutShort_savesOneEventWithTheFinishMessage() { + ChatResponse cutShort = + new ChatResponse( + List.of( + new Generation( + new AssistantMessage(" sho"), + ChatGenerationMetadata.builder().finishReason("MAX_TOKENS").build()))); + when(mockStreamingChatModel.stream(any(Prompt.class))) + .thenReturn(Flux.just(createStreamingChatResponse("Cut"), cutShort)); + InMemoryRunner runner = + new InMemoryRunner( + LlmAgent.builder().name("agent").model(new SpringAI(mockStreamingChatModel)).build(), + "test-app"); + Session session = runner.sessionService().createSession("test-app", "user").blockingGet(); + + List events = + runner + .runAsync( + "user", + session.id(), + Content.fromParts(Part.fromText("hello")), + RunConfig.builder().streamingMode(RunConfig.StreamingMode.SSE).build()) + .toList() + .blockingGet(); + + List finals = events.stream().filter(event -> !event.partial().orElse(false)).toList(); + assertThat(finals).hasSize(1); + assertThat(finals.get(0).errorCode().map(FinishReason::knownEnum)) + .hasValue(FinishReason.Known.MAX_TOKENS); + assertThat(finals.get(0).errorMessage()).hasValue("Maximum tokens reached"); + assertThat(finals.get(0).content().get().text()).isEqualTo("Cut sho"); + } + private static FunctionCall onlyFunctionCall(LlmResponse response) { List parts = response.content().get().parts().get(); assertThat(parts).hasSize(1); diff --git a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorTest.java b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorTest.java index 0d333d0cf8..d209434111 100644 --- a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorTest.java +++ b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") // Tests the deprecated class itself. class StreamingResponseAggregatorTest { private StreamingResponseAggregator aggregator; diff --git a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorThreadSafetyTest.java b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorThreadSafetyTest.java index c50a86aa5a..fe5024fc05 100644 --- a/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorThreadSafetyTest.java +++ b/contrib/spring-ai/src/test/java/com/google/adk/models/springai/StreamingResponseAggregatorThreadSafetyTest.java @@ -35,6 +35,7 @@ *

These tests verify that the aggregator correctly handles concurrent access from multiple * threads without data corruption or race conditions. */ +@SuppressWarnings("deprecation") // Tests the deprecated class itself. class StreamingResponseAggregatorThreadSafetyTest { @Test diff --git a/core/src/main/java/com/google/adk/models/StreamingResponseAggregator.java b/core/src/main/java/com/google/adk/models/StreamingResponseAggregator.java index 92621c59aa..62a777cb84 100644 --- a/core/src/main/java/com/google/adk/models/StreamingResponseAggregator.java +++ b/core/src/main/java/com/google/adk/models/StreamingResponseAggregator.java @@ -16,6 +16,7 @@ package com.google.adk.models; +import com.google.adk.annotations.Experimental; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import com.google.genai.types.Content; @@ -42,11 +43,13 @@ * Aggregates the chunks of one streamed model turn into partial responses and one final response * holding the whole turn. * - *

Pass each chunk to {@link #processRawResponse}, or to {@link #processResponse} once converted - * to an {@link LlmResponse}, then call {@link #aggregate} once the stream ends. An instance handles - * a single stream and is not thread-safe. + *

Pass each chunk to {@link #processResponse}, then call {@link #aggregate} once the stream + * ends. An instance handles a single stream and is not thread-safe. + * + *

This class is only for use by Agent Development Kit. */ -final class StreamingResponseAggregator { +@Experimental +public final class StreamingResponseAggregator { /** The largest list index a streamed argument path may set, as in ADK Python. */ private static final int MAX_ARRAY_INDEX = 10_000; @@ -97,31 +100,23 @@ final class StreamingResponseAggregator { // Where the call started in accumulatedSequence, so parts that arrive later stay after it. private int currentFcIndex = -1; - /** - * Processes {@code response} as {@link #processResponse} does, and also keeps the finish message - * of the candidate that sets the finish reason, so the final response can carry it as the error - * message. - */ - Optional processRawResponse(GenerateContentResponse response) { - response - .candidates() - .flatMap(candidates -> candidates.stream().findFirst()) - .filter(candidate -> candidate.finishReason().isPresent()) - .ifPresent(candidate -> finishMessage = candidate.finishMessage().orElse(null)); - return processResponse(LlmResponse.create(response)); - } - /** * Accumulates {@code response} and returns it as a partial response in which every function call * carries an ID: its own model-provided ID, or else the ID of the call it belongs to. A call * without a name also gets an ID, though it is left out of the final response. Returns empty if - * the chunk carries no content, such as a metadata-only chunk. Unlike {@link - * #processRawResponse}, it does not keep the finish message. + * the chunk carries no content, such as a metadata-only chunk. A chunk with a finish reason also + * gives the final response its error message. */ - Optional processResponse(LlmResponse response) { + public Optional processResponse(LlmResponse response) { + Objects.requireNonNull(response); lastResponse = response; response.usageMetadata().ifPresent(usage -> usageMetadata = usage); - response.finishReason().ifPresent(reason -> finishReason = reason); + response + .finishReason() + .ifPresent(reason -> { + finishReason = reason; + finishMessage = response.errorMessage().orElse(null); + }); response.groundingMetadata().ifPresent(grounding -> groundingMetadata = grounding); List parts = response.content().flatMap(Content::parts).orElse(ImmutableList.of()); // Only terminators: a dropped part, such as a nameless function call, must not reach the final. @@ -141,10 +136,11 @@ Optional processResponse(LlmResponse response) { * repeat a model-provided ID, or else the latest content made only of stream terminators, with * the latest usage, finish reason and grounding metadata; other fields come from the last chunk. * Once a finish reason is seen, the error code is that reason unless it is STOP, and the error - * message is the finish message kept by {@link #processRawResponse} for an error, or else - * cleared. Returns empty only if no chunk was processed. + * message is the message of the chunk that set it for an error, or else cleared. Merged plain + * text carries {@code thought=false}, where ADK Python leaves the flag unset. Returns empty only + * if no chunk was processed. */ - Optional aggregate() { + public Optional aggregate() { if (lastResponse == null) { return Optional.empty(); } @@ -180,6 +176,21 @@ Optional aggregate() { .build()); } + /** + * Processes {@code response} as {@code processResponse(LlmResponse.create(response))} does, but + * takes the finish message from the candidate that sets the finish reason, which {@link + * LlmResponse#create} keeps only for a candidate without parts. + */ + Optional processRawResponse(GenerateContentResponse response) { + Optional partial = processResponse(LlmResponse.create(response)); + response + .candidates() + .flatMap(candidates -> candidates.stream().findFirst()) + .filter(candidate -> candidate.finishReason().isPresent()) + .ifPresent(candidate -> finishMessage = candidate.finishMessage().orElse(null)); + return partial; + } + /** * Returns a mutable copy of {@code parts} without the function calls that repeat a model-provided * ID, keeping the first, as ADK Python's {@code _deduplicate_function_calls} does. Calls without diff --git a/core/src/test/java/com/google/adk/models/StreamingResponseAggregatorTest.java b/core/src/test/java/com/google/adk/models/StreamingResponseAggregatorTest.java index 206b54ec29..5e64d9d8e1 100644 --- a/core/src/test/java/com/google/adk/models/StreamingResponseAggregatorTest.java +++ b/core/src/test/java/com/google/adk/models/StreamingResponseAggregatorTest.java @@ -17,6 +17,7 @@ import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -1080,6 +1081,16 @@ public void aggregate_noChunks_returnsEmpty() { assertThat(new StreamingResponseAggregator().aggregate()).isEmpty(); } + @Test + public void processResponse_null_throwsAndKeepsTheEarlierChunks() { + StreamingResponseAggregator aggregator = new StreamingResponseAggregator(); + process(aggregator, chunk(Part.fromText("Hello"))); + + assertThrows(NullPointerException.class, () -> aggregator.processResponse(null)); + + assertThat(aggregator.aggregate().get().content().get().text()).isEqualTo("Hello"); + } + @Test public void aggregate_noContentAndNoFinishReason_returnsFinalWithoutContent() { StreamingResponseAggregator aggregator = new StreamingResponseAggregator(); @@ -1261,6 +1272,56 @@ public void aggregate_groundingOnEarlierChunk_isKept() { assertThat(aggregated.groundingMetadata()).hasValue(grounding); } + @Test + public void aggregate_errorChunkWithMessageThenTrailingChunk_keepsTheMessage() { + StreamingResponseAggregator aggregator = new StreamingResponseAggregator(); + process( + aggregator, + chunk(Part.fromText("Cut sho")).toBuilder() + .finishReason(MAX_TOKENS) + .errorCode(MAX_TOKENS) + .errorMessage("Maximum tokens reached") + .build(), + trailingUsageChunk(usage(7))); + + LlmResponse aggregated = aggregator.aggregate().get(); + + assertThat(aggregated.errorCode()).hasValue(MAX_TOKENS); + assertThat(aggregated.errorMessage()).hasValue("Maximum tokens reached"); + } + + @Test + public void aggregate_laterErrorChunkWithoutMessage_dropsTheEarlierMessage() { + StreamingResponseAggregator aggregator = new StreamingResponseAggregator(); + process( + aggregator, + chunk(Part.fromText("Cut")).toBuilder() + .finishReason(MAX_TOKENS) + .errorMessage("Maximum tokens reached") + .build(), + chunk(Part.fromText(" off")).toBuilder().finishReason(MAX_TOKENS).build()); + + LlmResponse aggregated = aggregator.aggregate().get(); + + assertThat(aggregated.errorCode()).hasValue(MAX_TOKENS); + assertThat(aggregated.errorMessage()).isEmpty(); + } + + @Test + public void aggregate_stopChunkWithMessage_hasNoErrorMessage() { + StreamingResponseAggregator aggregator = new StreamingResponseAggregator(); + process( + aggregator, + chunk(Part.fromText("Done.")).toBuilder() + .finishReason(STOP) + .errorMessage("Model finished.") + .build()); + + LlmResponse aggregated = aggregator.aggregate().get(); + + assertThat(aggregated.errorMessage()).isEmpty(); + } + @Test public void aggregate_rawErrorChunkThenChunkWithoutCandidates_keepsTheFinishMessage() { StreamingResponseAggregator aggregator = new StreamingResponseAggregator();