Skip to content
Closed
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 @@ -646,15 +646,19 @@ protected List<Generation> responseCandidateToGeneration(Candidate candidate) {
.finishReason(candidateFinishReason.toString())
.build();

boolean isFunctionCall = candidate.content().isPresent() && candidate.content().get().parts().isPresent()
&& candidate.content().get().parts().get().stream().anyMatch(part -> part.functionCall().isPresent());

if (isFunctionCall) {
List<AssistantMessage.ToolCall> assistantToolCalls = candidate.content()
.get()
.parts()
.orElse(List.of())
.stream()
// Collect text parts
String textContent = "";
if (candidate.content().isPresent() && candidate.content().get().parts().isPresent()) {
textContent = candidate.content().get().parts().get().stream()
.filter(part -> part.text().isPresent())
.map(part -> part.text().get())
.collect(Collectors.joining(" "));
}

// Collect function call parts
List<AssistantMessage.ToolCall> assistantToolCalls = List.of();
if (candidate.content().isPresent() && candidate.content().get().parts().isPresent()) {
assistantToolCalls = candidate.content().get().parts().get().stream()
.filter(part -> part.functionCall().isPresent())
.map(part -> {
FunctionCall functionCall = part.functionCall().get();
Expand All @@ -663,45 +667,26 @@ protected List<Generation> responseCandidateToGeneration(Candidate candidate) {
return new AssistantMessage.ToolCall("", "function", functionName, functionArguments);
})
.toList();
}

// Handle the case where all parts are server-side tool invocations (no text, no function calls)
if (textContent.isEmpty() && assistantToolCalls.isEmpty()) {
AssistantMessage assistantMessage = AssistantMessage.builder()
.content("")
.properties(messageMetadata)
.toolCalls(assistantToolCalls)
.build();

return List.of(new Generation(assistantMessage, chatGenerationMetadata));
}
else {
List<Generation> generations = candidate.content()
.get()
.parts()
.orElse(List.of())
.stream()
.filter(part -> part.toolCall().isEmpty() && part.toolResponse().isEmpty())
.map(part -> {
var partMessageMetadata = new HashMap<>(messageMetadata);
partMessageMetadata.put("isThought", part.thought().orElse(false));
return AssistantMessage.builder()
.content(part.text().orElse(""))
.properties(partMessageMetadata)
.build();
})
.map(assistantMessage -> new Generation(assistantMessage, chatGenerationMetadata))
.toList();

// If all parts were server-side tool invocations, return a single generation
// with empty text but with the server-side tool invocation metadata
if (generations.isEmpty()) {
AssistantMessage assistantMessage = AssistantMessage.builder()
.content("")
.properties(messageMetadata)
.build();
return List.of(new Generation(assistantMessage, chatGenerationMetadata));
}
// Build a SINGLE generation with BOTH text and tool calls (mixed modality)
AssistantMessage assistantMessage = AssistantMessage.builder()
.content(textContent)
.properties(messageMetadata)
.toolCalls(assistantToolCalls.isEmpty() ? null : assistantToolCalls)
.build();

return generations;
}

return List.of(new Generation(assistantMessage, chatGenerationMetadata));
}

private ChatResponseMetadata toChatResponseMetadata(Usage usage, String modelVersion) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.google.genai;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.FunctionCall;
import com.google.genai.types.Part;
import org.junit.jupiter.api.Test;

import org.springframework.ai.chat.model.Generation;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Regression tests for mixed-modality Gemini responses (text + functionCall parts). These
* tests verify that the fix for issue #5466 correctly handles mixed content.
*
* @author ENG
* @since 1.1.0
* @see <a href="https://github.com/spring-projects/spring-ai/issues/5466">Issue #5466</a>
*/
public class GoogleGenAiChatModelMixedContentTests {

@Test
@SuppressWarnings("unchecked")
void testMixedTextAndFunctionCallParts() throws Exception {
// Arrange: a candidate with both a TextPart and a FunctionCallPart
Part textPart = Part.builder().text("The answer is 42.").build();
Part functionCallPart = Part.builder()
.functionCall(FunctionCall.builder().name("get_weather").args(Map.of("location", "Toronto")).build())
.build();

Content content = Content.builder().parts(List.of(textPart, functionCallPart)).build();

Candidate candidate = Candidate.builder().content(content).index(0).build();

// Act: call responseCandidateToGeneration via reflection
GoogleGenAiChatModel model = GoogleGenAiChatModel.builder()
.defaultOptions(GoogleGenAiChatOptions.builder().build())
.build();
Method method = GoogleGenAiChatModel.class.getDeclaredMethod("responseCandidateToGeneration", Candidate.class);
method.setAccessible(true);
List<Generation> generations = (List<Generation>) method.invoke(model, candidate);

// Assert: exactly one generation with both text content and toolCalls
assertThat(generations).hasSize(1);
Generation generation = generations.get(0);
var assistantMessage = (org.springframework.ai.chat.messages.AssistantMessage) generation.getOutput();

// Text content must be preserved
assertThat(assistantMessage.getText()).isEqualTo("The answer is 42.");

// Tool calls must also be preserved (not dropped by allMatch logic)
assertThat(assistantMessage.getToolCalls()).isNotNull();
assertThat(assistantMessage.getToolCalls()).hasSize(1);
assertThat(assistantMessage.getToolCalls().get(0).name()).isEqualTo("get_weather");
assertThat(assistantMessage.getToolCalls().get(0).arguments()).contains("Toronto");
}

@Test
@SuppressWarnings("unchecked")
void testFunctionCallOnlyParts() throws Exception {
// Arrange: a candidate with only functionCall parts
Part functionCallPart1 = Part.builder()
.functionCall(FunctionCall.builder().name("get_weather").args(Map.of("location", "Toronto")).build())
.build();
Part functionCallPart2 = Part.builder()
.functionCall(FunctionCall.builder().name("get_time").args(Map.of("timezone", "America/Toronto")).build())
.build();

Content content = Content.builder().parts(List.of(functionCallPart1, functionCallPart2)).build();

Candidate candidate = Candidate.builder().content(content).index(0).build();

// Act
GoogleGenAiChatModel model = GoogleGenAiChatModel.builder()
.defaultOptions(GoogleGenAiChatOptions.builder().build())
.build();
Method method = GoogleGenAiChatModel.class.getDeclaredMethod("responseCandidateToGeneration", Candidate.class);
method.setAccessible(true);
List<Generation> generations = (List<Generation>) method.invoke(model, candidate);

// Assert: one generation with both tool calls and empty text content
assertThat(generations).hasSize(1);
var assistantMessage = (org.springframework.ai.chat.messages.AssistantMessage) generations.get(0).getOutput();

assertThat(assistantMessage.getText()).isEmpty();
assertThat(assistantMessage.getToolCalls()).hasSize(2);
assertThat(assistantMessage.getToolCalls().get(0).name()).isEqualTo("get_weather");
assertThat(assistantMessage.getToolCalls().get(1).name()).isEqualTo("get_time");
}

@Test
@SuppressWarnings("unchecked")
void testTextOnlyParts() throws Exception {
// Arrange: a candidate with only text parts
Part textPart1 = Part.builder().text("Hello ").build();
Part textPart2 = Part.builder().text("world!").build();

Content content = Content.builder().parts(List.of(textPart1, textPart2)).build();

Candidate candidate = Candidate.builder().content(content).index(0).build();

// Act
GoogleGenAiChatModel model = GoogleGenAiChatModel.builder()
.defaultOptions(GoogleGenAiChatOptions.builder().build())
.build();
Method method = GoogleGenAiChatModel.class.getDeclaredMethod("responseCandidateToGeneration", Candidate.class);
method.setAccessible(true);
List<Generation> generations = (List<Generation>) method.invoke(model, candidate);

// Assert: one generation with concatenated text and no tool calls
assertThat(generations).hasSize(1);
var assistantMessage = (org.springframework.ai.chat.messages.AssistantMessage) generations.get(0).getOutput();

assertThat(assistantMessage.getText()).isEqualTo("Hello world!");
assertThat(assistantMessage.getToolCalls()).isNullOrEmpty();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ public CompressionQueryTransformer(ChatClient.Builder chatClientBuilder, @Nullab
public Query transform(Query query) {
Assert.notNull(query, "query cannot be null");


if (query.history().isEmpty()) {
logger.debug("Conversation history is empty. Returning the query unchanged.");
return query;
}

logger.debug("Compressing conversation history and follow-up query into a standalone query");

var compressedQueryText = this.chatClient.prompt()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.rag.Query;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link CompressionQueryTransformer}.
Expand Down Expand Up @@ -69,4 +71,18 @@ void whenPromptHasMissingQueryPlaceholderThenThrow() {
.hasMessageContaining("query");
}


@Test
void whenHistoryIsEmptyThenReturnQueryUnchanged() {
ChatClient.Builder chatClientBuilder = mock(ChatClient.Builder.class);
ChatClient chatClient = mock(ChatClient.class);
when(chatClientBuilder.build()).thenReturn(chatClient);
QueryTransformer queryTransformer = CompressionQueryTransformer.builder()
.chatClientBuilder(chatClientBuilder)
.build();
Query query = new Query("What is Spring AI?");
Query result = queryTransformer.transform(query);
org.assertj.core.api.Assertions.assertThat(result.text()).isEqualTo("What is Spring AI?");
}

}