Skip to content

Commit 2e25b4d

Browse files
cornellgitcopybara-github
authored andcommitted
feat: make readonly context more efficient
PiperOrigin-RevId: 782128528
1 parent 92631a1 commit 2e25b4d

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

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

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

1919
import com.google.adk.events.Event;
20-
import com.google.common.collect.ImmutableList;
21-
import com.google.common.collect.ImmutableMap;
2220
import com.google.genai.types.Content;
21+
import java.util.Collections;
2322
import java.util.List;
2423
import java.util.Map;
2524
import java.util.Optional;
@@ -28,6 +27,8 @@
2827
public class ReadonlyContext {
2928

3029
protected final InvocationContext invocationContext;
30+
private List<Event> eventsView;
31+
private Map<String, Object> stateView;
3132

3233
public ReadonlyContext(InvocationContext invocationContext) {
3334
this.invocationContext = invocationContext;
@@ -59,22 +60,26 @@ public String sessionId() {
5960
}
6061

6162
/**
62-
* Returns a read-only view of the events of the current session.
63+
* Returns an unmodifiable view of the events of the session.
6364
*
64-
* <p>This is a shallow copy and if the underlying values of the list are modified, the read-only
65-
* view will also be modified.
65+
* <p><b>Warning:</b> This is a live view, not a snapshot.
6666
*/
67-
public ImmutableList<Event> events() {
68-
return ImmutableList.copyOf(invocationContext.session().events());
67+
public List<Event> events() {
68+
if (eventsView == null) {
69+
eventsView = Collections.unmodifiableList(invocationContext.session().events());
70+
}
71+
return eventsView;
6972
}
7073

7174
/**
72-
* Returns a read-only view of the state of the current session.
75+
* Returns an unmodifiable view of the state of the session.
7376
*
74-
* <p>This is a shallow copy and if the underlying values of the map are modified, the read-only
75-
* view will also be modified.
77+
* <p><b>Warning:</b> This is a live view, not a snapshot.
7678
*/
7779
public Map<String, Object> state() {
78-
return ImmutableMap.copyOf(invocationContext.session().state());
80+
if (stateView == null) {
81+
stateView = Collections.unmodifiableMap(invocationContext.session().state());
82+
}
83+
return stateView;
7984
}
8085
}

0 commit comments

Comments
 (0)