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
22 changes: 22 additions & 0 deletions core/src/main/java/com/google/adk/agents/LlmAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -143,6 +144,7 @@ public enum IncludeContents {
private final Optional<String> outputKey;
private final Optional<BaseCodeExecutor> codeExecutor;
private final Optional<AgentMode> mode;
private final NodeConfig nodeConfig;

private volatile Model resolvedModel;
private final BaseLlmFlow llmFlow;
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -243,6 +246,7 @@ public static class Builder extends BaseAgent.Builder<Builder> {
private String outputKey;
private BaseCodeExecutor codeExecutor;
private AgentMode mode;
private NodeConfig nodeConfig;

@CanIgnoreReturnValue
public Builder model(String model) {
Expand Down Expand Up @@ -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 <B, A> @Nullable ImmutableList<A> convertCallbacks(
@Nullable List<? extends B> callbacks, Function<B, A> converter, String callbackType) {
return Optional.ofNullable(callbacks)
Expand Down Expand Up @@ -2064,6 +2080,12 @@ public Optional<Schema> 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.
Expand Down
29 changes: 29 additions & 0 deletions core/src/test/java/com/google/adk/agents/LlmAgentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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());
}
}
180 changes: 150 additions & 30 deletions core/src/test/java/com/google/adk/workflow/LlmAgentAsNodeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Event> 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<Event> 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<Event> 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<Event> events = session.turn(go());

assertThat(calls.get()).isEqualTo(2);
assertThat(replyInput(events)).isEqualTo("recovered");
}

@Test
public void runAsync_resumableAppRetriesATimedOutWorkflow_callsItsAgentsModelAgain() {
TestLlm model = modelCallingLookupUntilAnswered();
Expand Down Expand Up @@ -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());
Expand All @@ -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());
Expand All @@ -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()
Expand All @@ -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(
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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(
Expand All @@ -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")));
Expand Down
Loading