Skip to content

Commit 784dd98

Browse files
committed
Enforce strict JSON Schema compliance to prevent OpenAI 400 Bad Request errors
1 parent 9831733 commit 784dd98

6 files changed

Lines changed: 272 additions & 22 deletions

File tree

‎core/src/main/java/com/google/adk/models/chat/ChatCompletionsCommon.java‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,12 @@
1919
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
2020
import com.fasterxml.jackson.annotation.JsonInclude;
2121
import com.fasterxml.jackson.annotation.JsonProperty;
22+
import com.fasterxml.jackson.core.JsonParser;
23+
import com.fasterxml.jackson.core.JsonProcessingException;
2224
import com.fasterxml.jackson.core.type.TypeReference;
25+
import com.fasterxml.jackson.databind.JsonMappingException;
2326
import com.fasterxml.jackson.databind.ObjectMapper;
27+
import com.google.common.collect.ImmutableMap;
2428
import com.google.genai.types.FunctionCall;
2529
import com.google.genai.types.Part;
2630
import java.util.Base64;
@@ -37,6 +41,10 @@ private ChatCompletionsCommon() {}
3741

3842
private static final ObjectMapper objectMapper = new ObjectMapper();
3943

44+
static final String EMPTY_JSON_OBJECT = "{}";
45+
static final ImmutableMap<String, Object> EMPTY_PARAMETERS_SCHEMA =
46+
ImmutableMap.of("type", "object", "properties", ImmutableMap.of());
47+
4048
public static final String ROLE_ASSISTANT = "assistant";
4149
public static final String ROLE_MODEL = "model";
4250

@@ -157,6 +165,21 @@ public Part applyThoughtSignature(Part part) {
157165
}
158166
}
159167

168+
static ImmutableMap<String, Object> parseToolCallArguments(String arguments, ObjectMapper mapper)
169+
throws JsonProcessingException {
170+
if (arguments == null || arguments.trim().isEmpty()) {
171+
return ImmutableMap.of();
172+
}
173+
Map<String, Object> result =
174+
mapper.readValue(arguments, new TypeReference<Map<String, Object>>() {});
175+
if (result == null) {
176+
throw JsonMappingException.from(
177+
(JsonParser) null,
178+
"JSON literal 'null' is not a valid JSON object for tool call arguments");
179+
}
180+
return ImmutableMap.copyOf(result);
181+
}
182+
160183
/**
161184
* See
162185
* https://developers.openai.com/api/reference/resources/chat#(resource)%20chat.completions%20%3E%20(model)%20chat_completion_message_function_tool_call%20%3E%20(schema)
@@ -181,21 +204,21 @@ public FunctionCall toFunctionCall(@Nullable String toolCallId) {
181204
if (name != null) {
182205
fcBuilder.name(name);
183206
}
184-
if (arguments != null && !arguments.isEmpty()) {
185-
try {
186-
Map<String, Object> args =
187-
objectMapper.readValue(arguments, new TypeReference<Map<String, Object>>() {});
188-
fcBuilder.args(args);
189-
} catch (Exception e) {
190-
throw new IllegalArgumentException(
191-
"Failed to parse function arguments JSON: " + arguments, e);
192-
}
193-
}
207+
fcBuilder.args(parseArguments(arguments));
194208
if (toolCallId != null) {
195209
fcBuilder.id(toolCallId);
196210
}
197211
return fcBuilder.build();
198212
}
213+
214+
private ImmutableMap<String, Object> parseArguments(String arguments) {
215+
try {
216+
return parseToolCallArguments(arguments, objectMapper);
217+
} catch (Exception e) {
218+
throw new IllegalArgumentException(
219+
"Failed to parse function arguments JSON: " + arguments, e);
220+
}
221+
}
199222
}
200223

201224
/**

‎core/src/main/java/com/google/adk/models/chat/ChatCompletionsRequest.java‎

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,12 @@
2121
import com.fasterxml.jackson.annotation.JsonInclude;
2222
import com.fasterxml.jackson.annotation.JsonProperty;
2323
import com.fasterxml.jackson.annotation.JsonValue;
24+
import com.fasterxml.jackson.core.JsonGenerator;
2425
import com.fasterxml.jackson.core.type.TypeReference;
26+
import com.fasterxml.jackson.databind.JsonSerializer;
2527
import com.fasterxml.jackson.databind.ObjectMapper;
28+
import com.fasterxml.jackson.databind.SerializerProvider;
29+
import com.fasterxml.jackson.databind.module.SimpleModule;
2630
import com.google.adk.JsonBaseModel;
2731
import com.google.adk.models.LlmRequest;
2832
import com.google.common.collect.ImmutableList;
@@ -32,6 +36,8 @@
3236
import com.google.genai.types.FunctionResponse;
3337
import com.google.genai.types.GenerateContentConfig;
3438
import com.google.genai.types.Part;
39+
import com.google.genai.types.Type;
40+
import java.io.IOException;
3541
import java.util.ArrayList;
3642
import java.util.Base64;
3743
import java.util.List;
@@ -270,7 +276,28 @@ public final class ChatCompletionsRequest {
270276
public Map<String, Object> extraBody;
271277

272278
private static final Logger logger = LoggerFactory.getLogger(ChatCompletionsRequest.class);
273-
private static final ObjectMapper objectMapper = JsonBaseModel.getMapper();
279+
280+
/**
281+
* Registers a custom serializer to force JSON Schema types to lowercase (e.g., "STRING" ->
282+
* "string"). The genai SDK uses uppercase Enums for schema types, which strict OpenAI-compatible
283+
* endpoints reject with HTTP 400.
284+
*/
285+
private static SimpleModule schemaNormalizerModule() {
286+
SimpleModule module = new SimpleModule();
287+
module.addSerializer(
288+
Type.class,
289+
new JsonSerializer<Type>() {
290+
@Override
291+
public void serialize(Type value, JsonGenerator gen, SerializerProvider serializers)
292+
throws IOException {
293+
gen.writeString(value.toString().toLowerCase());
294+
}
295+
});
296+
return module;
297+
}
298+
299+
private static final ObjectMapper objectMapper =
300+
JsonBaseModel.getMapper().copy().registerModule(schemaNormalizerModule());
274301

275302
/**
276303
* Converts a standard {@link LlmRequest} into a {@link ChatCompletionsRequest} for
@@ -476,7 +503,10 @@ private static ChatCompletionsCommon.ToolCall processFunctionCallPart(Part part)
476503
function.arguments = objectMapper.writeValueAsString(fc.args().get());
477504
} catch (Exception e) {
478505
logger.warn("Failed to serialize function arguments", e);
506+
function.arguments = ChatCompletionsCommon.EMPTY_JSON_OBJECT;
479507
}
508+
} else {
509+
function.arguments = ChatCompletionsCommon.EMPTY_JSON_OBJECT;
480510
}
481511
toolCall.function = function;
482512
part.thoughtSignature()
@@ -505,7 +535,10 @@ private static Message processFunctionResponsePart(Part part) {
505535
toolResp.content = new MessageContent(objectMapper.writeValueAsString(fr.response().get()));
506536
} catch (Exception e) {
507537
logger.warn("Failed to serialize tool response", e);
538+
toolResp.content = new MessageContent(ChatCompletionsCommon.EMPTY_JSON_OBJECT);
508539
}
540+
} else {
541+
toolResp.content = new MessageContent(ChatCompletionsCommon.EMPTY_JSON_OBJECT);
509542
}
510543
return toolResp;
511544
}
@@ -570,12 +603,15 @@ private static void handleTools(GenerateContentConfig config, ChatCompletionsReq
570603
FunctionDefinition def = new FunctionDefinition();
571604
def.name = fd.name().orElse("");
572605
def.description = fd.description().orElse("");
573-
fd.parameters()
574-
.ifPresent(
575-
params ->
576-
def.parameters =
577-
objectMapper.convertValue(
578-
params, new TypeReference<Map<String, Object>>() {}));
606+
if (fd.parameters().isPresent()) {
607+
def.parameters =
608+
objectMapper.convertValue(
609+
fd.parameters().get(), new TypeReference<Map<String, Object>>() {});
610+
} else {
611+
// OpenAI-compatible APIs (like Groq) strictly require the parameters object
612+
// to exist, even for zero-argument functions.
613+
def.parameters = ChatCompletionsCommon.EMPTY_PARAMETERS_SCHEMA;
614+
}
579615
tool.function = def;
580616
tools.add(tool);
581617
}

‎core/src/main/java/com/google/adk/models/chat/ChatCompletionsResponse.java‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import com.fasterxml.jackson.annotation.JsonInclude;
2121
import com.fasterxml.jackson.annotation.JsonProperty;
2222
import com.fasterxml.jackson.core.JsonProcessingException;
23-
import com.fasterxml.jackson.core.type.TypeReference;
2423
import com.fasterxml.jackson.databind.ObjectMapper;
2524
import com.google.adk.models.LlmResponse;
2625
import com.google.common.collect.ImmutableList;
@@ -836,8 +835,7 @@ private ImmutableList<Part> getFinalToolCallParts() {
836835
if (argsSb != null && argsSb.length() > 0) {
837836
try {
838837
Map<String, Object> args =
839-
objectMapper.readValue(
840-
argsSb.toString(), new TypeReference<Map<String, Object>>() {});
838+
ChatCompletionsCommon.parseToolCallArguments(argsSb.toString(), objectMapper);
841839
fc = fc.toBuilder().args(args).build();
842840
part = part.toBuilder().functionCall(fc).build();
843841
} catch (JsonProcessingException e) {
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.google.adk.models.chat;
2+
3+
import static com.google.common.truth.Truth.assertThat;
4+
import static org.junit.Assert.assertThrows;
5+
6+
import com.fasterxml.jackson.core.JsonProcessingException;
7+
import com.fasterxml.jackson.databind.ObjectMapper;
8+
import com.google.common.collect.ImmutableMap;
9+
import java.util.Map;
10+
import org.junit.Before;
11+
import org.junit.Test;
12+
import org.junit.runner.RunWith;
13+
import org.junit.runners.JUnit4;
14+
15+
@RunWith(JUnit4.class)
16+
public final class ChatCompletionsCommonTest {
17+
18+
private ObjectMapper objectMapper;
19+
20+
@Before
21+
public void setUp() {
22+
objectMapper = new ObjectMapper();
23+
}
24+
25+
@Test
26+
public void parseToolCallArguments_withValidJson() throws Exception {
27+
String json = "{\"pr_number\": 1042, \"reason\": \"review\"}";
28+
ImmutableMap<String, Object> args =
29+
ChatCompletionsCommon.parseToolCallArguments(json, objectMapper);
30+
assertThat(args).hasSize(2);
31+
assertThat(args.get("pr_number")).isEqualTo(1042);
32+
assertThat(args.get("reason")).isEqualTo("review");
33+
assertThat(args).isInstanceOf(ImmutableMap.class);
34+
}
35+
36+
@Test
37+
public void parseToolCallArguments_withEmptyString() throws Exception {
38+
Map<String, Object> args = ChatCompletionsCommon.parseToolCallArguments("", objectMapper);
39+
assertThat(args).isEmpty();
40+
}
41+
42+
@Test
43+
public void parseToolCallArguments_withNullString() throws Exception {
44+
Map<String, Object> args = ChatCompletionsCommon.parseToolCallArguments(null, objectMapper);
45+
assertThat(args).isEmpty();
46+
}
47+
48+
@Test
49+
public void parseToolCallArguments_withWhitespaceString() throws Exception {
50+
Map<String, Object> args = ChatCompletionsCommon.parseToolCallArguments(" ", objectMapper);
51+
assertThat(args).isEmpty();
52+
}
53+
54+
@Test
55+
public void parseToolCallArguments_withInvalidJson_throwsException() {
56+
assertThrows(
57+
JsonProcessingException.class,
58+
() -> ChatCompletionsCommon.parseToolCallArguments("none", objectMapper));
59+
60+
assertThrows(
61+
JsonProcessingException.class,
62+
() -> ChatCompletionsCommon.parseToolCallArguments("{bad_json:", objectMapper));
63+
}
64+
65+
@Test
66+
public void parseToolCallArguments_withLiteralNullString_throwsException() {
67+
JsonProcessingException exception =
68+
assertThrows(
69+
JsonProcessingException.class,
70+
() -> ChatCompletionsCommon.parseToolCallArguments("null", objectMapper));
71+
assertThat(exception)
72+
.hasMessageThat()
73+
.contains("JSON literal 'null' is not a valid JSON object for tool call arguments");
74+
}
75+
}

‎core/src/test/java/com/google/adk/models/chat/ChatCompletionsRequestTest.java‎

Lines changed: 81 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import com.google.genai.types.FunctionResponse;
3535
import com.google.genai.types.GenerateContentConfig;
3636
import com.google.genai.types.Part;
37+
import com.google.genai.types.Schema;
3738
import com.google.genai.types.Tool;
3839
import com.google.genai.types.ToolConfig;
3940
import java.util.AbstractMap;
@@ -567,6 +568,84 @@ public void testFromLlmRequest_withFunctionCall() throws Exception {
567568
assertThat(msg.toolCalls.get(0).function.arguments).isEqualTo("{\"location\":\"Paris\"}");
568569
}
569570

571+
@Test
572+
public void testFromLlmRequest_withAbsentFunctionArguments() throws Exception {
573+
FunctionCall functionCall = FunctionCall.builder().id("call_123").name("get_time").build();
574+
Part part = Part.builder().functionCall(functionCall).build();
575+
Content content = Content.builder().role("model").parts(ImmutableList.of(part)).build();
576+
577+
LlmRequest llmRequest =
578+
LlmRequest.builder().model("gemini-1.5-pro").contents(ImmutableList.of(content)).build();
579+
580+
ChatCompletionsRequest request = ChatCompletionsRequest.fromLlmRequest(llmRequest, false);
581+
582+
assertThat(request.messages).hasSize(1);
583+
ChatCompletionsRequest.Message msg = request.messages.get(0);
584+
assertThat(msg.role).isEqualTo("assistant");
585+
assertThat(msg.toolCalls).hasSize(1);
586+
assertThat(msg.toolCalls.get(0).function.name).isEqualTo("get_time");
587+
assertThat(msg.toolCalls.get(0).function.arguments).isEqualTo("{}");
588+
}
589+
590+
@Test
591+
public void testFromLlmRequest_withAbsentParameters() throws Exception {
592+
FunctionDeclaration function =
593+
FunctionDeclaration.builder().name("test_func").description("A test function").build();
594+
595+
Tool tool = Tool.builder().functionDeclarations(ImmutableList.of(function)).build();
596+
GenerateContentConfig config =
597+
GenerateContentConfig.builder().tools(ImmutableList.of(tool)).build();
598+
599+
LlmRequest llmRequest =
600+
LlmRequest.builder()
601+
.model("gemini-1.5-pro")
602+
.config(config)
603+
.contents(ImmutableList.of())
604+
.build();
605+
606+
ChatCompletionsRequest request = ChatCompletionsRequest.fromLlmRequest(llmRequest, false);
607+
608+
assertThat(request.tools).hasSize(1);
609+
Map<String, Object> params = (Map<String, Object>) request.tools.get(0).function.parameters;
610+
assertThat(params.get("type")).isEqualTo("object");
611+
@SuppressWarnings("unchecked")
612+
Map<String, Object> props = (Map<String, Object>) params.get("properties");
613+
assertThat(props).isEmpty();
614+
}
615+
616+
@Test
617+
public void testFromLlmRequest_normalizesSchemaTypeToLowerCase() throws Exception {
618+
Schema param1Schema = Schema.builder().type("STRING").build();
619+
620+
Schema functionSchema =
621+
Schema.builder().type("OBJECT").properties(ImmutableMap.of("param1", param1Schema)).build();
622+
623+
FunctionDeclaration function =
624+
FunctionDeclaration.builder().name("test_func").parameters(functionSchema).build();
625+
626+
Tool tool = Tool.builder().functionDeclarations(ImmutableList.of(function)).build();
627+
GenerateContentConfig config =
628+
GenerateContentConfig.builder().tools(ImmutableList.of(tool)).build();
629+
630+
LlmRequest llmRequest =
631+
LlmRequest.builder()
632+
.model("gemini-1.5-pro")
633+
.config(config)
634+
.contents(ImmutableList.of())
635+
.build();
636+
637+
ChatCompletionsRequest request = ChatCompletionsRequest.fromLlmRequest(llmRequest, false);
638+
639+
assertThat(request.tools).hasSize(1);
640+
Map<String, Object> params = (Map<String, Object>) request.tools.get(0).function.parameters;
641+
assertThat(params.get("type")).isEqualTo("object");
642+
@SuppressWarnings("unchecked")
643+
Map<String, Object> props = (Map<String, Object>) params.get("properties");
644+
@SuppressWarnings("unchecked")
645+
Map<String, Object> param1 = (Map<String, Object>) props.get("param1");
646+
assertThat(param1.get("type")).isEqualTo("string");
647+
}
648+
570649
@Test
571650
public void testFromLlmRequest_withStreamOptions() throws Exception {
572651
LlmRequest llmRequest =
@@ -628,11 +707,11 @@ public void testFromLlmRequest_withFunctionResponse() throws Exception {
628707

629708
assertThat(request.messages.get(1).role).isEqualTo("tool");
630709
assertThat(request.messages.get(1).toolCallId).isEmpty();
631-
assertThat(request.messages.get(1).content).isNull();
710+
assertThat(request.messages.get(1).content.getValue()).isEqualTo("{}");
632711

633712
assertThat(request.messages.get(2).role).isEqualTo("tool");
634713
assertThat(request.messages.get(2).toolCallId).isEqualTo("call_faulty");
635-
assertThat(request.messages.get(2).content).isNull();
714+
assertThat(request.messages.get(2).content.getValue()).isEqualTo("{}");
636715
}
637716

638717
@Test

0 commit comments

Comments
 (0)