Observers let you attach lightweight, read-only event listeners directly to an Agent. Under the hood, each observer is a regular Stream subscriber — but you register it on the Agent instead of managing the stream yourself.
Use observers when you want to monitor agent behavior (logging, metrics, debugging) without writing a full Middleware class.
Use the observer() function to pair an event condition with a callback. The first argument is the event type (or condition) to match, the second is an optional callback:
fromautogen.betaimportAgentagent=Agent("assistant",config=config,observers=[observer(ModelResponse,log_to_file)],)# log_to_file fires AND send_metric fires for this callreply=awaitagent.ask("Hello!",observers=[observer(ModelResponse,send_metric)],)
# Async observer — disable sync_to_thread since it's already async@observer(ModelResponse,sync_to_thread=False)asyncdefasync_tracker(event:ModelResponse)->None:awaitmetrics.record(event)# Interrupter — processes before regular subscribers and can modify events@observer(ModelResponse,interrupt=True)defintercept(event:ModelResponse)->ModelResponse:event.content=event.content.upper()returnevent