Skip to content
Merged
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
205 changes: 161 additions & 44 deletions core/src/main/java/com/google/adk/SchemaUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.math.BigInteger;
Expand All @@ -32,6 +34,7 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import org.jspecify.annotations.Nullable;

/** Utility class for reading JSON and validating values against schemas. */
Expand Down Expand Up @@ -331,11 +334,15 @@ public static Map<String, Object> withDefaults(Map<String, Object> args, Schema
}

/**
* Returns whether {@code value} can receive defaults from {@code schema}. In addition to {@link
* #mismatch}, it checks enum values, nested {@code anyOf} alternatives, and types inferred from
* keys, including items of an untyped array.
* Returns whether {@code value} can receive defaults from {@code schema}. Beyond the strict
* schema check, it requires types inferred from keys or items to match, at every depth.
*/
private static boolean fits(@Nullable Object value, Schema schema) {
return fits(value, schema, ImmutableSet.of());
}

/** Like {@link #fits(Object, Schema)}, but a map may also hold any key in {@code inherited}. */
private static boolean fits(@Nullable Object value, Schema schema, Set<String> inherited) {
if (value == null && schema.nullable().orElse(false)) {
return true;
}
Expand All @@ -347,15 +354,12 @@ private static boolean fits(@Nullable Object value, Schema schema) {
: value instanceof List<?>
? type == Type.Known.ARRAY
: type != Type.Known.OBJECT && type != Type.Known.ARRAY);
if (!kindFits || mismatch(value, schema) != null) {
return false;
}
Optional<List<String>> allowed = schema.enum_();
if (allowed.isPresent() && (value == null || !allowed.get().contains(String.valueOf(value)))) {
if (!kindFits || mismatch(value, schema, /* strict= */ true, inherited) != null) {
return false;
}
List<Schema> anyOf = schema.anyOf().orElse(ImmutableList.of());
if (!anyOf.isEmpty() && anyOf.stream().noneMatch(member -> fits(value, member))) {
Set<String> declared = declaredWith(inherited, schema);
if (!anyOf.isEmpty() && anyOf.stream().noneMatch(member -> fits(value, member, declared))) {
return false;
}
if (value instanceof Map<?, ?> map && schema.properties().isPresent()) {
Expand Down Expand Up @@ -406,18 +410,24 @@ private static boolean fits(@Nullable Object value, Schema schema) {
* depth and the items of a list under an untyped schema, as a workflow node's schema check does.
*/
private static @Nullable String mismatch(@Nullable Object value, Schema schema, boolean strict) {
return mismatch(value, schema, strict, ImmutableSet.of());
}

/**
* Like {@link #mismatch(Object, Schema, boolean)}, but a map may also hold any key in {@code
* inherited}, which a schema enclosing this {@code anyOf} member declares and checks.
*/
private static @Nullable String mismatch(
@Nullable Object value, Schema schema, boolean strict, Set<String> inherited) {
if (value == null && schema.nullable().orElse(false)) {
return null;
}
Optional<List<String>> allowed = schema.enum_();
if (strict
&& allowed.isPresent()
&& (value == null || !allowed.get().contains(String.valueOf(value)))) {
if (strict && outsideEnum(value, schema)) {
return "it is not one of the schema's enum values";
}
// Check maps before anyOf so each member is validated as an object with its required keys.
if (value instanceof Map<?, ?> map) {
return mapMismatch(map, schema, strict);
return mapCheck(map, schema, strict, inherited, /* enclosingChecksKeys= */ false).reason();
}
List<Schema> anyOf = schema.anyOf().orElse(ImmutableList.of());
if (!anyOf.isEmpty()
Expand All @@ -426,14 +436,13 @@ private static boolean fits(@Nullable Object value, Schema schema) {
}
Type.Known type = typeOf(schema);
if (type == null || type == Type.Known.TYPE_UNSPECIFIED) {
Schema itemSchema = schema.items().orElse(null);
return strict
&& itemSchema != null
&& value instanceof Collection<?> items
&& items.stream().anyMatch(item -> mismatch(item, itemSchema, strict) != null)
? "an item does not match the schema's items"
return strict && value instanceof Collection<?> items
? itemsMismatch(items, schema.items().orElse(null), strict)
: null;
}
if (type == Type.Known.ARRAY && value instanceof Collection<?> items) {
return itemsMismatch(items, schema.items().orElse(null), strict);
}
boolean matches =
switch (type) {
case STRING -> value instanceof String;
Expand All @@ -446,51 +455,159 @@ private static boolean fits(@Nullable Object value, Schema schema) {
case NUMBER -> value instanceof Number;
case BOOLEAN -> value instanceof Boolean;
case NULL -> value == null;
case ARRAY -> {
if (!(value instanceof Collection<?> items)) {
yield false;
}
Optional<Schema> itemSchema = schema.items();
yield itemSchema.isEmpty()
|| items.stream()
.allMatch(item -> mismatch(item, itemSchema.get(), strict) == null);
}
case OBJECT -> false;
case ARRAY, OBJECT -> false; // Maps, and lists under ARRAY, were handled above.
default -> true;
};
return matches ? null : "it is not of the schema's type " + type;
}

/** Returns why {@code map} does not match {@code schema}, or {@code null} if it does. */
private static @Nullable String mapMismatch(Map<?, ?> map, Schema schema, boolean strict) {
/**
* Returns the mismatch reason for the first item in {@code items} that fails {@code itemSchema}.
*/
private static @Nullable String itemsMismatch(
Collection<?> items, @Nullable Schema itemSchema, boolean strict) {
if (itemSchema == null) {
return null;
}
for (Object item : items) {
String reason = mismatch(item, itemSchema, strict);
if (reason != null) {
return "an item does not match the schema's items: " + reason;
}
}
return null;
}

/** Why a map does not match, or null, and whether its keys were checked against declared ones. */
private record MapCheck(@Nullable String reason, boolean keysChecked) {
static MapCheck failed(String reason) {
return new MapCheck(reason, false);
}
}

/**
* Checks {@code map} against {@code schema}. A key counts as declared if {@code schema} declares
* it, an enclosing schema does ({@code inherited}), or the {@code anyOf} member that matched
* checked it, so a member need not repeat its parent's keys; {@code enclosingChecksKeys} says
* whether an enclosing schema rejects a key that no member checked.
*/
private static MapCheck mapCheck(
Map<?, ?> map,
Schema schema,
boolean strict,
Set<String> inherited,
boolean enclosingChecksKeys) {
Type.Known type = typeOf(schema);
if (type != null && type != Type.Known.OBJECT && type != Type.Known.TYPE_UNSPECIFIED) {
return "the schema's type is " + type + ", not an object";
return MapCheck.failed("the schema's type is " + type + ", not an object");
}
Optional<Map<String, Schema>> properties = schema.properties();
boolean checksKeys = enclosingChecksKeys || properties.isPresent();
boolean memberCheckedKeys = false;
List<Schema> anyOf = schema.anyOf().orElse(ImmutableList.of());
if (!anyOf.isEmpty()
&& anyOf.stream().allMatch(member -> mismatch(map, member, strict) != null)) {
return "it matches none of the schema's anyOf alternatives";
if (!anyOf.isEmpty()) {
Set<String> declared = declaredWith(inherited, schema);
boolean keyLeftOver =
checksKeys
&& map.keySet().stream()
.map(String::valueOf)
.anyMatch(key -> !declared.contains(key));
boolean matched = false;
// Failed member with the most required keys, all present in the map, unless tied.
String closestReason = null;
int closestRequired = 0;
for (Schema member : anyOf) {
MapCheck check = memberCheck(map, member, strict, declared, checksKeys);
if (check.reason() == null) {
matched = true;
memberCheckedKeys = check.keysChecked();
// A member that checked no keys may leave one that a later member declares.
if (memberCheckedKeys || !keyLeftOver) {
break;
}
continue;
}
int required = requiredKeysPresent(map, member);
if (required > closestRequired) {
closestRequired = required;
closestReason = check.reason();
} else if (required == closestRequired) {
closestReason = null;
}
}
if (!matched) {
String reason = "it matches none of the schema's anyOf alternatives";
return MapCheck.failed(
closestReason == null ? reason : reason + "; the closest one fails: " + closestReason);
}
}
Optional<Map<String, Schema>> properties = schema.properties();
if (properties.isPresent()) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
Schema property = properties.get().get(String.valueOf(entry.getKey()));
// An undeclared key comes from the user, so the reason does not name it.
String key = String.valueOf(entry.getKey());
Schema property = properties.get().get(key);
if (property == null) {
return "it has a key the schema does not declare";
// An enclosing schema or the matched member checks a key it declares.
if (inherited.contains(key) || memberCheckedKeys) {
continue;
}
// An undeclared key comes from the user, so the reason does not name it.
return MapCheck.failed("it has a key the schema does not declare");
}
if (mismatch(entry.getValue(), property, strict) != null) {
return "property '" + entry.getKey() + "' does not match its schema";
String propertyReason = mismatch(entry.getValue(), property, strict);
if (propertyReason != null) {
return MapCheck.failed(propertyMismatch(key, propertyReason));
}
}
}
for (String required : schema.required().orElse(ImmutableList.of())) {
if (!map.containsKey(required)) {
return "required property '" + required + "' is missing";
return MapCheck.failed("required property '" + required + "' is missing");
}
}
return null;
return new MapCheck(null, properties.isPresent() || memberCheckedKeys);
}

/**
* Returns a mismatch reason for property {@code key}, joining nested names into one path; for
* example, {@code property 'error.code' does not match its schema: <reason>}.
*/
private static String propertyMismatch(String key, String reason) {
String nestedProperty = "property '";
return reason.startsWith(nestedProperty)
? nestedProperty + key + "." + reason.substring(nestedProperty.length())
: nestedProperty + key + "' does not match its schema: " + reason;
}

/** Returns the number of keys {@code member} requires if {@code map} contains them all, or 0. */
private static int requiredKeysPresent(Map<?, ?> map, Schema member) {
List<String> required = member.required().orElse(ImmutableList.of());
return required.stream().allMatch(map::containsKey) ? required.size() : 0;
}

/** Checks {@code map} against an {@code anyOf} member, its enum included if {@code strict}. */
private static MapCheck memberCheck(
Map<?, ?> map,
Schema member,
boolean strict,
Set<String> inherited,
boolean enclosingChecksKeys) {
if (strict && outsideEnum(map, member)) {
return MapCheck.failed("it is not one of the schema's enum values");
}
return mapCheck(map, member, strict, inherited, enclosingChecksKeys);
}

/** Returns whether {@code schema} has an enum that does not list {@code value}. */
private static boolean outsideEnum(@Nullable Object value, Schema schema) {
Optional<List<String>> allowed = schema.enum_();
return allowed.isPresent() && (value == null || !allowed.get().contains(String.valueOf(value)));
}

/** Returns {@code inherited} with the keys {@code schema} declares. */
private static Set<String> declaredWith(Set<String> inherited, Schema schema) {
return schema.properties().isPresent()
? Sets.union(inherited, schema.properties().get().keySet())
: inherited;
}

private static Type.@Nullable Known typeOf(Schema schema) {
Expand Down
34 changes: 22 additions & 12 deletions core/src/main/java/com/google/adk/tools/SetModelResponseTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class SetModelResponseTool extends BaseTool {
// Function parameters must be an object, so a non-object output schema goes into this field.
private static final String RESPONSE_PARAMETER = "response";

private final Schema outputSchema;
private final boolean wrapsOutputSchema;
private final Schema parameters;

Expand All @@ -55,6 +56,7 @@ public SetModelResponseTool(Schema outputSchema) {
"Set your final response using the required output schema. "
+ "After using any other tools needed to complete the task, always call"
+ " set_model_response with your final answer in the specified schema format.");
this.outputSchema = outputSchema;
this.wrapsOutputSchema = !SchemaUtils.describesObject(outputSchema);
if (wrapsOutputSchema) {
// Vertex AI rejects an untyped parameter; a wrapped untyped schema has only items.
Expand Down Expand Up @@ -103,20 +105,28 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
return validationFeedback(sanitizeValidationMessage(e.getMessage()));
}
// 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) {
// A null answer cannot end the run, so the model has to give a value.
return validationFeedback("Output arg: " + RESPONSE_PARAMETER + " must not be null");
Map<String, Object> withDefaults = SchemaUtils.withDefaults(args, parameters);
Map<String, Object> validatedResponse = excludeNullFields(withDefaults, parameters);
Object answer =
wrapsOutputSchema ? validatedResponse.get(RESPONSE_PARAMETER) : validatedResponse;
if (answer == null) {
// A null answer cannot end the run, so the model has to give a value.
return validationFeedback("Output arg: " + RESPONSE_PARAMETER + " must not be null");
}
// validateMapOnSchema skips enum values, which a workflow node's output check enforces.
Optional<String> mismatch = SchemaUtils.findMismatch(answer, outputSchema);
if (mismatch.isPresent()) {
// An anyOf branch can require a null that excludeNullFields dropped.
Object withNulls = wrapsOutputSchema ? withDefaults.get(RESPONSE_PARAMETER) : withDefaults;
if (SchemaUtils.findMismatch(withNulls, outputSchema).isPresent()) {
return validationFeedback("Output args: " + mismatch.get());
}
toolContext.actions().setSetModelResponse(response);
// Like a function tool's non-map result.
return ImmutableMap.of("result", response);
answer = withNulls;
validatedResponse = withDefaults;
}
toolContext.actions().setSetModelResponse(validatedResponse);
return validatedResponse;
toolContext.actions().setSetModelResponse(answer);
// A wrapped answer comes back like a function tool's non-map result.
return wrapsOutputSchema ? ImmutableMap.of("result", answer) : validatedResponse;
});
}

Expand Down
Loading
Loading