adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Add `get_events()` and `filter_events()` methods to Session

Open ecanlar opened this issue 8 months ago • 0 comments

Add get_events() and filter_events() methods to Session

Summary

This PR adds two new methods to the Session class to provide cleaner and more convenient access to session events, particularly for filtering out events that have been invalidated by rewind operations.

  • get_events() - Returns all events from the session
  • filter_events(exclude_rewound=True) - Returns events with optional filtering to exclude rewound events

Motivation

After the rewind feature was introduced (9dce06f), consumers who iterate over session.events need to manually filter out events that belong to rewound invocations.

Currently, every consumer must implement custom filtering logic like this:

@staticmethod
def _filter_rewound_events(events: list) -> list:
    """Filter out events that have been annulled by a rewind."""
    filtered = []
    i = len(events) - 1
    while i >= 0:
        event = events[i]
        if event.actions and event.actions.rewind_before_invocation_id:
            rewind_invocation_id = event.actions.rewind_before_invocation_id
            for j in range(0, i):
                if events[j].invocation_id == rewind_invocation_id:
                    i = j
                    break
        else:
            filtered.append(event)
        i -= 1
    filtered.reverse()
    return filtered

This logic is:

  1. Error-prone - Easy to get wrong when implementing from scratch
  2. Duplicated - Every consumer needs to implement it
  3. Inconsistent - Different implementations may have subtle bugs

Solution

Add two methods to the Session class:

get_events() -> list[Event]

Returns all events in the session. This provides a method-based API consistent with the new filter_events() method.

# Before
for event in session.events:
    process(event)

# After  
for event in session.get_events():
    process(event)

filter_events(*, exclude_rewound: bool = True) -> list[Event]

Returns filtered events. By default, excludes events that have been invalidated by a rewind operation.

# Get only "active" events (excluding rewound)
for event in session.filter_events():
    process(event)

# Get all events including rewound ones
for event in session.filter_events(exclude_rewound=False):
    process(event)

Use Case Example

Before (current state)

class MyAgentRunner:
    async def get_conversation_history(self, session: Session) -> list[str]:
        # Must implement filtering manually
        filtered_events = self._filter_rewound_events(session.events)
        return [self._extract_text(e) for e in filtered_events if e.author == "user"]
    
    @staticmethod
    def _filter_rewound_events(events: list) -> list:
        # 15+ lines of complex filtering logic...
        filtered = []
        i = len(events) - 1
        while i >= 0:
            event = events[i]
            if event.actions and event.actions.rewind_before_invocation_id:
                rewind_invocation_id = event.actions.rewind_before_invocation_id
                for j in range(0, i):
                    if events[j].invocation_id == rewind_invocation_id:
                        i = j
                        break
            else:
                filtered.append(event)
            i -= 1
        filtered.reverse()
        return filtered

After (with this PR)

class MyAgentRunner:
    async def get_conversation_history(self, session: Session) -> list[str]:
        # Clean and simple!
        return [
            self._extract_text(e) 
            for e in session.filter_events() 
            if e.author == "user"
        ]

Changes

Modified Files

  • src/google/adk/sessions/session.py - Added get_events() and filter_events() methods

New Files

  • tests/unittests/sessions/test_session_filter_events.py - Unit tests for the new methods

Backward Compatibility

This is a non-breaking change:

  • session.events remains accessible as before
  • New methods are purely additive
  • No changes to existing behavior

Testing

Added comprehensive unit tests covering:

  • get_events() returns all events
  • filter_events() with default behavior (excludes rewound)
  • filter_events(exclude_rewound=False) returns all events
  • Single rewind scenario
  • Multiple sequential rewinds
  • Empty events list
  • Events with no rewind operations

Checklist

  • [x] Code follows the project's style guidelines
  • [x] Added unit tests for new functionality
  • [x] All existing tests pass
  • [x] Documentation updated (docstrings)
  • [x] Backward compatible

Related Issues

This addresses the need for a standard way to filter rewound events, which became necessary after the rewind feature was added in 9dce06f.

ecanlar avatar Mar 23 '26 10:03 ecanlar