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
70 changes: 42 additions & 28 deletions a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -568,35 +568,34 @@ synchronized void handleEvent(ClientEvent clientEvent, AgentCard unused) {
* surrounding aggregation bookkeeping is ADK's own; none of it throws on peer input today.
*/
private void emit(ClientEvent clientEvent, Optional<Event> eventOpt) {
eventOpt.ifPresent(
event -> {
addMetadata(event, clientEvent);

if (isCompleted(clientEvent)) {
// Terminal event, check if we can merge.
boolean mergeResult = mergeAggregatedContentIntoEvent(event);
if (!mergeResult) {
emitAggregatedEventAndClearBuffer(null);
}
} else {
boolean isPartial = event.partial().orElse(false);
if (isPartial) {
if (shouldResetBuffer(clientEvent)) {
clearBuffer();
}
boolean addedToBuffer = bufferContent(event, clientEvent);
if (!addedToBuffer) {
// Partial event with no content to buffer (e.g. tool call).
// Flush buffer before emitting this event.
emitAggregatedEventAndClearBuffer(null);
}
} else {
// Intermediate non-partial.
emitAggregatedEventAndClearBuffer(null);
}
eventOpt.ifPresent(event -> {
addMetadata(event, clientEvent);

if (isCompleted(clientEvent)) {
// Terminal event, check if we can merge.
boolean mergeResult = mergeAggregatedContentIntoEvent(event);
if (!mergeResult) {
emitAggregatedEventAndClearBuffer(null);
}
} else if (!isMidStreamEmptyUpdate(clientEvent, event)) {
boolean isPartial = event.partial().orElse(false);
if (isPartial) {
if (shouldResetBuffer(clientEvent)) {
clearBuffer();
}
boolean addedToBuffer = bufferContent(event, clientEvent);
if (!addedToBuffer) {
// Partial event with no content to buffer (e.g. tool call).
// Flush buffer before emitting this event.
emitAggregatedEventAndClearBuffer(null);
}
emitter.onNext(event);
});
} else {
// Intermediate non-partial.
emitAggregatedEventAndClearBuffer(null);
}
}
emitter.onNext(event);
});

// Wait until the client receives a status payload marking the completion of the task
// regardless of the underlying streaming or non-streaming protocol configuration.
Expand Down Expand Up @@ -791,6 +790,21 @@ private Event createAggregatedEvent(Content content, @Nullable ClientEvent trigg
}
}

/**
* Returns whether {@code event}, converted from {@code clientEvent}, is a task update without
* content that neither ends the turn nor is an artifact's last chunk, such as an error code alone
* in the middle of a stream. It leaves the streamed text alone, as in ADK Kotlin.
*/
private static boolean isMidStreamEmptyUpdate(ClientEvent clientEvent, Event event) {
if (!(clientEvent instanceof TaskUpdateEvent updateEvent)
|| event.content().isPresent()
|| event.turnComplete().orElse(false)) {
return false;
}
return !(updateEvent.getUpdateEvent() instanceof TaskArtifactUpdateEvent artifactEvent
&& Objects.equals(artifactEvent.isLastChunk(), true));
}

private static boolean isCompleted(ClientEvent event) {
TaskState state;
if (event instanceof TaskEvent taskEvent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,11 @@ private ResponseConverter() {}

/**
* Converts a A2A {@link ClientEvent} to an ADK {@link Event}, based on the event type. Returns an
* empty optional if the event should be ignored: a TaskArtifactUpdateEvent that is not a final
* update, a TaskStatusUpdateEvent with an empty message or none of whose parts convert and that
* does not end the turn, or a message none of whose parts convert and that reports no error code.
* empty optional if the event should be ignored: a last artifact chunk marked partial, an
* artifact update none of whose parts convert, a status update with no message or none of whose
* parts convert that does not end the turn, or a message none of whose parts convert. An artifact
* or status message with an error code is kept with no content, and a message with one with empty
* content.
*
* @throws IllegalArgumentException if the event type is not supported.
*/
Expand Down Expand Up @@ -133,10 +135,10 @@ private static boolean isLongRunning(@Nullable Map<String, Object> metadata) {
}

/**
* Converts a A2A {@link TaskUpdateEvent} to an ADK {@link Event}, if applicable. Returns empty if
* the event is not a final update for TaskArtifactUpdateEvent, if the message is empty for
* TaskStatusUpdateEvent, or if no part could be converted from the message of a status update
* that does not end the turn.
* Converts a A2A {@link TaskUpdateEvent} to an ADK {@link Event}, if applicable. Returns empty
* for a last artifact chunk marked partial, and for an artifact update none of whose parts
* convert, or a status update with no message or none of whose parts convert that does not end
* the turn, unless the artifact or status message has an error code.
*
* @throws IllegalArgumentException if the task update type is not supported.
*/
Expand All @@ -153,14 +155,20 @@ private static Optional<Event> handleTaskUpdate(
}

Event eventPart = artifactToEvent(artifactEvent.getArtifact(), context, converter);
if (!hasParts(eventPart)) {
return Optional.empty();
boolean hasContent = hasParts(eventPart);
if (!hasContent) {
// With no convertible part, still emit the artifact's error code, as ADK Python does.
if (errorCode(artifactEvent.getArtifact().metadata()) == null) {
return Optional.empty();
}
eventPart.setContent(null);
}
eventPart.setPartial(isAppend || !isLastChunk);
eventPart.setPartial((hasContent && isAppend) || !isLastChunk);
// append=true, lastChunk=false: emit as partial, update aggregation
// append=false, lastChunk=false: emit as partial, reset aggregation
// append=true, lastChunk=true: emit as partial, update aggregation and emit as non-partial
// append=false, lastChunk=true: emit as non-partial, drop aggregation
// no content, lastChunk=true: emit as non-partial
return Optional.of(
updateEventMetadata(
eventPart,
Expand All @@ -183,7 +191,17 @@ private static Optional<Event> handleTaskUpdate(
return messageToEvent(
value, context, PENDING_STATES.contains(taskState), converter);
})
.filter(converted -> taskState == TaskState.FAILED || hasParts(converted));
// With no convertible part, still emit the message's error code, as ADK Python does.
.filter(converted ->
taskState == TaskState.FAILED
|| hasParts(converted)
|| errorCode(statusMessage.getMetadata()) != null)
.map(converted -> {
if (!hasParts(converted)) {
converted.setContent(null);
}
return converted;
});

if (statusEvent.isFinal()
|| taskState == TaskState.INPUT_REQUIRED
Expand Down Expand Up @@ -551,7 +569,10 @@ private static Event updateEventMetadata(
* JSON string is decoded first, and other text, such as a number Go sends, is the error code
* itself.
*/
private static @Nullable FinishReason errorCode(Map<String, Object> clientMetadata) {
private static @Nullable FinishReason errorCode(@Nullable Map<String, Object> clientMetadata) {
if (clientMetadata == null) {
return null;
}
if (!(clientMetadata.get(A2AMetadataKey.ERROR_CODE.getType()) instanceof String value)) {
return parseMetadata(clientMetadata, A2AMetadataKey.ERROR_CODE, FinishReason.class);
}
Expand Down
198 changes: 198 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 @@ -1853,6 +1853,204 @@ public void runAsync_streamedStatusWithErrorCodeOnMessage_emitsAndStoresIt() {
assertErrorCodeEmittedAndStored(createAgent());
}

@Test
public void runAsync_streamedErrorOnlyUpdates_keepStreamedTextInOneEvent() {
TaskStatus completed = new TaskStatus(TaskState.COMPLETED);
mockStreamResponse(consumer -> {
consumer.accept(createPartialEvent("Hello ", true, false), agentCard);
consumer.accept(
createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ false), agentCard);
consumer.accept(
createErrorOnlyChunk("SPII", /* append= */ false, /* lastChunk= */ false), agentCard);
consumer.accept(createErrorOnlyStatusUpdate("RECITATION"), agentCard);
consumer.accept(createPartialEvent("world", true, false), agentCard);
consumer.accept(
createErrorOnlyChunk("BLOCKLIST", /* append= */ true, /* lastChunk= */ true), agentCard);
consumer.accept(
new TaskUpdateEvent(
new Task.Builder().id("task-1").contextId("context-1").status(completed).build(),
new TaskStatusUpdateEvent("task-1", completed, "context-1", true, null)),
agentCard);
});
InMemoryRunner runner = new InMemoryRunner(createAgent());
Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet();

List<Event> events =
runner
.runAsync("user", session.id(), Content.fromParts(Part.fromText("Hi")))
.toList()
.blockingGet();

assertThat(errorCodes(events))
.containsExactly(
new FinishReason("SAFETY"),
new FinishReason("SPII"),
new FinishReason("RECITATION"),
new FinishReason("BLOCKLIST"))
.inOrder();
ImmutableList<Event> stored =
runner
.sessionService()
.getSession(runner.appName(), "user", session.id(), Optional.empty())
.blockingGet()
.immutableEvents()
.stream()
.filter(event -> event.author().equals("remote-agent"))
.collect(ImmutableList.toImmutableList());
// The mid-stream chunks are partial, and partial events are not stored. The streamed text is
// stored as one event before the last chunk's error.
assertThat(storedSummary(stored))
.containsExactly("error=RECITATION", "text=Hello world", "error=BLOCKLIST")
.inOrder();
}

@Test
public void runAsync_errorOnlyLastChunkThenNewArtifact_keepsBothTextsInOrder() {
mockStreamResponse(consumer -> {
consumer.accept(createPartialEvent("Hello ", true, false), agentCard);
consumer.accept(
createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ true), agentCard);
consumer.accept(createPartialEvent("Bye", false, false), agentCard);
consumer.accept(completedStatusUpdate(), agentCard);
});

assertThat(storedSummary(runStoringEvents()))
.containsExactly("text=Hello ", "error=SAFETY", "text=Bye")
.inOrder();
}

@Test
public void runAsync_errorOnlyLastChunkThenCompleted_storesTextBeforeError() {
mockStreamResponse(consumer -> {
consumer.accept(createPartialEvent("Hello ", true, false), agentCard);
consumer.accept(
createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ true), agentCard);
consumer.accept(completedStatusUpdate(), agentCard);
});

assertThat(storedSummary(runStoringEvents()))
.containsExactly("text=Hello ", "error=SAFETY")
.inOrder();
}

@Test
@SuppressWarnings("unchecked") // cast for Mockito
public void runAsync_finalUpdateOnWorkingTask_storesTextBeforeIt() {
TaskStatus working = new TaskStatus(TaskState.WORKING);
doAnswer(
invocation -> {
List<BiConsumer<ClientEvent, AgentCard>> consumers = invocation.getArgument(1);
Consumer<Throwable> errorConsumer = invocation.getArgument(2);
consumers.get(0).accept(createPartialEvent("Hello ", true, false), agentCard);
consumers
.get(0)
.accept(
new TaskUpdateEvent(
new Task.Builder()
.id("task-1")
.contextId("context-1")
.status(working)
.build(),
new TaskStatusUpdateEvent("task-1", working, "context-1", true, null)),
agentCard);
// The a2a client signals the end of the stream with a null error.
errorConsumer.accept(null);
return null;
})
.when(mockClient)
.sendMessage(any(Message.class), any(List.class), any(Consumer.class), any());

ImmutableList<Event> stored = runStoringEvents();

// The update that ends the turn comes after the streamed text.
assertThat(stored.get(0).stringifyContent()).isEqualTo("Hello ");
assertThat(stored.get(1).turnComplete()).hasValue(true);
}

private static ClientEvent completedStatusUpdate() {
TaskStatus completed = new TaskStatus(TaskState.COMPLETED);
return new TaskUpdateEvent(
new Task.Builder().id("task-1").contextId("context-1").status(completed).build(),
new TaskStatusUpdateEvent("task-1", completed, "context-1", true, null));
}

/** Runs the agent once through an {@link InMemoryRunner}; returns the events it stored. */
private ImmutableList<Event> runStoringEvents() {
InMemoryRunner runner = new InMemoryRunner(createAgent());
Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet();
var unused =
runner
.runAsync("user", session.id(), Content.fromParts(Part.fromText("Hi")))
.toList()
.blockingGet();
return runner
.sessionService()
.getSession(runner.appName(), "user", session.id(), Optional.empty())
.blockingGet()
.immutableEvents()
.stream()
.filter(event -> event.author().equals("remote-agent"))
.collect(ImmutableList.toImmutableList());
}

/** Returns each stored event's text and error code, in order. */
private static ImmutableList<String> storedSummary(List<Event> stored) {
ImmutableList.Builder<String> summary = ImmutableList.builder();
for (Event event : stored) {
String text = event.stringifyContent();
if (!text.isEmpty()) {
summary.add("text=" + text);
}
event.errorCode().ifPresent(code -> summary.add("error=" + code.toString()));
}
return summary.build();
}

/** An artifact chunk whose only part does not convert, carrying {@code errorCode}. */
private static ClientEvent createErrorOnlyChunk(
String errorCode, boolean append, boolean lastChunk) {
Artifact artifact =
new Artifact.Builder()
.artifactId("artifact-1")
.parts(
ImmutableList.of(new FilePart(new FileWithBytes("text/plain", "bad.txt", "!!!"))))
.metadata(ImmutableMap.of("adk_error_code", errorCode))
.build();
Task task =
new Task.Builder()
.id("task-1")
.contextId("context-1")
.status(new TaskStatus(TaskState.WORKING))
.build();
TaskArtifactUpdateEvent update =
new TaskArtifactUpdateEvent.Builder()
.append(append)
.lastChunk(lastChunk)
.contextId("context-1")
.artifact(artifact)
.taskId("task-1")
.build();
return new TaskUpdateEvent(task, update);
}

/** A working task's status update whose message's only part does not convert. */
private static ClientEvent createErrorOnlyStatusUpdate(String errorCode) {
TaskStatus working =
new TaskStatus(
TaskState.WORKING,
new Message.Builder()
.role(Message.Role.AGENT)
.parts(
ImmutableList.of(
new FilePart(new FileWithBytes("text/plain", "bad.txt", "!!!"))))
.metadata(ImmutableMap.of("adk_error_code", errorCode))
.build(),
null);
return new TaskUpdateEvent(
new Task.Builder().id("task-1").contextId("context-1").status(working).build(),
new TaskStatusUpdateEvent("task-1", working, "context-1", false, null));
}

/** Runs {@code agent} once and checks that its event and the stored event carry SAFETY. */
private void assertErrorCodeEmittedAndStored(RemoteA2AAgent agent) {
InMemoryRunner runner = new InMemoryRunner(agent);
Expand Down
Loading
Loading