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
3 changes: 2 additions & 1 deletion core/src/main/java/com/google/adk/workflow/NodeInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public abstract class NodeInfo {

/**
* Returns {@code true} if this event's content is the node's output, so no separate output event
* follows.
* follows. On an event without content, it marks the output as a message, which a stored session
* holds as its JSON form.
*/
@JsonProperty("messageAsOutput")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
Expand Down
5 changes: 5 additions & 0 deletions core/src/main/java/com/google/adk/workflow/NodeRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.genai.types.Content;
import com.google.genai.types.FinishReason;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
Expand Down Expand Up @@ -770,6 +771,9 @@ private Event stamp(Event event) {
String author = nodeState.eventAuthor();
NodeInfo nodeInfo = event.nodeInfo().orElseGet(() -> NodeInfo.builder().build());
boolean carriesOutput = event.output().isPresent() || isMessageAsOutput(event);
// Marked, so that a stored session reads the output back as a message, not as a map.
boolean messageInOutput =
event.content().isEmpty() && event.output().orElse(null) instanceof Content;
return event.toBuilder()
.author(author.isEmpty() ? node.name() : author)
.invocationId(eventContext.invocationId())
Expand All @@ -779,6 +783,7 @@ private Event stamp(Event event) {
nodeInfo.toBuilder()
.path(nodeState.nodePath())
.outputFor(carriesOutput ? nodeState.outputFor() : nodeInfo.outputFor())
.messageAsOutput(nodeInfo.messageAsOutput() || messageInOutput)
.build())
.build();
}
Expand Down
54 changes: 46 additions & 8 deletions core/src/main/java/com/google/adk/workflow/ResumeScan.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
final class ResumeScan {

private static final String RESULT_KEY = "result";
private static final ImmutableSet<String> MESSAGE_KEYS = ImmutableSet.of("role", "parts");

private ResumeScan() {}

Expand Down Expand Up @@ -130,7 +131,9 @@ static Interception intercept(
Object output = recovered.output;
if (output != null || recovered.route != null || transfer != null) {
return Interception.replay(
output instanceof Content content ? processRehydratedOutput(node, content) : output,
recovered.outputFromContent && output instanceof Content content
? processRehydratedOutput(node, content, recovered.outputDelegated)
: output,
recovered.route,
branch,
transfer);
Expand Down Expand Up @@ -189,18 +192,23 @@ static Context replayContext(
}

/**
* Returns the output of a node whose content was its output: the content's text, read as JSON
* when the node has an output schema that does not accept a string, or as the enum value it
* quotes. Blank text is no output.
* Returns the output of a node whose content was its output: the content itself when the node has
* no output schema, is not an {@link LlmAgent} and gave the message itself rather than through a
* {@code delegated} child. Otherwise it is the content's text, read as JSON when the schema does
* not accept a string, or as the enum value it quotes, and blank text is no output.
*
* @throws IllegalArgumentException if the schema needs JSON and the text is not JSON
*/
static @Nullable Object processRehydratedOutput(Node node, Content content) {
static @Nullable Object processRehydratedOutput(Node node, Content content, boolean delegated) {
Optional<Schema> schema = node.outputSchema();
// An LlmAgent's output is its text, not the message, and a delegate may be an LlmAgent.
if (schema.isEmpty() && !delegated && !(node instanceof LlmAgent)) {
return content;
}
String text = MessageReader.textOf(content).trim();
if (text.isEmpty()) {
return null;
}
Optional<Schema> schema = node.outputSchema();
if (schema.isEmpty()) {
return text;
}
Expand Down Expand Up @@ -269,6 +277,13 @@ static Context replayContext(
*/
static final class RecoveredNode {
@Nullable Object output;

/** Whether {@link #output} is a message read from an event's content, not its output field. */
boolean outputFromContent;

/** Whether {@link #output} came from a descendant that delegated it to this node. */
boolean outputDelegated;

boolean failed;
@Nullable ImmutableList<Route> route;
@Nullable String branch;
Expand Down Expand Up @@ -484,8 +499,14 @@ private ImmutableMap<String, RecoveredNode> interruptsMatchingBranch(@Nullable S
private static void recordOutcome(
Event event, boolean isDirect, String ownerPath, RecoveredNode node) {
Object eventOutput = event.output().orElse(null);
if (eventOutput == null && event.nodeInfo().map(NodeInfo::messageAsOutput).orElse(false)) {
eventOutput = event.content().orElse(null);
boolean fromContent = false;
if (event.nodeInfo().map(NodeInfo::messageAsOutput).orElse(false)) {
if (eventOutput == null) {
eventOutput = event.content().orElse(null);
fromContent = eventOutput != null;
} else if (event.content().isEmpty()) {
eventOutput = asMessage(eventOutput);
}
}
boolean isDelegated =
eventOutput != null
Expand All @@ -495,6 +516,8 @@ private static void recordOutcome(
}
if (eventOutput != null) {
node.output = eventOutput;
node.outputFromContent = fromContent;
node.outputDelegated = !isDirect;
// A delegate's output event carries the delegate's branch, not this node's.
if (isDirect && event.output().isPresent()) {
node.branch = event.branch().orElse(null);
Expand All @@ -516,6 +539,21 @@ private static void recordOutcome(
}
}

/**
* Returns {@code value} converted to a message if it is a message's JSON form, which is how a
* stored session gives back a message output; returns any other value unchanged.
*/
private static Object asMessage(Object value) {
if (value instanceof Map<?, ?> map && MESSAGE_KEYS.containsAll(map.keySet())) {
try {
return JsonBaseModel.getMapper().convertValue(map, Content.class);
} catch (IllegalArgumentException e) {
return value;
}
}
return value;
}

/**
* Records the interrupts {@code event} raises for {@code node} (long-running calls and requests
* for input, together with their response schemas) and returns whether it raised any.
Expand Down
10 changes: 8 additions & 2 deletions core/src/main/java/com/google/adk/workflow/Scheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.genai.types.Content;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
Expand Down Expand Up @@ -347,7 +348,9 @@ private Completable checkpoint() {

/**
* On a resumable invocation, re-emits the output of a node replayed from history on the node's
* branch, without the paths that the output counts for.
* branch, without the paths that the output counts for. A replayed message is marked as one, so a
* later resume reads it back as a message; sent as content, it would appear twice in a later
* agent's history.
*/
private void reemitReplayedOutput(Context childContext) {
Optional<Object> output = childContext.requireNodeState().output();
Expand All @@ -359,7 +362,10 @@ private void reemitReplayedOutput(Context childContext) {
workflowEvent(childContext.invocationContext().branch().orElse(null))
.output(output.get())
.nodeInfo(
NodeInfo.builder().path(childContext.requireNodeState().nodePath()).build()));
NodeInfo.builder()
.path(childContext.requireNodeState().nodePath())
.messageAsOutput(output.get() instanceof Content)
.build()));
}

/** Returns the start of an event that the workflow itself emits on {@code branch}. */
Expand Down
87 changes: 81 additions & 6 deletions core/src/test/java/com/google/adk/workflow/ResumeScanTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,61 @@ public void scan_outputOnAnEventWithAnErrorCode_replaysTheOutput() {
assertThat(interception.output()).isEqualTo("cut short");
}

@Test
public void scan_messageInTheOutputFieldOfAStoredEvent_isReadBackAsTheMessage() {
Event resent =
nodeEvent("wf@1/chat@1")
.output(modelText("hi"))
.nodeInfo(NodeInfo.builder().path("wf@1/chat@1").messageAsOutput(true).build())
.build();
Event stored = Event.fromJson(resent.toJson());

RecoveredNode recovered =
ResumeScan.scan(ImmutableList.of(stored), "wf@1", "inv").get("chat@1");

assertThat(stored.output().orElseThrow()).isInstanceOf(Map.class);
assertThat(recovered.output).isEqualTo(modelText("hi"));
}

@Test
public void scan_eventMarkedAsAMessageWithAPlainOutput_keepsTheOutput() {
Event event =
nodeEvent("wf@1/chat@1")
.output("hi")
.nodeInfo(NodeInfo.builder().path("wf@1/chat@1").messageAsOutput(true).build())
.build();

RecoveredNode recovered = ResumeScan.scan(ImmutableList.of(event), "wf@1", "inv").get("chat@1");

assertThat(recovered.output).isEqualTo("hi");
}

@Test
public void scan_eventMarkedAsAMessageWithAMapOutput_keepsTheMap() {
Event event =
nodeEvent("wf@1/chat@1")
.output(ImmutableMap.of("v", 1))
.nodeInfo(NodeInfo.builder().path("wf@1/chat@1").messageAsOutput(true).build())
.build();

RecoveredNode recovered = ResumeScan.scan(ImmutableList.of(event), "wf@1", "inv").get("chat@1");

assertThat(recovered.output).isEqualTo(ImmutableMap.of("v", 1));
}

@Test
public void scan_eventMarkedAsAMessageWithAMapThatIsNotAMessage_keepsTheMap() {
Event event =
nodeEvent("wf@1/chat@1")
.output(ImmutableMap.of("parts", "x"))
.nodeInfo(NodeInfo.builder().path("wf@1/chat@1").messageAsOutput(true).build())
.build();

RecoveredNode recovered = ResumeScan.scan(ImmutableList.of(event), "wf@1", "inv").get("chat@1");

assertThat(recovered.output).isEqualTo(ImmutableMap.of("parts", "x"));
}

@Test
public void scan_partialEvent_isIgnored() {
ImmutableList<Event> events =
Expand Down Expand Up @@ -418,7 +473,9 @@ public void processRehydratedOutput_outputNoLongerFitsTheSchema_resumesUnvalidat

Object output =
ResumeScan.processRehydratedOutput(
new MessageOutputNode("chat", "", schema), modelText("{\"town\": \"Paris\"}"));
new MessageOutputNode("chat", "", schema),
modelText("{\"town\": \"Paris\"}"),
/* delegated= */ false);

assertThat(output).isEqualTo(ImmutableMap.of("town", "Paris"));
}
Expand All @@ -432,11 +489,11 @@ public void processRehydratedOutput_textThatIsNotJsonForAnObjectSchema_fails() {
IllegalArgumentException notJson =
assertThrows(
IllegalArgumentException.class,
() -> ResumeScan.processRehydratedOutput(node, notJsonText));
() -> ResumeScan.processRehydratedOutput(node, notJsonText, /* delegated= */ false));
IllegalArgumentException bareWord =
assertThrows(
IllegalArgumentException.class,
() -> ResumeScan.processRehydratedOutput(node, bareWordText));
() -> ResumeScan.processRehydratedOutput(node, bareWordText, /* delegated= */ false));

assertThat(notJson)
.hasMessageThat()
Expand All @@ -450,16 +507,31 @@ public void processRehydratedOutput_textThatIsNotJsonForAnObjectSchema_fails() {
public void processRehydratedOutput_blankText_isNoOutput() {
Object output =
ResumeScan.processRehydratedOutput(
new MessageOutputNode("chat", "", COUNT_SCHEMA), modelText(" "));
new MessageOutputNode("chat", "", COUNT_SCHEMA),
modelText(" "),
/* delegated= */ false);

assertThat(output).isNull();
}

@Test
public void processRehydratedOutput_blankTextWithoutSchema_keepsTheMessage() {
Content blank = modelText(" ");

Object output =
ResumeScan.processRehydratedOutput(
new MessageOutputNode("chat", "", /* schema= */ null), blank, /* delegated= */ false);

assertThat(output).isEqualTo(blank);
}

@Test
public void processRehydratedOutput_jsonNullForAnObjectSchema_isNoOutput() {
Object output =
ResumeScan.processRehydratedOutput(
new MessageOutputNode("chat", "", AGE_SCHEMA), modelText("null"));
new MessageOutputNode("chat", "", AGE_SCHEMA),
modelText("null"),
/* delegated= */ false);

assertThat(output).isNull();
}
Expand All @@ -468,7 +540,10 @@ public void processRehydratedOutput_jsonNullForAnObjectSchema_isNoOutput() {
public void processRehydratedOutput_stringSchema_keepsTheText() {
Node node = new MessageOutputNode("chat", "", Schema.builder().type(Type.Known.STRING).build());

assertThat(ResumeScan.processRehydratedOutput(node, modelText("42"))).isEqualTo("42");
Object output =
ResumeScan.processRehydratedOutput(node, modelText("42"), /* delegated= */ false);

assertThat(output).isEqualTo("42");
}

@Test
Expand Down
Loading
Loading