Skip to content

Commit f7e95c4

Browse files
google-genai-botcopybara-github
authored andcommitted
refactor: Marking InvocationContext settings as deprecated
- Updating a bunch of calls to InvocationContext that directly modify state to use the Builder instead. - Updating calls to InvocationContext constructors to use InvocationContext.buider() instead. PiperOrigin-RevId: 852935731
1 parent ee491ea commit f7e95c4

File tree

14 files changed

+202
-230
lines changed

14 files changed

+202
-230
lines changed

core/src/main/java/com/google/adk/agents/BaseAgent.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,13 @@ public Optional<List<? extends AfterAgentCallback>> afterAgentCallback() {
187187
* @return new context with updated branch name.
188188
*/
189189
private InvocationContext createInvocationContext(InvocationContext parentContext) {
190-
InvocationContext invocationContext = InvocationContext.copyOf(parentContext);
191-
invocationContext.agent(this);
190+
InvocationContext.Builder builder = parentContext.toBuilder();
191+
builder.agent(this);
192192
// Check for branch to be truthy (not None, not empty string),
193193
if (parentContext.branch().filter(s -> !s.isEmpty()).isPresent()) {
194-
invocationContext.branch(parentContext.branch().get() + "." + name());
194+
builder.branch(parentContext.branch().get() + "." + name());
195195
}
196-
return invocationContext;
196+
return builder.build();
197197
}
198198

199199
/**
@@ -303,17 +303,16 @@ private Single<Optional<Event>> callCallback(
303303
return maybeContent
304304
.map(
305305
content -> {
306-
Event.Builder eventBuilder =
306+
invocationContext.setEndInvocation(true);
307+
return Optional.of(
307308
Event.builder()
308309
.id(Event.generateEventId())
309310
.invocationId(invocationContext.invocationId())
310311
.author(name())
311312
.branch(invocationContext.branch())
312-
.actions(callbackContext.eventActions());
313-
314-
eventBuilder.content(Optional.of(content));
315-
invocationContext.setEndInvocation(true);
316-
return Optional.of(eventBuilder.build());
313+
.actions(callbackContext.eventActions())
314+
.content(content)
315+
.build());
317316
})
318317
.toFlowable();
319318
})

core/src/main/java/com/google/adk/agents/InvocationContext.java

Lines changed: 72 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -45,24 +45,25 @@ public class InvocationContext {
4545
private final BaseMemoryService memoryService;
4646
private final Plugin pluginManager;
4747
private final Optional<LiveRequestQueue> liveRequestQueue;
48-
private final Map<String, ActiveStreamingTool> activeStreamingTools = new ConcurrentHashMap<>();
48+
private final Map<String, ActiveStreamingTool> activeStreamingTools;
4949
private final String invocationId;
5050
private final Session session;
5151
private final Optional<Content> userContent;
5252
private final RunConfig runConfig;
5353
private final ResumabilityConfig resumabilityConfig;
54-
private final InvocationCostManager invocationCostManager = new InvocationCostManager();
54+
private final InvocationCostManager invocationCostManager;
5555

5656
private Optional<String> branch;
5757
private BaseAgent agent;
5858
private boolean endInvocation;
5959

60-
private InvocationContext(Builder builder) {
60+
protected InvocationContext(Builder builder) {
6161
this.sessionService = builder.sessionService;
6262
this.artifactService = builder.artifactService;
6363
this.memoryService = builder.memoryService;
6464
this.pluginManager = builder.pluginManager;
6565
this.liveRequestQueue = builder.liveRequestQueue;
66+
this.activeStreamingTools = builder.activeStreamingTools;
6667
this.branch = builder.branch;
6768
this.invocationId = builder.invocationId;
6869
this.agent = builder.agent;
@@ -71,6 +72,7 @@ private InvocationContext(Builder builder) {
7172
this.runConfig = builder.runConfig;
7273
this.endInvocation = builder.endInvocation;
7374
this.resumabilityConfig = builder.resumabilityConfig;
75+
this.invocationCostManager = builder.invocationCostManager;
7476
}
7577

7678
/**
@@ -188,7 +190,7 @@ public static InvocationContext create(
188190
.artifactService(artifactService)
189191
.agent(agent)
190192
.session(session)
191-
.liveRequestQueue(Optional.ofNullable(liveRequestQueue))
193+
.liveRequestQueue(liveRequestQueue)
192194
.runConfig(runConfig)
193195
.build();
194196
}
@@ -198,26 +200,19 @@ public static Builder builder() {
198200
return new Builder();
199201
}
200202

201-
/** Creates a shallow copy of the given {@link InvocationContext}. */
203+
/** Returns a {@link Builder} initialized with the values of this instance. */
204+
public Builder toBuilder() {
205+
return new Builder(this);
206+
}
207+
208+
/**
209+
* Creates a shallow copy of the given {@link InvocationContext}.
210+
*
211+
* @deprecated Use {@code other.toBuilder().build()} instead.
212+
*/
213+
@Deprecated(forRemoval = true)
202214
public static InvocationContext copyOf(InvocationContext other) {
203-
InvocationContext newContext =
204-
builder()
205-
.sessionService(other.sessionService)
206-
.artifactService(other.artifactService)
207-
.memoryService(other.memoryService)
208-
.pluginManager(other.pluginManager)
209-
.liveRequestQueue(other.liveRequestQueue)
210-
.branch(other.branch)
211-
.invocationId(other.invocationId)
212-
.agent(other.agent)
213-
.session(other.session)
214-
.userContent(other.userContent)
215-
.runConfig(other.runConfig)
216-
.endInvocation(other.endInvocation)
217-
.resumabilityConfig(other.resumabilityConfig)
218-
.build();
219-
newContext.activeStreamingTools.putAll(other.activeStreamingTools);
220-
return newContext;
215+
return other.toBuilder().build();
221216
}
222217

223218
/** Returns the session service for managing session state. */
@@ -258,7 +253,10 @@ public String invocationId() {
258253
/**
259254
* Sets the [branch] ID for the current invocation. A branch represents a fork in the conversation
260255
* history.
256+
*
257+
* @deprecated Use {@link #toBuilder()} and {@link Builder#branch(String)} instead.
261258
*/
259+
@Deprecated(forRemoval = true)
262260
public void branch(@Nullable String branch) {
263261
this.branch = Optional.ofNullable(branch);
264262
}
@@ -276,7 +274,12 @@ public BaseAgent agent() {
276274
return agent;
277275
}
278276

279-
/** Sets the [agent] being invoked. This is useful when delegating to a sub-agent. */
277+
/**
278+
* Sets the [agent] being invoked. This is useful when delegating to a sub-agent.
279+
*
280+
* @deprecated Use {@link #toBuilder()} and {@link Builder#agent(BaseAgent)} instead.
281+
*/
282+
@Deprecated(forRemoval = true)
280283
public void agent(BaseAgent agent) {
281284
this.agent = agent;
282285
}
@@ -370,15 +373,53 @@ void incrementAndEnforceLlmCallsLimit(RunConfig runConfig)
370373
"Max number of llm calls limit of " + runConfig.maxLlmCalls() + " exceeded");
371374
}
372375
}
376+
377+
@Override
378+
public boolean equals(Object o) {
379+
if (this == o) {
380+
return true;
381+
}
382+
if (!(o instanceof InvocationCostManager that)) {
383+
return false;
384+
}
385+
return numberOfLlmCalls == that.numberOfLlmCalls;
386+
}
387+
388+
@Override
389+
public int hashCode() {
390+
return Integer.hashCode(numberOfLlmCalls);
391+
}
373392
}
374393

375394
/** Builder for {@link InvocationContext}. */
376395
public static class Builder {
396+
397+
private Builder() {}
398+
399+
private Builder(InvocationContext context) {
400+
this.sessionService = context.sessionService;
401+
this.artifactService = context.artifactService;
402+
this.memoryService = context.memoryService;
403+
this.pluginManager = context.pluginManager;
404+
this.liveRequestQueue = context.liveRequestQueue;
405+
this.activeStreamingTools = new ConcurrentHashMap<>(context.activeStreamingTools);
406+
this.branch = context.branch;
407+
this.invocationId = context.invocationId;
408+
this.agent = context.agent;
409+
this.session = context.session;
410+
this.userContent = context.userContent;
411+
this.runConfig = context.runConfig;
412+
this.endInvocation = context.endInvocation;
413+
this.resumabilityConfig = context.resumabilityConfig;
414+
this.invocationCostManager = context.invocationCostManager;
415+
}
416+
377417
private BaseSessionService sessionService;
378418
private BaseArtifactService artifactService;
379419
private BaseMemoryService memoryService;
380420
private Plugin pluginManager = new PluginManager();
381421
private Optional<LiveRequestQueue> liveRequestQueue = Optional.empty();
422+
private Map<String, ActiveStreamingTool> activeStreamingTools = new ConcurrentHashMap<>();
382423
private Optional<String> branch = Optional.empty();
383424
private String invocationId = newInvocationContextId();
384425
private BaseAgent agent;
@@ -387,6 +428,7 @@ public static class Builder {
387428
private RunConfig runConfig = RunConfig.builder().build();
388429
private boolean endInvocation = false;
389430
private ResumabilityConfig resumabilityConfig = new ResumabilityConfig();
431+
private InvocationCostManager invocationCostManager = new InvocationCostManager();
390432

391433
/**
392434
* Sets the session service for managing session state.
@@ -458,8 +500,8 @@ public Builder liveRequestQueue(Optional<LiveRequestQueue> liveRequestQueue) {
458500
* @return this builder instance for chaining.
459501
*/
460502
@CanIgnoreReturnValue
461-
public Builder liveRequestQueue(LiveRequestQueue liveRequestQueue) {
462-
this.liveRequestQueue = Optional.of(liveRequestQueue);
503+
public Builder liveRequestQueue(@Nullable LiveRequestQueue liveRequestQueue) {
504+
this.liveRequestQueue = Optional.ofNullable(liveRequestQueue);
463505
return this;
464506
}
465507

@@ -618,7 +660,8 @@ public boolean equals(Object o) {
618660
&& Objects.equals(session, that.session)
619661
&& Objects.equals(userContent, that.userContent)
620662
&& Objects.equals(runConfig, that.runConfig)
621-
&& Objects.equals(resumabilityConfig, that.resumabilityConfig);
663+
&& Objects.equals(resumabilityConfig, that.resumabilityConfig)
664+
&& Objects.equals(invocationCostManager, that.invocationCostManager);
622665
}
623666

624667
@Override
@@ -637,6 +680,7 @@ public int hashCode() {
637680
userContent,
638681
runConfig,
639682
endInvocation,
640-
resumabilityConfig);
683+
resumabilityConfig,
684+
invocationCostManager);
641685
}
642686
}

core/src/main/java/com/google/adk/agents/ParallelAgent.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616
package com.google.adk.agents;
1717

1818
import static com.google.common.base.Strings.isNullOrEmpty;
19+
import static com.google.common.collect.ImmutableList.toImmutableList;
1920

2021
import com.google.adk.agents.ConfigAgentUtils.ConfigurationException;
2122
import com.google.adk.events.Event;
2223
import io.reactivex.rxjava3.core.Flowable;
23-
import java.util.ArrayList;
2424
import java.util.List;
2525
import org.slf4j.Logger;
2626
import org.slf4j.LoggerFactory;
@@ -101,14 +101,15 @@ public static ParallelAgent fromConfig(ParallelAgentConfig config, String config
101101
*
102102
* @param currentAgent Current agent.
103103
* @param invocationContext Invocation context to update.
104+
* @return A new invocation context with branch set.
104105
*/
105-
private static void setBranchForCurrentAgent(
106+
private static InvocationContext setBranchForCurrentAgent(
106107
BaseAgent currentAgent, InvocationContext invocationContext) {
107108
String branch = invocationContext.branch().orElse(null);
108109
if (isNullOrEmpty(branch)) {
109-
invocationContext.branch(currentAgent.name());
110+
return invocationContext.toBuilder().branch(currentAgent.name()).build();
110111
} else {
111-
invocationContext.branch(branch + "." + currentAgent.name());
112+
return invocationContext.toBuilder().branch(branch + "." + currentAgent.name()).build();
112113
}
113114
}
114115

@@ -122,18 +123,16 @@ private static void setBranchForCurrentAgent(
122123
*/
123124
@Override
124125
protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
125-
setBranchForCurrentAgent(this, invocationContext);
126-
127126
List<? extends BaseAgent> currentSubAgents = subAgents();
128127
if (currentSubAgents == null || currentSubAgents.isEmpty()) {
129128
return Flowable.empty();
130129
}
131130

132-
List<Flowable<Event>> agentFlowables = new ArrayList<>();
133-
for (BaseAgent subAgent : currentSubAgents) {
134-
agentFlowables.add(subAgent.runAsync(invocationContext));
135-
}
136-
return Flowable.merge(agentFlowables);
131+
var updatedInvocationContext = setBranchForCurrentAgent(this, invocationContext);
132+
return Flowable.merge(
133+
currentSubAgents.stream()
134+
.map(subAgent -> subAgent.runAsync(updatedInvocationContext))
135+
.collect(toImmutableList()));
137136
}
138137

139138
/**

core/src/main/java/com/google/adk/flows/llmflows/Examples.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import com.google.adk.examples.ExampleUtils;
2222
import com.google.adk.models.LlmRequest;
2323
import com.google.common.collect.ImmutableList;
24+
import com.google.genai.types.Content;
2425
import io.reactivex.rxjava3.core.Single;
2526

2627
/** {@link RequestProcessor} that populates examples in LLM request. */
@@ -38,9 +39,12 @@ public Single<RequestProcessor.RequestProcessingResult> processRequest(
3839
LlmRequest.Builder builder = request.toBuilder();
3940

4041
String query =
41-
context.userContent().isPresent()
42-
? context.userContent().get().parts().get().get(0).text().orElse("")
43-
: "";
42+
context
43+
.userContent()
44+
.flatMap(Content::parts)
45+
.filter(parts -> !parts.isEmpty())
46+
.map(parts -> parts.get(0).text().orElse(""))
47+
.orElse("");
4448
agent
4549
.exampleProvider()
4650
.ifPresent(

0 commit comments

Comments
 (0)