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
18 changes: 16 additions & 2 deletions a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,13 @@ private Message.Builder newA2AMessage(
private @Nullable Message prepareMessage(
InvocationContext invocationContext, ImmutableList<Event> events) {
// An answer that was all credentials answers no call, so history is sent instead.
Event callEvent = EventConverter.findUserFunctionCall(events);
ImmutableList<Event> answered =
withoutTrailingEmptyEvents(events, invocationContext.invocationId());
Event callEvent = answered.isEmpty() ? null : EventConverter.findUserFunctionCall(answered);
if (callEvent != null) {
// As in ADK Python, a call that came without ids sends none.
return newA2AMessage(invocationContext, Message.Role.USER, EventConverter.answerParts(events))
return newA2AMessage(
invocationContext, Message.Role.USER, EventConverter.answerParts(answered))
.taskId(emptyToNull(EventConverter.taskId(callEvent)))
.contextId(emptyToNull(EventConverter.contextId(callEvent)))
.build();
Expand Down Expand Up @@ -362,6 +365,17 @@ private static Optional<String> metadataValue(Event event, A2AMetadata.Key key)
.flatMap(CustomMetadata::stringValue);
}

/** Returns {@code events} without this agent's empty events of this invocation at the end. */
private ImmutableList<Event> withoutTrailingEmptyEvents(
ImmutableList<Event> events, String invocationId) {
int end = events.size();
while (end > 0
&& EventConverter.isEmptyEventOfInvocation(events.get(end - 1), name(), invocationId)) {
end--;
}
return events.subList(0, end);
}

@Override
protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
// One snapshot, so the call found and the answer sent come from the same list.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.jspecify.annotations.Nullable;

Expand Down Expand Up @@ -186,9 +187,11 @@ public static ImmutableList<Part<?>> contentToParts(
* Returns the parts from the context events that should be sent to the agent.
*
* <p>All session events from the previous remote agent response (or the beginning of the session
* in case of the first agent invocation) are included into the A2A message. A failed request is
* not a response. Events from other agents are presented as user messages and rephased as if a
* user was telling what happened in the session up to the point. Credential parts are left out.
* in case of the first agent invocation) are included into the A2A message, skipping this agent's
* empty events of the current invocation (see {@link #isEmptyEventOfInvocation}). A failed
* request is not a response. Events from other agents are presented as user messages and
* rephrased as if a user was telling what happened in the session up to the point. Credential
* parts are left out.
*
* @param context The invocation context to get the parts from.
* @return A list of A2A Parts.
Expand All @@ -203,7 +206,9 @@ public static ImmutableList<Part<?>> messagePartsFromContext(InvocationContext c
for (int i = events.size() - 1; i >= 0; i--) {
Event event = events.get(i);
// A failed request's turn may not have reached the remote agent, so it is sent again.
if (event.author().equals(context.agent().name()) && !isFailedRequest(event)) {
if (event.author().equals(context.agent().name())
&& !isFailedRequest(event)
&& !isEmptyEventOfInvocation(event, context.agent().name(), context.invocationId())) {
lastResponseIndex = i;
break;
}
Expand All @@ -227,6 +232,25 @@ public static ImmutableList<Part<?>> messagePartsFromContext(InvocationContext c
return partsBuilder.build();
}

/**
* Returns whether {@code event} is an event of {@code agentName} in invocation {@code
* invocationId} with no content, no error, no recorded response and no context ID, such as one a
* before-agent callback wrote only to update state. Such an event from an earlier invocation
* still ends the history, since a callback may have blocked that turn. Within one invocation, as
* when a {@code LoopAgent} runs the agent again, it does not.
*/
@Experimental
public static boolean isEmptyEventOfInvocation(
Event event, String agentName, String invocationId) {
return Objects.equals(event.author(), agentName)
&& Objects.equals(event.invocationId(), invocationId)
&& event.content().flatMap(Content::parts).map(List::isEmpty).orElse(true)
&& event.errorMessage().isEmpty()
&& event.errorCode().isEmpty()
&& findMetadata(event, A2AMetadata.Key.RESPONSE.getValue()).isEmpty()
&& contextId(event).isEmpty();
}

/** Returns whether the event records a failed request: an error with no response or context. */
private static boolean isFailedRequest(Event event) {
return event.errorMessage().isPresent()
Expand Down
99 changes: 99 additions & 0 deletions a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,31 @@ public void runAsync_answeringRemoteCall_sendsAnswerInItsTask() {
assertThat(answer.getData()).containsEntry("id", "call-1");
}

@Test
public void runAsync_answeringRemoteCallAfterStateOnlyEvent_sendsAnswerInItsTask() {
// A before-agent callback that only wrote state left an event after the user's answer.
Message message =
sendAndCapture(
historyContext(
event("remote-agent", functionCall("fn", "call-1")).toBuilder()
.customMetadata(
ImmutableList.of(
metadata("a2a:task_id", "task-1"),
metadata("a2a:context_id", "context-1")))
.build(),
event("user", functionResponse("fn", "call-1", ImmutableMap.of("result", "ok"))),
Event.builder()
.author("remote-agent")
.invocationId(invocationContext.invocationId())
.build()));

assertThat(message.getTaskId()).isEqualTo("task-1");
assertThat(message.getContextId()).isEqualTo("context-1");
DataPart answer = (DataPart) Iterables.getOnlyElement(message.getParts());
assertThat(answer.getMetadata()).containsEntry("adk_type", "function_response");
assertThat(answer.getData()).containsEntry("id", "call-1");
}

@Test
public void runAsync_answeringRemoteCallWithoutIds_sendsNoIds() {
Message message =
Expand Down Expand Up @@ -2252,6 +2277,80 @@ private static ImmutableList<FinishReason> errorCodes(List<Event> events) {
.collect(ImmutableList.toImmutableList());
}

@Test
@SuppressWarnings("unchecked") // cast for Mockito
public void runAsync_afterStateOnlyBeforeAgentCallback_sendsTheUserMessage() {
// A before-agent callback that only writes state lets the agent run, but leaves an event of
// this agent with no content in the session.
RemoteA2AAgent agent =
getAgentBuilder()
.beforeAgentCallback(
ImmutableList.<Callbacks.BeforeAgentCallback>of(
(CallbackContext callbackContext) -> {
callbackContext.state().put("seen", true);
return Maybe.empty();
}))
.build();
InMemoryRunner runner = new InMemoryRunner(agent);
Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet();
mockStreamResponse(consumer -> consumer.accept(createFinalEvent("hi"), agentCard));

var unused =
runner
.runAsync("user", session.id(), Content.fromParts(Part.fromText("hello")))
.toList()
.blockingGet();

ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockClient)
.sendMessage(messageCaptor.capture(), any(List.class), any(Consumer.class), any());
assertThat(((TextPart) messageCaptor.getValue().getParts().get(0)).getText())
.isEqualTo("hello");
}

@Test
@SuppressWarnings("unchecked") // cast for Mockito
public void runAsync_afterTurnBlockedByStateOnlyCallback_doesNotSendBlockedInput() {
// The guard blocks "blocked input" without replying: it writes state and ends the invocation.
RemoteA2AAgent agent =
getAgentBuilder()
.beforeAgentCallback(
ImmutableList.<Callbacks.BeforeAgentCallback>of(
(CallbackContext callbackContext) -> {
boolean blocked =
callbackContext.userContent().flatMap(Content::parts).stream()
.flatMap(List::stream)
.anyMatch(part -> part.text().orElse("").equals("blocked input"));
if (blocked) {
callbackContext.state().put("blocked", true);
callbackContext.invocationContext().setEndInvocation(true);
}
return Maybe.empty();
}))
.build();
InMemoryRunner runner = new InMemoryRunner(agent);
Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet();
mockStreamResponse(consumer -> consumer.accept(createFinalEvent("ok"), agentCard));

for (String text : ImmutableList.of("first question", "blocked input", "next question")) {
var unused =
runner
.runAsync("user", session.id(), Content.fromParts(Part.fromText(text)))
.toList()
.blockingGet();
}

ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockClient, times(2))
.sendMessage(messageCaptor.capture(), any(List.class), any(Consumer.class), any());
Message last = messageCaptor.getAllValues().get(1);
assertThat(
last.getParts().stream()
.map(part -> ((TextPart) part).getText())
.collect(ImmutableList.toImmutableList()))
.containsExactly("next question");
}

@Test
public void runAsync_handlesClientError() {
RemoteA2AAgent agent = createAgent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.adk.a2a.converters;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;

import com.google.adk.agents.BaseAgent;
Expand All @@ -28,6 +29,7 @@
import com.google.common.collect.Iterables;
import com.google.genai.types.Content;
import com.google.genai.types.CustomMetadata;
import com.google.genai.types.FinishReason;
import com.google.genai.types.FunctionCall;
import com.google.genai.types.FunctionResponse;
import com.google.genai.types.Part;
Expand Down Expand Up @@ -382,6 +384,153 @@ public void answerParts_dropsCallWithAuthConfigArgument() {
assertThat(((TextPart) Iterables.getOnlyElement(parts)).getText()).isEqualTo("hi");
}

@Test
public void messagePartsFromContext_afterStateEventOfThisInvocation_sendsHistoryBeforeIt() {
// A before-agent callback of this invocation that only updated state.
Event stateOnly = Event.builder().author("test_agent").invocationId("current").build();

ImmutableList<String> texts =
sentTexts(
event("user", Part.fromText("hello")),
event("test_agent", Part.fromText("hi")),
event("user", Part.fromText("how are you?")),
stateOnly);

assertThat(texts).containsExactly("how are you?");
}

@Test
public void messagePartsFromContext_afterStateEventOfEarlierInvocation_startsAfterIt() {
// A before-agent callback may have blocked that turn, so its input is not sent again.
Event stateOnly = Event.builder().author("test_agent").invocationId("earlier").build();

ImmutableList<String> texts =
sentTexts(
event("user", Part.fromText("blocked input")),
stateOnly,
event("user", Part.fromText("next question")));

assertThat(texts).containsExactly("next question");
}

@Test
public void messagePartsFromContext_afterContextIdOnlyEventOfThisInvocation_startsAfterIt() {
// An event that kept the context ID shows the remote agent has the turn before it.
Event contextIdOnly =
Event.builder()
.author("test_agent")
.invocationId("current")
.customMetadata(ImmutableList.of(metadata("a2a:context_id", "context-1")))
.build();

ImmutableList<String> texts =
sentTexts(
event("user", Part.fromText("hello")),
contextIdOnly,
event("user", Part.fromText("how are you?")));

assertThat(texts).containsExactly("how are you?");
}

@Test
public void messagePartsFromContext_afterResponseOnlyEventOfThisInvocation_startsAfterIt() {
// A remote response with no content and no context ID is still a response.
Event emptyResponse =
Event.builder()
.author("test_agent")
.invocationId("current")
.customMetadata(ImmutableList.of(metadata("a2a:response", "{}")))
.build();

ImmutableList<String> texts =
sentTexts(
event("user", Part.fromText("hello")),
emptyResponse,
event("user", Part.fromText("how are you?")));

assertThat(texts).containsExactly("how are you?");
}

@Test
public void isEmptyEventOfInvocation_withEmptyContentOfThisInvocation_returnsTrue() {
Event emptyContent =
Event.builder()
.author("test_agent")
.invocationId("current")
.content(Content.builder().build())
.build();

assertThat(EventConverter.isEmptyEventOfInvocation(emptyContent, "test_agent", "current"))
.isTrue();
}

@Test
public void isEmptyEventOfInvocation_withAnotherAuthor_returnsFalse() {
Event userEvent = Event.builder().author("user").invocationId("current").build();

assertThat(EventConverter.isEmptyEventOfInvocation(userEvent, "test_agent", "current"))
.isFalse();
}

@Test
public void isEmptyEventOfInvocation_withError_returnsFalse() {
Event error =
Event.builder()
.author("test_agent")
.invocationId("current")
.errorMessage("Failed to communicate with the remote agent")
.build();

assertThat(EventConverter.isEmptyEventOfInvocation(error, "test_agent", "current")).isFalse();
}

@Test
public void isEmptyEventOfInvocation_withErrorCodeOnly_returnsFalse() {
Event error =
Event.builder()
.author("test_agent")
.invocationId("current")
.errorCode(new FinishReason(FinishReason.Known.SAFETY))
.build();

assertThat(EventConverter.isEmptyEventOfInvocation(error, "test_agent", "current")).isFalse();
}

@Test
public void isEmptyEventOfInvocation_withoutAuthor_returnsFalse() {
Event noAuthor = Event.builder().invocationId("current").build();

assertThat(EventConverter.isEmptyEventOfInvocation(noAuthor, "test_agent", "current"))
.isFalse();
}

@Test
public void messagePartsFromContext_afterCallbackReply_startsAfterIt() {
// A reply written by a callback has content, so it still ends the history.
ImmutableList<String> texts =
sentTexts(
event("user", Part.fromText("blocked input")),
event("test_agent", Part.fromText("Request withheld.")).toBuilder()
.invocationId("current")
.build(),
event("user", Part.fromText("next question")));

assertThat(texts).containsExactly("next question");
}

private static ImmutableList<String> sentTexts(Event... events) {
InvocationContext ctx =
InvocationContext.builder()
.session(Session.builder("session1").events(ImmutableList.copyOf(events)).build())
.sessionService(new InMemorySessionService())
.agent(new TestAgent())
.invocationId("current")
.build();
return EventConverter.messagePartsFromContext(ctx).stream()
.map(part -> ((TextPart) part).getText())
.collect(toImmutableList());
}

private static final class TestAgent extends BaseAgent {
TestAgent() {
super("test_agent", "test", ImmutableList.of(), null, null);
Expand Down
Loading