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 @@ -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;
Expand Down Expand Up @@ -233,126 +231,52 @@ private Flowable<LlmResponse> 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<Part> 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<LlmResponse> 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<Part> 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<LlmResponse> 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<Part> 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<Part> 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<Part> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
* <p><b>Thread Safety:</b> 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();
Expand Down
Loading
Loading