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
40 changes: 24 additions & 16 deletions core/src/main/java/com/google/adk/tools/AgentTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
.instantSource(parentContext.instantSource())
.uuidProvider(parentContext.uuidProvider())
.build();
// Follow the caller's RunConfig but run unary: only the last event becomes the result.
// Follow the caller's RunConfig but run unary, so the result is not read from partial chunks.
RunConfig callerRunConfig = parentContext.runConfig();
RunConfig runConfig =
callerRunConfig.streamingMode() == StreamingMode.NONE
Expand All @@ -226,21 +226,14 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
updateState(event.actions().stateDelta(), toolContext.state());
}
})
.lastElement()
.map(Optional::of)
.defaultIfEmpty(Optional.empty())
.map(optionalLastEvent -> {
if (optionalLastEvent.isEmpty()) {
return ImmutableMap.of();
}
Event lastEvent = optionalLastEvent.get();
Optional<String> outputText = lastEvent.content().map(Content::text);

// A run that ends with an error and no text reports the error, as in ADK Python, so the
// model sees the failure instead of an empty result.
String errorMessage = lastEvent.errorMessage().orElse("");
if (outputText.orElse("").isEmpty() && !errorMessage.isEmpty()) {
return ImmutableMap.of("result", errorMessage);
.reduce(RunOutcome.EMPTY, RunOutcome::with)
.map(outcome -> {
Optional<String> outputText = outcome.lastContent().map(Content::text);

// A run that ends without text reports its last error, as in ADK Python, so the model
// sees the failure instead of an empty result.
if (outputText.orElse("").isEmpty() && !outcome.lastErrorMessage().isEmpty()) {
return ImmutableMap.of("result", outcome.lastErrorMessage());
}
if (outputText.isEmpty()) {
return ImmutableMap.of();
Expand All @@ -262,6 +255,21 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
});
}

/**
* The content of the run's last event that has content, and the run's last non-empty error
* message. As in ADK Python and Kotlin, a later event without content, such as a state-only event
* from an after-agent callback, does not hide them.
*/
private record RunOutcome(Optional<Content> lastContent, String lastErrorMessage) {
static final RunOutcome EMPTY = new RunOutcome(Optional.empty(), "");

RunOutcome with(Event event) {
return new RunOutcome(
event.content().or(() -> lastContent),
event.errorMessage().filter(message -> !message.isEmpty()).orElse(lastErrorMessage));
}
}

/**
* Updates the given state map with the state delta.
*
Expand Down
84 changes: 80 additions & 4 deletions core/src/test/java/com/google/adk/tools/AgentToolTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -551,8 +551,7 @@ public void call_emptyErrorMessageWithoutText_returnsEmptyMap() throws Exception
}

@Test
public void call_textAfterEarlierError_withAfterAgentStateEvent_doesNotReturnError()
throws Exception {
public void call_textAfterEarlierError_withAfterAgentStateEvent_returnsText() throws Exception {
Event failure =
Event.builder()
.id("failure")
Expand All @@ -578,8 +577,85 @@ public void call_textAfterEarlierError_withAfterAgentStateEvent_doesNotReturnErr
Map<String, Object> result =
agentTool.runAsync(ImmutableMap.of("request", "magic"), toolContext).blockingGet();

// The run's last event is the state-only one, which has neither text nor an error.
assertThat(result).isEmpty();
// The state-only event the callback adds last does not hide the answer.
assertThat(result).containsExactly("result", "content for event answer");
}

@Test
public void call_errorWithAfterAgentStateEvent_returnsErrorMessage() throws Exception {
Event failure =
Event.builder()
.id("failure")
.invocationId("invocationId")
.author("remote_agent")
.errorMessage("Failed to communicate with the remote agent (A2AClientException)")
.build();
AfterAgentCallback writesState =
callbackContext -> {
callbackContext.state().put("done", true);
return Maybe.empty();
};
BaseAgent testAgent =
new TestBaseAgent(
"remote_agent",
"agent description",
/* beforeAgentCallbacks= */ null,
ImmutableList.of(writesState),
() -> Flowable.just(failure));
AgentTool agentTool = AgentTool.create(testAgent);
ToolContext toolContext = createToolContext(testAgent);

Map<String, Object> result =
agentTool.runAsync(ImmutableMap.of("request", "magic"), toolContext).blockingGet();

assertThat(result)
.containsExactly(
"result", "Failed to communicate with the remote agent (A2AClientException)");
}

@Test
public void call_severalErrors_returnsLastNonEmptyOne() throws Exception {
BaseAgent testAgent =
createSubAgent(
"agent_name",
errorEvent("first", "First failure"),
errorEvent("second", "Second failure"),
errorEvent("third", ""));
AgentTool agentTool = AgentTool.create(testAgent);
ToolContext toolContext = createToolContext(testAgent);

Map<String, Object> result =
agentTool.runAsync(ImmutableMap.of("request", "magic"), toolContext).blockingGet();

assertThat(result).containsExactly("result", "Second failure");
}

private static Event errorEvent(String id, String errorMessage) {
return Event.builder()
.id(id)
.invocationId("invocationId")
.author("agent_name")
.errorMessage(errorMessage)
.build();
}

@Test
public void call_errorAfterText_returnsText() throws Exception {
Event failure =
Event.builder()
.id("failure")
.invocationId("invocationId")
.author("agent_name")
.errorMessage("Transient failure")
.build();
BaseAgent testAgent = createSubAgent("agent_name", createEvent("answer"), failure);
AgentTool agentTool = AgentTool.create(testAgent);
ToolContext toolContext = createToolContext(testAgent);

Map<String, Object> result =
agentTool.runAsync(ImmutableMap.of("request", "magic"), toolContext).blockingGet();

assertThat(result).containsExactly("result", "content for event answer");
}

@Test
Expand Down
Loading