diff --git a/core/src/main/java/com/google/adk/SchemaUtils.java b/core/src/main/java/com/google/adk/SchemaUtils.java index fad0e5ebb..b518d800b 100644 --- a/core/src/main/java/com/google/adk/SchemaUtils.java +++ b/core/src/main/java/com/google/adk/SchemaUtils.java @@ -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; @@ -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. * *

This method is only for use by Agent Development Kit. * @@ -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"; @@ -268,6 +270,86 @@ public static Map 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. + * + *

This method is only for use by Agent Development Kit. + */ + @SuppressWarnings("unchecked") // A map stays a map with String keys. + public static Map withDefaults(Map args, Schema schema) { + return (Map) fillDefaults(Preconditions.checkNotNull(args), schema); + } + + /** + * Returns {@code value}, any JSON value, as {@link #withDefaults} fills it; null stays null. + * + *

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> properties = schema.properties(); + Optional items = schema.items(); + if (value instanceof Map map && properties.isPresent()) { + Map 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 property : properties.get().entrySet()) { + // An explicit null is a value, so only an absent key gets the default. + Optional 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 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 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 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; diff --git a/core/src/main/java/com/google/adk/agents/LlmAgent.java b/core/src/main/java/com/google/adk/agents/LlmAgent.java index 6882e1116..3e9403ae6 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -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. diff --git a/core/src/main/java/com/google/adk/agents/SingleTurnAgentTool.java b/core/src/main/java/com/google/adk/agents/SingleTurnAgentTool.java index 719844418..fc4fac4b6 100644 --- a/core/src/main/java/com/google/adk/agents/SingleTurnAgentTool.java +++ b/core/src/main/java/com/google/adk/agents/SingleTurnAgentTool.java @@ -71,7 +71,7 @@ public Single> runAsync(Map args, ToolContex } catch (IllegalArgumentException e) { return Single.just(result("Error validating input: " + e.getMessage())); } - nodeInput = args; + nodeInput = SchemaUtils.withDefaults(args, agent.inputSchema().get()); } Optional parentNode = toolContext.invocationContext().nodeContext(); if (parentNode.isEmpty()) { diff --git a/core/src/main/java/com/google/adk/tools/AgentTool.java b/core/src/main/java/com/google/adk/tools/AgentTool.java index c2e106536..081ddc00a 100644 --- a/core/src/main/java/com/google/adk/tools/AgentTool.java +++ b/core/src/main/java/com/google/adk/tools/AgentTool.java @@ -173,9 +173,10 @@ public Single> runAsync(Map args, ToolContex final Content content; if (agentInputSchema.isPresent()) { SchemaUtils.validateMapOnSchema(args, agentInputSchema.get(), true); + Map 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)); diff --git a/core/src/main/java/com/google/adk/tools/SetModelResponseTool.java b/core/src/main/java/com/google/adk/tools/SetModelResponseTool.java index c32448185..e234b663b 100644 --- a/core/src/main/java/com/google/adk/tools/SetModelResponseTool.java +++ b/core/src/main/java/com/google/adk/tools/SetModelResponseTool.java @@ -102,7 +102,9 @@ public Single> runAsync(Map args, ToolContex } catch (IllegalArgumentException e) { return validationFeedback(sanitizeValidationMessage(e.getMessage())); } - Map validatedResponse = excludeNullFields(args, parameters); + // Fill defaults before dropping nulls so an explicit null is not replaced with a default. + Map validatedResponse = + excludeNullFields(SchemaUtils.withDefaults(args, parameters), parameters); if (wrapsOutputSchema) { Object response = validatedResponse.get(RESPONSE_PARAMETER); if (response == null) { diff --git a/core/src/test/java/com/google/adk/SchemaUtilsTest.java b/core/src/test/java/com/google/adk/SchemaUtilsTest.java index 2c9b5ea5a..d7a750092 100644 --- a/core/src/test/java/com/google/adk/SchemaUtilsTest.java +++ b/core/src/test/java/com/google/adk/SchemaUtilsTest.java @@ -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; @@ -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 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 args = new HashMap<>(); + args.put("extra", null); + + Map 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 tags = + (List) 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 meta = + (Map) 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 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 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 = @@ -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(); + } } diff --git a/core/src/test/java/com/google/adk/agents/LlmAgentTest.java b/core/src/test/java/com/google/adk/agents/LlmAgentTest.java index e180af8e0..f1540c16e 100644 --- a/core/src/test/java/com/google/adk/agents/LlmAgentTest.java +++ b/core/src/test/java/com/google/adk/agents/LlmAgentTest.java @@ -225,6 +225,29 @@ public void testRun_withOutputKeyAndFreeFormOutputSchema_savesParsedState() { assertThat(getOnlyElement(events).actions().stateDelta()).containsEntry("answer", expected); } + @Test + public void testRun_withOutputKeyAndOutputSchema_savesTheDefaultsOfOmittedProperties() { + Schema outputSchema = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "city", + Schema.builder().type("STRING").build(), + "country", + Schema.builder().type("STRING").default_("France").build())) + .build(); + TestLlm testLlm = createTestLlm(createTextLlmResponse("{\"city\":\"Paris\"}")); + LlmAgent agent = + createTestAgentBuilder(testLlm).outputSchema(outputSchema).outputKey("answer").build(); + InvocationContext invocationContext = createInvocationContext(agent); + + List events = agent.runAsync(invocationContext).toList().blockingGet(); + + assertThat(getOnlyElement(events).actions().stateDelta()) + .containsEntry("answer", ImmutableMap.of("city", "Paris", "country", "France")); + } + @Test public void testRun_withOutputKey_savesMultiPartState() { Content modelContent = Content.fromParts(Part.fromText("Part 1."), Part.fromText(" Part 2.")); diff --git a/core/src/test/java/com/google/adk/tools/AgentToolTest.java b/core/src/test/java/com/google/adk/tools/AgentToolTest.java index 6e365e4d3..b59bb7896 100644 --- a/core/src/test/java/com/google/adk/tools/AgentToolTest.java +++ b/core/src/test/java/com/google/adk/tools/AgentToolTest.java @@ -455,6 +455,71 @@ public void call_withInputSchema_argsAreSentToAgent() throws Exception { .containsExactly(Content.fromParts(Part.fromText("{\"is_magic\":true}"))); } + @Test + public void call_withInputSchema_omittedArgWithDefault_sendsTheDefault() throws Exception { + TestLlm testLlm = + createTestLlm( + LlmResponse.builder() + .content(Content.fromParts(Part.fromText("test response"))) + .build()); + LlmAgent testAgent = + createTestAgentBuilder(testLlm) + .name("agent_name") + .description("agent description") + .inputSchema( + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "is_magic", + Schema.builder().type("BOOLEAN").build(), + "level", + Schema.builder().type("INTEGER").default_(3).build())) + .required(ImmutableList.of("is_magic")) + .build()) + .build(); + AgentTool agentTool = AgentTool.create(testAgent); + ToolContext toolContext = createToolContext(testAgent); + + Map unused = + agentTool.runAsync(ImmutableMap.of("is_magic", true), toolContext).blockingGet(); + + assertThat(testLlm.getLastRequest().contents()) + .containsExactly(Content.fromParts(Part.fromText("{\"is_magic\":true,\"level\":3}"))); + } + + @Test + public void call_withOutputSchema_omittedPropertyWithDefault_isLeftOmitted() throws Exception { + Schema outputSchema = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "is_valid", + Schema.builder().type("BOOLEAN").build(), + "message", + Schema.builder().type("STRING").default_("none").build())) + .required(ImmutableList.of("is_valid")) + .build(); + LlmAgent testAgent = + createTestAgentBuilder( + createTestLlm( + LlmResponse.builder() + .content(Content.fromParts(Part.fromText("{\"is_valid\": true}"))) + .build())) + .name("agent_name") + .description("agent description") + .outputSchema(outputSchema) + .build(); + AgentTool agentTool = AgentTool.create(testAgent); + ToolContext toolContext = createToolContext(testAgent); + + Map result = + agentTool.runAsync(ImmutableMap.of("request", "test"), toolContext).blockingGet(); + + assertThat(result).containsExactly("is_valid", true); + } + @Test public void call_withoutInputSchema_requestIsSentToAgent() throws Exception { TestLlm testLlm = diff --git a/core/src/test/java/com/google/adk/tools/SetModelResponseToolTest.java b/core/src/test/java/com/google/adk/tools/SetModelResponseToolTest.java index 1a762152f..30f9bdcbd 100644 --- a/core/src/test/java/com/google/adk/tools/SetModelResponseToolTest.java +++ b/core/src/test/java/com/google/adk/tools/SetModelResponseToolTest.java @@ -430,6 +430,54 @@ public void runAsync_validatesComplexArgs() { assertThat(toolContext.actions().setModelResponse()).hasValue(complexArgs); } + @Test + public void runAsync_omittedPropertyWithDefault_recordsTheDefault() { + Schema outputSchema = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "a", + Schema.builder().type("STRING").build(), + "b", + Schema.builder().type("STRING").default_("fallback").build())) + .build(); + + ToolContext toolContext = createToolContext(); + Map result = + new SetModelResponseTool(outputSchema) + .runAsync(ImmutableMap.of("a", "x"), toolContext) + .blockingGet(); + + assertThat(result).containsExactly("a", "x", "b", "fallback"); + assertThat(toolContext.actions().setModelResponse()) + .hasValue(ImmutableMap.of("a", "x", "b", "fallback")); + } + + @Test + public void runAsync_nullForPropertyWithDefault_dropsItWithoutTheDefault() { + Schema outputSchema = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "a", + Schema.builder().type("STRING").build(), + "b", + Schema.builder().type("STRING").nullable(true).default_("fallback").build())) + .build(); + Map args = new LinkedHashMap<>(); + args.put("a", "x"); + args.put("b", null); + + ToolContext toolContext = createToolContext(); + Map result = + new SetModelResponseTool(outputSchema).runAsync(args, toolContext).blockingGet(); + + assertThat(result).containsExactly("a", "x"); + assertThat(toolContext.actions().setModelResponse()).hasValue(ImmutableMap.of("a", "x")); + } + @Test public void declaration_arraySchema_wrapsItInAResponseParameter() { SetModelResponseTool tool = new SetModelResponseTool(STRING_ARRAY_SCHEMA); diff --git a/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java b/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java index 716d391f9..d2c0d9628 100644 --- a/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java +++ b/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java @@ -500,6 +500,27 @@ public void runAsync_singleTurnNodeWithAnOutputSchema_givesAndSavesTheParsedValu assertThat(outputEvent.nodeInfo().map(NodeInfo::messageAsOutput)).hasValue(false); } + @Test + public void runAsync_singleTurnNodeWithAnOutputSchema_fillsTheDefaultsOfOmittedProperties() { + Schema schema = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "title", + Schema.builder().type("STRING").build(), + "count", + Schema.builder().type("INTEGER").default_(1).build())) + .build(); + LlmAgent agent = schemaAgent(schema, "{\"title\": \"Story\"}").outputKey("meta").build(); + + NodeRun nodeRun = runWithSuccessor(agent); + + ImmutableMap expected = ImmutableMap.of("title", "Story", "count", 1); + assertThat(nodeRun.output()).isEqualTo(expected); + assertThat(stateDeltaValues(nodeRun.events(), "meta")).containsExactly(expected); + } + @Test public void runAsync_singleTurnNodeWithAStringSchema_givesItsPlainText() { LlmAgent agent = diff --git a/core/src/test/java/com/google/adk/workflow/LlmAgentModeTest.java b/core/src/test/java/com/google/adk/workflow/LlmAgentModeTest.java index 2b7e33648..59b0d2c23 100644 --- a/core/src/test/java/com/google/adk/workflow/LlmAgentModeTest.java +++ b/core/src/test/java/com/google/adk/workflow/LlmAgentModeTest.java @@ -624,6 +624,36 @@ public void singleTurnSubAgentWithAnInputSchema_getsTheArgsAsItsInput() { .containsExactly(userText("{\"city\":\"Paris\"}")); } + @Test + public void singleTurnSubAgentWithAnInputSchema_getsTheDefaultsOfOmittedArgs() { + TestLlm helperModel = TestLlm.create(createTextLlmResponse("Sunny")); + LlmAgent helper = + LlmAgent.builder() + .name("helper") + .model(helperModel) + .mode(AgentMode.SINGLE_TURN) + .inputSchema( + CITY_SCHEMA.toBuilder() + .properties( + ImmutableMap.of( + "city", + Schema.builder().type("STRING").build(), + "unit", + Schema.builder().type("STRING").default_("celsius").build())) + .build()) + .build(); + TestLlm model = + TestLlm.create( + createFunctionCallLlmResponse("call_1", "helper", ImmutableMap.of("city", "Paris")), + createTextLlmResponse("done")); + + new WorkflowSession(workflow(new Edge(START, chat("coordinator", model, helper)))) + .advance(go()); + + assertThat(helperModel.getLastRequest().contents()) + .containsExactly(userText("{\"city\":\"Paris\",\"unit\":\"celsius\"}")); + } + @Test public void agent_doesNotListASingleTurnPeerAsATransferTarget() { LlmAgent agent = LlmAgent.builder().name("agent").model(TestLlm.create("ok")).build(); diff --git a/core/src/test/java/com/google/adk/workflow/LlmAgentTaskModeTest.java b/core/src/test/java/com/google/adk/workflow/LlmAgentTaskModeTest.java index 78de8f3de..40b1a73ce 100644 --- a/core/src/test/java/com/google/adk/workflow/LlmAgentTaskModeTest.java +++ b/core/src/test/java/com/google/adk/workflow/LlmAgentTaskModeTest.java @@ -166,6 +166,29 @@ public void taskAgentWithAnOutputSchema_declaresItAndGetsNoResponseSchema() { .hasValue(ImmutableMap.of("received", ImmutableMap.of("city", "Paris"))); } + @Test + public void taskAgentWithAnOutputSchema_savesTheFinishTaskArgsWithoutDefaults() { + Schema city = + Schema.builder() + .type("OBJECT") + .properties( + ImmutableMap.of( + "city", + Schema.builder().type("STRING").build(), + "country", + Schema.builder().type("STRING").default_("France").build())) + .required(ImmutableList.of("city")) + .build(); + TestLlm model = TestLlm.create(finishTask(ImmutableMap.of("city", "Paris"))); + LlmAgent task = task(model).outputSchema(city).outputKey("booking").build(); + WorkflowSession session = new WorkflowSession(withSuccessor(task)); + + var unused = session.turn(go()); + + assertThat(stateValues(session.storedEvents(), "booking")) + .containsExactly(ImmutableMap.of("city", "Paris")); + } + @Test public void taskAgentWithANonObjectOutputSchema_takesItsOutputUnderResult() { Schema text = Schema.builder().type("STRING").build(); diff --git a/core/src/test/java/com/google/adk/workflow/ResumeScanTest.java b/core/src/test/java/com/google/adk/workflow/ResumeScanTest.java index 3b51c4c86..576b14768 100644 --- a/core/src/test/java/com/google/adk/workflow/ResumeScanTest.java +++ b/core/src/test/java/com/google/adk/workflow/ResumeScanTest.java @@ -478,6 +478,24 @@ public void validateAnswer_answerThatFits_isReturned() { assertThat(answer).isEqualTo(ImmutableMap.of("count", 1)); } + @Test + public void validateAnswer_answerOmittingADefaultedProperty_isReturnedWithoutTheDefault() { + Schema schema = + Schema.builder() + .type(Type.Known.OBJECT) + .properties( + ImmutableMap.of( + "count", + Schema.builder().type(Type.Known.INTEGER).build(), + "unit", + Schema.builder().type(Type.Known.STRING).default_("items").build())) + .build(); + + Object answer = ResumeScan.validateAnswer(schema, ImmutableMap.of("count", 1), "ask_1"); + + assertThat(answer).isEqualTo(ImmutableMap.of("count", 1)); + } + @Test public void validateAnswer_objectTheSchemaRejects_failsWithoutTheValue() { IllegalArgumentException error =