[gemini] Handle incomplete converstations (#21008)

Conversations are limited in size. This can lead to invalid structures
being rejected by the Gemini API.
This is now handled to ensure that API requests are valid.

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich
2026-06-20 00:23:14 +02:00
committed by GitHub
parent 9b204c8c2d
commit 28cf437342
@@ -162,7 +162,8 @@ public class GeminiApiClient {
case TOOL_RETURN: {
String name = pendingToolCallNames.poll();
if (name == null) {
name = "";
logger.trace("skipping orphaned TOOL_RETURN");
break; // TOOL_RETURN without preceding TOOL_CALL - ignore
}
GeminiFunctionResponse fr = new GeminiFunctionResponse(name, Map.of("result", msg.content()));
GeminiPart part = new GeminiPart(null, null, fr, null);
@@ -174,6 +175,18 @@ public class GeminiApiClient {
}
}
while (!contents.isEmpty()) {
GeminiContent first = contents.getFirst();
List<GeminiPart> firstParts = first.parts();
boolean isValidFirst = ROLE_USER.equals(first.role()) && firstParts != null
&& firstParts.stream().anyMatch(p -> p.text() != null);
if (isValidFirst) {
break;
}
logger.trace("removing leading invalid content entry with role '{}'", first.role());
contents.removeFirst();
}
List<GeminiTool> geminiTools = null;
if (!tools.isEmpty()) {
List<GeminiFunctionDeclaration> functions = new ArrayList<>();