From 6fb1ecc5e06cf9cbe5954acbd44fa99009b61b41 Mon Sep 17 00:00:00 2001 From: Damian Momot Date: Wed, 2 Dec 2026 04:22:10 -0800 Subject: [PATCH] feat(workflow): let LlmAgent nodes set a retry policy and timeout PiperOrigin-RevId: 1034339612 --- .../java/com/google/adk/agents/LlmAgent.java | 22 +++ .../com/google/adk/agents/LlmAgentTest.java | 29 +++ .../adk/workflow/LlmAgentAsNodeTest.java | 180 +++++++++++++++--- 3 files changed, 201 insertions(+), 30 deletions(-) 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 69ec08c8ea..4139559740 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -61,6 +61,7 @@ import com.google.adk.sessions.StateSchemaException; import com.google.adk.tools.BaseTool; import com.google.adk.tools.BaseToolset; +import com.google.adk.workflow.NodeConfig; import com.google.adk.workflow.NodeExecutionState; import com.google.adk.workflow.NodeInfo; import com.google.adk.workflow.RunNodeConfig; @@ -143,6 +144,7 @@ public enum IncludeContents { private final Optional outputKey; private final Optional codeExecutor; private final Optional mode; + private final NodeConfig nodeConfig; private volatile Model resolvedModel; private final BaseLlmFlow llmFlow; @@ -198,6 +200,7 @@ protected LlmAgent(Builder builder) { this.toolsets = extractToolsets(this.toolsUnion); this.codeExecutor = Optional.ofNullable(builder.codeExecutor); this.mode = Optional.ofNullable(builder.mode); + this.nodeConfig = requireNonNullElse(builder.nodeConfig, NodeConfig.builder().build()); this.llmFlow = determineLlmFlow(); @@ -243,6 +246,7 @@ public static class Builder extends BaseAgent.Builder { private String outputKey; private BaseCodeExecutor codeExecutor; private AgentMode mode; + private NodeConfig nodeConfig; @CanIgnoreReturnValue public Builder model(String model) { @@ -631,6 +635,18 @@ public Builder mode(AgentMode mode) { return this; } + /** + * Sets the retry policy and per-attempt timeout this agent uses when it runs as a workflow + * node. This config has no effect when the agent does not run as a node, such as under {@link + * com.google.adk.apps.App.Builder#rootAgent} or in a live run. + */ + @CanIgnoreReturnValue + @Experimental + public Builder nodeConfig(NodeConfig nodeConfig) { + this.nodeConfig = nodeConfig; + return this; + } + private static @Nullable ImmutableList convertCallbacks( @Nullable List callbacks, Function converter, String callbackType) { return Optional.ofNullable(callbacks) @@ -2064,6 +2080,12 @@ public Optional outputSchema() { return outputSchema; } + /** Returns the retry policy and per-attempt timeout this agent uses as a workflow node. */ + @Override + public NodeConfig config() { + return nodeConfig; + } + /** * Returns {@code true}, so that a workflow resuming this agent as a node runs it again and its * model sees the answers to its long-running calls. 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 f1540c16e8..e750b80729 100644 --- a/core/src/test/java/com/google/adk/agents/LlmAgentTest.java +++ b/core/src/test/java/com/google/adk/agents/LlmAgentTest.java @@ -54,6 +54,8 @@ import com.google.adk.tools.BaseTool; import com.google.adk.tools.BaseToolset; import com.google.adk.tools.ExampleTool; +import com.google.adk.workflow.NodeConfig; +import com.google.adk.workflow.RetryConfig; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -71,6 +73,7 @@ import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; +import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -1128,4 +1131,30 @@ public void runAsync_resumeFromTransferToPeer_runsTransferredPeerAgent() { assertThat(simplifyEvents(events)).contains("agent_b: agent B response"); assertThat(simplifyEvents(events)).doesNotContain("agent_a: agent A should not re-run"); } + + @Test + public void builder_nodeConfig_isTheAgentsNodeConfig() { + NodeConfig nodeConfig = + NodeConfig.builder() + .retryConfig(RetryConfig.builder().maxAttempts(3).build()) + .timeout(Duration.ofSeconds(5)) + .build(); + + LlmAgent agent = + LlmAgent.builder() + .name("agent") + .model(createTestLlm(createTextLlmResponse("hi"))) + .nodeConfig(nodeConfig) + .build(); + + assertThat(agent.config()).isEqualTo(nodeConfig); + } + + @Test + public void builder_noNodeConfig_usesTheDefault() { + LlmAgent agent = + LlmAgent.builder().name("agent").model(createTestLlm(createTextLlmResponse("hi"))).build(); + + assertThat(agent.config()).isEqualTo(NodeConfig.builder().build()); + } } 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 49a32469f1..74e038ba00 100644 --- a/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java +++ b/core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java @@ -784,6 +784,116 @@ public void runAsync_resumableAppRetriesAWorkflowWhoseAgentsToolFailed_callsTheM assertThat(events.stream().map(Event::stringifyContent)).contains("found it"); } + @Test + public void runAsync_singleTurnAgentWithANodeConfig_retriesItsFailedModelCall() { + TestLlm model = failingOnceThenAnswering(createTextLlmResponse("recovered")); + LlmAgent worker = + LlmAgent.builder() + .name("worker") + .model(model) + .mode(AgentMode.SINGLE_TURN) + .nodeConfig(retrying(2)) + .build(); + WorkflowSession session = + new WorkflowSession( + Workflow.builder() + .name("wf") + .edges(new Edge(Start.INSTANCE, worker), new Edge(worker, captureInput("reply"))) + .build()); + + ImmutableList events = session.turn(go()); + + assertThat(model.getRequests()).hasSize(2); + assertThat(replyInput(events)).isEqualTo("recovered"); + } + + @Test + public void runAsync_taskAgentWithANodeConfig_retriesItsFailedModelCall() { + TestLlm model = + failingOnceThenAnswering( + createFunctionCallLlmResponse( + "finish_1", "finish_task", ImmutableMap.of("result", "memo"))); + LlmAgent task = + LlmAgent.builder() + .name("task") + .model(model) + .mode(AgentMode.TASK) + .nodeConfig(retrying(2)) + .build(); + WorkflowSession session = new WorkflowSession(chain(task, captureInput("after"))); + + ImmutableList events = session.turn(go()); + + assertThat(model.getRequests()).hasSize(2); + assertThat(outputEventAt(events, "wf@1/after@1").output()) + .hasValue(ImmutableMap.of("received", ImmutableMap.of("result", "memo"))); + } + + @Test + public void runAsync_chatAgentWithANodeConfig_retriesItsFailedModelCall() { + TestLlm model = failingOnceThenAnswering(createTextLlmResponse("Hi there.")); + LlmAgent chat = + LlmAgent.builder() + .name("chat") + .model(model) + .mode(AgentMode.CHAT) + .nodeConfig(retrying(2)) + .build(); + WorkflowSession session = + new WorkflowSession( + Workflow.builder().name("wf").edges(new Edge(Start.INSTANCE, chat)).build()); + + ImmutableList events = session.turn(go()); + + assertThat(model.getRequests()).hasSize(2); + assertThat(events.stream().map(Event::stringifyContent)).contains("Hi there."); + } + + @Test + public void runAsync_agentOverrunningItsNodeTimeout_failsNamingTheAgent() { + TestLlm model = new TestLlm(Flowable::never); + LlmAgent worker = + LlmAgent.builder() + .name("worker") + .model(model) + .nodeConfig(NodeConfig.builder().timeout(Duration.ofMillis(100)).build()) + .build(); + Workflow workflow = + Workflow.builder().name("wf").edges(new Edge(Start.INSTANCE, worker)).build(); + + var thrown = assertThrows(NodeTimeoutException.class, () -> run(workflow, "go")); + + assertThat(thrown.nodeName()).isEqualTo("worker"); + } + + @Test + public void runAsync_agentTimingOutWithANodeConfigRetry_runsAgainAndHandsItsAnswerOn() { + AtomicInteger calls = new AtomicInteger(); + TestLlm model = + new TestLlm(() -> + calls.incrementAndGet() == 1 + ? Flowable.never() + : Flowable.just(createTextLlmResponse("recovered"))); + LlmAgent worker = + LlmAgent.builder() + .name("worker") + .model(model) + .mode(AgentMode.SINGLE_TURN) + .nodeConfig(retryingOnTimeout()) + .build(); + WorkflowSession session = + new WorkflowSession( + Workflow.builder() + .name("wf") + .edges(new Edge(Start.INSTANCE, worker), new Edge(worker, captureInput("reply"))) + .build()); + + ImmutableList events = session.turn(go()); + + assertThat(calls.get()).isEqualTo(2); + assertThat(replyInput(events)).isEqualTo("recovered"); + } + @Test public void runAsync_resumableAppRetriesATimedOutWorkflow_callsItsAgentsModelAgain() { TestLlm model = modelCallingLookupUntilAnswered(); @@ -854,8 +964,12 @@ public void runAsync_retriedFanOutWithTheFailedCallLastOnItsBranch_runsTheCallAg public void runAsync_resumableAppRetriesAnAgentWhoseToolFailed_callsTheModelAgain() { TestLlm model = modelCallingLookupUntilAnswered(); LlmAgent worker = - withNodeConfig( - LlmAgent.builder().name("worker").model(model).tools(failsOnce()), retrying(2)); + LlmAgent.builder() + .name("worker") + .model(model) + .tools(failsOnce()) + .nodeConfig(retrying(2)) + .build(); WorkflowSession session = new WorkflowSession( Workflow.builder().name("wf").edges(new Edge(Start.INSTANCE, worker)).build()); @@ -870,9 +984,12 @@ public void runAsync_resumableAppRetriesAnAgentWhoseToolFailed_callsTheModelAgai public void runAsync_resumableAppRetriesAnAgentWhoseToolTimedOut_callsTheModelAgain() { TestLlm model = modelCallingLookupUntilAnswered(); LlmAgent worker = - withNodeConfig( - LlmAgent.builder().name("worker").model(model).tools(stallsOnce()), - retryingOnTimeout()); + LlmAgent.builder() + .name("worker") + .model(model) + .tools(stallsOnce()) + .nodeConfig(retryingOnTimeout()) + .build(); WorkflowSession session = new WorkflowSession( Workflow.builder().name("wf").edges(new Edge(Start.INSTANCE, worker)).build()); @@ -886,13 +1003,13 @@ public void runAsync_resumableAppRetriesAnAgentWhoseToolTimedOut_callsTheModelAg @Test public void runAsync_resumableAppRetriesASingleTurnAgentWhoseToolFailed_outputsItsAnswer() { LlmAgent worker = - withNodeConfig( - LlmAgent.builder() - .name("worker") - .model(modelCallingLookupUntilAnswered()) - .mode(AgentMode.SINGLE_TURN) - .tools(failsOnce()), - retrying(2)); + LlmAgent.builder() + .name("worker") + .model(modelCallingLookupUntilAnswered()) + .mode(AgentMode.SINGLE_TURN) + .tools(failsOnce()) + .nodeConfig(retrying(2)) + .build(); WorkflowSession session = new WorkflowSession( Workflow.builder() @@ -913,8 +1030,12 @@ public void runAsync_loopBackToAnAgentWhoseEarlierRunRetried_callsTheModelAgain( createTextLlmResponse("draft"), createTextLlmResponse("final")); LlmAgent worker = - withNodeConfig( - LlmAgent.builder().name("worker").model(model).tools(failsOnce()), retrying(2)); + LlmAgent.builder() + .name("worker") + .model(model) + .tools(failsOnce()) + .nodeConfig(retrying(2)) + .build(); AtomicInteger reviews = new AtomicInteger(); Node review = new TestNode( @@ -960,12 +1081,12 @@ public void runAsync_retryOfAnAgentWhoseFailedAttemptAskedForApproval_doesNotCal TestLlm firstModel = TestLlm.create(createLlmResponse(approveAndLookUp), createTextLlmResponse("first done")); LlmAgent first = - withNodeConfig( - LlmAgent.builder() - .name("first") - .model(firstModel) - .tools(pendingFunctionTool(), failsOnce()), - retrying(2)); + LlmAgent.builder() + .name("first") + .model(firstModel) + .tools(pendingFunctionTool(), failsOnce()) + .nodeConfig(retrying(2)) + .build(); TestLlm secondModel = TestLlm.create(createTextLlmResponse("second done")); LlmAgent second = LlmAgent.builder().name("second").model(secondModel).build(); WorkflowSession session = @@ -1817,6 +1938,15 @@ private static Event nodeEvent(String author, String path, Content content) { .build(); } + /** Returns a model that fails like an unavailable backend on its first call, then answers. */ + private static TestLlm failingOnceThenAnswering(LlmResponse answer) { + AtomicInteger calls = new AtomicInteger(); + return new TestLlm(() -> + calls.incrementAndGet() == 1 + ? Flowable.error(new IllegalStateException("unavailable")) + : Flowable.just(answer)); + } + /** Returns a model that calls {@code lookup}, calls it again, then answers "found it". */ private static TestLlm modelCallingLookupUntilAnswered() { return TestLlm.create( @@ -1830,16 +1960,6 @@ private static NodeConfig retryingOnTimeout() { return retrying(2).toBuilder().timeout(Duration.ofMillis(300)).build(); } - /** Returns the agent that {@code builder} builds, as a node with {@code config}. */ - private static LlmAgent withNodeConfig(LlmAgent.Builder builder, NodeConfig config) { - return new LlmAgent(builder) { - @Override - public NodeConfig config() { - return config; - } - }; - } - /** Returns a {@code lookup} tool whose first call fails, as a flaky backend's does. */ private static BaseTool failsOnce() { return new FlakyLookupTool(Single.error(new IllegalStateException("backend down")));