Skip to content

Conversation

@strands-agent
Copy link
Contributor

Description

Add BeforeContextReductionEvent and AfterContextReductionEvent hooks that fire when the agent reduces context due to ContextWindowOverflowException.

This enables users to:

  • Notify users that context reduction is starting/completing
  • Display UI feedback during long conversations
  • Monitor context window usage patterns
  • Implement custom cleanup before messages are removed

Events Added

BeforeContextReductionEvent

  • Fires before reduce_context() is called
  • Attributes: exception, message_count

AfterContextReductionEvent

  • Fires after reduce_context() completes
  • Attributes: original_message_count, new_message_count, removed_count
  • Uses reverse callback ordering (consistent with other "After" events)

Usage Example

import asyncio
from strands import Agent
from strands.hooks import BeforeContextReductionEvent, AfterContextReductionEvent

agent = Agent(model=...)

@agent.hooks.on(BeforeContextReductionEvent)
async def on_reduction_start(event):
    print(f"⏳ Context reduction starting ({event.message_count} messages)")

@agent.hooks.on(AfterContextReductionEvent)
async def on_reduction_complete(event):
    print(f"✅ Context reduced: {event.original_message_count}{event.new_message_count} ({event.removed_count} removed)")

Related Issues

Closes #1511

Documentation PR

No documentation changes required - follows existing hook event patterns.

Type of Change

New feature

Testing

  • Added unit tests for both new event classes
  • Verified existing hook tests still pass (30/30 tests)
  • I ran hatch fmt (formatter + linter)

Checklist

  • I have read the CONTRIBUTING document
  • I have added tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly (N/A - follows existing patterns)
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Adds BeforeContextReductionEvent and AfterContextReductionEvent hook events
that are emitted when the agent handles ContextWindowOverflowException.

This enables users to:
- Show 'compacting conversation...' UI feedback during context reduction
- Track context reduction frequency for analytics
- Debug context window management issues

Closes strands-agents#1511
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Real-time Streaming Events During Context Reduction

1 participant