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
86 changes: 84 additions & 2 deletions core/src/main/java/com/google/adk/SchemaUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Expand Down Expand Up @@ -157,7 +159,7 @@ private static void validateProperties(
/**
* Parses model text against {@code schema} as one JSON value, or returns the text itself when
* that fails and the schema accepts a string. Blank text, and a JSON null the schema allows, give
* {@code null}.
* {@code null}. Omitted properties of a parsed value get their schema defaults.
*
* <p>This method is only for use by Agent Development Kit.
*
Expand All @@ -172,7 +174,7 @@ private static void validateProperties(
Object value = readStrictJson(output);
reason = mismatch(value, schema);
if (reason == null) {
return value;
return fillDefaults(value, schema);
}
} catch (JsonProcessingException e) {
reason = "it is not JSON";
Expand Down Expand Up @@ -268,6 +270,86 @@ public static Map<String, Object> validateOutputSchema(String output, Schema sch
return outputMap;
}

/**
* Returns a copy of {@code args} with the default of each property it omits, through nested
* objects, array items and the first {@code anyOf} alternative that matches. An explicit null
* keeps its value. Neither {@code args} nor the defaults are validated.
*
* <p>This method is only for use by Agent Development Kit.
*/
@SuppressWarnings("unchecked") // A map stays a map with String keys.
public static Map<String, Object> withDefaults(Map<String, Object> args, Schema schema) {
return (Map<String, Object>) fillDefaults(Preconditions.checkNotNull(args), schema);
}

/**
* Returns {@code value}, any JSON value, as {@link #withDefaults} fills it; null stays null.
*
* <p>This method is only for use by Agent Development Kit.
*/
public static @Nullable Object valueWithDefaults(@Nullable Object value, Schema schema) {
return fillDefaults(value, schema);
}

private static @Nullable Object fillDefaults(@Nullable Object value, Schema schema) {
Optional<Map<String, Schema>> properties = schema.properties();
Optional<Schema> items = schema.items();
if (value instanceof Map<?, ?> map && properties.isPresent()) {
Map<String, Object> result = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
Schema property = properties.get().get(String.valueOf(entry.getKey()));
result.put(
String.valueOf(entry.getKey()),
property == null ? entry.getValue() : fillDefaults(entry.getValue(), property));
}
for (Map.Entry<String, Schema> property : properties.get().entrySet()) {
// An explicit null is a value, so only an absent key gets the default.
Optional<Object> fallback = property.getValue().default_();
if (fallback.isPresent() && !result.containsKey(property.getKey())) {
result.put(property.getKey(), copyDefault(fallback.get()));
}
}
return result;
}
if (value instanceof List<?> list && items.isPresent()) {
List<Object> result = new ArrayList<>();
for (Object item : list) {
result.add(fillDefaults(item, items.get()));
}
return result;
}
if ((value instanceof Map || value instanceof List)
&& properties.isEmpty()
&& items.isEmpty()) {
// The first alternative that validates the value decides its defaults.
for (Schema member : schema.anyOf().orElse(ImmutableList.of())) {
if (mismatch(value, member) == null) {
return fillDefaults(value, member);
}
}
}
return value;
}

/** Returns a copy of {@code value} whose maps and lists are new, so callers can change it. */
private static @Nullable Object copyDefault(@Nullable Object value) {
if (value instanceof Map<?, ?> map) {
Map<String, Object> copy = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
copy.put(String.valueOf(entry.getKey()), copyDefault(entry.getValue()));
}
return copy;
}
if (value instanceof List<?> list) {
List<Object> copy = new ArrayList<>();
for (Object item : list) {
copy.add(copyDefault(item));
}
return copy;
}
return value;
}

private static @Nullable String mismatch(@Nullable Object value, Schema schema) {
if (value == null && schema.nullable().orElse(false)) {
return null;
Expand Down
4 changes: 3 additions & 1 deletion core/src/main/java/com/google/adk/agents/LlmAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,9 @@ private void maybeSaveOutputToState(Event event, InvocationContext invocationCon
}
} else if (outputSchema.isPresent()) {
try {
output = SchemaUtils.validateOutput(rawResult, outputSchema.get());
output =
SchemaUtils.valueWithDefaults(
SchemaUtils.validateOutput(rawResult, outputSchema.get()), outputSchema.get());
if (output == null) {
// A JSON null for a nullable array or primitive schema. State cannot hold null, so save
// "", which {key} renders as Python renders None. Single-turn mode skips the save.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
} catch (IllegalArgumentException e) {
return Single.just(result("Error validating input: " + e.getMessage()));
}
nodeInput = args;
nodeInput = SchemaUtils.withDefaults(args, agent.inputSchema().get());
}
Optional<Context> parentNode = toolContext.invocationContext().nodeContext();
if (parentNode.isEmpty()) {
Expand Down
3 changes: 2 additions & 1 deletion core/src/main/java/com/google/adk/tools/AgentTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,10 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
final Content content;
if (agentInputSchema.isPresent()) {
SchemaUtils.validateMapOnSchema(args, agentInputSchema.get(), true);
Map<String, Object> input = SchemaUtils.withDefaults(args, agentInputSchema.get());
try {
content =
Content.fromParts(Part.fromText(JsonBaseModel.getMapper().writeValueAsString(args)));
Content.fromParts(Part.fromText(JsonBaseModel.getMapper().writeValueAsString(input)));
} catch (JsonProcessingException e) {
return Single.error(
new RuntimeException("Error serializing tool arguments to JSON: " + args, e));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
} catch (IllegalArgumentException e) {
return validationFeedback(sanitizeValidationMessage(e.getMessage()));
}
Map<String, Object> validatedResponse = excludeNullFields(args, parameters);
// Fill defaults before dropping nulls so an explicit null is not replaced with a default.
Map<String, Object> validatedResponse =
excludeNullFields(SchemaUtils.withDefaults(args, parameters), parameters);
if (wrapsOutputSchema) {
Object response = validatedResponse.get(RESPONSE_PARAMETER);
if (response == null) {
Expand Down
205 changes: 205 additions & 0 deletions core/src/test/java/com/google/adk/SchemaUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
import com.google.common.collect.ImmutableMap;
import com.google.genai.types.Schema;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Test;
Expand Down Expand Up @@ -482,6 +484,205 @@ public void validateOutput_textForAnArraySchema_throwsJsonProcessingException()
JsonProcessingException.class, () -> SchemaUtils.validateOutput("not json", schema));
}

@Test
public void validateOutputSchema_omittedPropertyWithDefault_leavesItOmitted() throws Exception {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("name", STRING, "extra", defaulted(STRING, "default")))
.build();

Map<String, Object> output = SchemaUtils.validateOutputSchema("{\"name\":\"x\"}", schema);

assertThat(output).containsExactly("name", "x");
}

@Test
public void validateOutputSchema_missingRequiredPropertyWithDefault_throws() {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("extra", defaulted(STRING, "default")))
.required(ImmutableList.of("extra"))
.build();

assertThrows(
IllegalArgumentException.class, () -> SchemaUtils.validateOutputSchema("{}", schema));
}

@Test
public void withDefaults_explicitNull_keepsTheNull() {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(
ImmutableMap.of(
"extra",
Schema.builder().type("STRING").nullable(true).default_("default").build()))
.build();
Map<String, Object> args = new HashMap<>();
args.put("extra", null);

Map<String, Object> filled = SchemaUtils.withDefaults(args, schema);

assertThat(filled).containsExactly("extra", null);
}

@Test
public void withDefaults_listDefault_isCopied() {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(
ImmutableMap.of(
"tags",
Schema.builder()
.type("ARRAY")
.items(STRING)
.default_(new ArrayList<>(ImmutableList.of("a")))
.build()))
.build();

@SuppressWarnings("unchecked") // The default is a list.
List<Object> tags =
(List<Object>) SchemaUtils.withDefaults(ImmutableMap.of(), schema).get("tags");
tags.add("b");

assertThat(schema.properties().get().get("tags").default_()).hasValue(ImmutableList.of("a"));
}

@Test
public void withDefaults_mapDefault_isCopied() {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(
ImmutableMap.of(
"meta",
Schema.builder()
.type("OBJECT")
.default_(new HashMap<>(ImmutableMap.of("k", "v")))
.build()))
.build();

@SuppressWarnings("unchecked") // The default is a map.
Map<String, Object> meta =
(Map<String, Object>) SchemaUtils.withDefaults(ImmutableMap.of(), schema).get("meta");
meta.put("k2", "v2");

assertThat(schema.properties().get().get("meta").default_())
.hasValue(ImmutableMap.of("k", "v"));
}

@Test
public void withDefaults_nestedObjectsAndArrayItems_fillsTheirDefaults() {
Schema item =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("id", INTEGER, "tag", defaulted(STRING, "t")))
.build();
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(
ImmutableMap.of(
"items",
Schema.builder().type("ARRAY").items(item).build(),
"inner",
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("n", defaulted(INTEGER, 3)))
.build()))
.build();

Map<String, Object> filled =
SchemaUtils.withDefaults(
ImmutableMap.of(
"items", ImmutableList.of(ImmutableMap.of("id", 1)), "inner", ImmutableMap.of()),
schema);

assertThat(filled)
.containsExactly(
"items",
ImmutableList.of(ImmutableMap.of("id", 1, "tag", "t")),
"inner",
ImmutableMap.of("n", 3));
}

@Test
public void withDefaults_anyOf_fillsTheDefaultsOfTheMatchingAlternative() {
Schema withA =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("a", INTEGER, "x", defaulted(STRING, "from a")))
.required(ImmutableList.of("a"))
.build();
Schema withB =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("b", INTEGER, "x", defaulted(STRING, "from b")))
.required(ImmutableList.of("b"))
.build();
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(
ImmutableMap.of(
"value", Schema.builder().anyOf(ImmutableList.of(withA, withB)).build()))
.build();

Map<String, Object> filled =
SchemaUtils.withDefaults(ImmutableMap.of("value", ImmutableMap.of("b", 2)), schema);

assertThat(filled).containsExactly("value", ImmutableMap.of("b", 2, "x", "from b"));
}

@Test
public void parseModelOutput_omittedPropertyWithDefault_fillsTheDefault() {
Schema schema =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("name", STRING, "extra", defaulted(STRING, "default")))
.build();

Object output = SchemaUtils.parseModelOutput("{\"name\":\"x\"}", schema);

assertThat(output).isEqualTo(ImmutableMap.of("name", "x", "extra", "default"));
}

@Test
public void validateOutput_arrayOfObjectsOmittingADefault_leavesItOmitted() throws Exception {
Schema item =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("id", INTEGER, "tag", defaulted(STRING, "t")))
.build();
Schema schema = Schema.builder().type("ARRAY").items(item).build();

Object output = SchemaUtils.validateOutput("[{\"id\":1}]", schema);

assertThat(output).isEqualTo(ImmutableList.of(ImmutableMap.of("id", 1)));
}

@Test
public void valueWithDefaults_arrayOfObjects_fillsEachItemsDefaults() throws Exception {
Schema item =
Schema.builder()
.type("OBJECT")
.properties(ImmutableMap.of("id", INTEGER, "tag", defaulted(STRING, "t")))
.build();
Schema schema = Schema.builder().type("ARRAY").items(item).build();

Object output =
SchemaUtils.valueWithDefaults(
SchemaUtils.validateOutput("[{\"id\":1},{\"id\":2,\"tag\":\"u\"}]", schema), schema);

assertThat(output)
.isEqualTo(
ImmutableList.of(
ImmutableMap.of("id", 1, "tag", "t"), ImmutableMap.of("id", 2, "tag", "u")));
}

@Test
public void describesObject_unknownTypeWithProperties_isAnObject() {
Schema schema =
Expand All @@ -494,4 +695,8 @@ public void describesObject_unknownTypeWithProperties_isAnObject() {
public void describesObject_untypedSchemaWithOnlyItems_isNotAnObject() {
assertThat(SchemaUtils.describesObject(Schema.builder().items(STRING).build())).isFalse();
}

private static Schema defaulted(Schema schema, Object defaultValue) {
return schema.toBuilder().default_(defaultValue).build();
}
}
Loading
Loading