Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
ag2ai avatar

Ag2 Observers And Alerts

  • 33 installs
  • 8 repo stars
  • Updated July 27, 2026
  • ag2ai/ag2-skills

ag2-observers-and-alerts is a Claude Code skill that monitors an AG2 beta agent's stream for logging, loop detection, token tracking, alerts, and FATAL halts.

About

This skill monitors an AG2 beta agent's event stream to log events, detect repeated tool calls, track token spend, and build trigger-driven observers. A developer uses it for observability, runtime safety guards, alerts, or batch/time-based reactive logic. It covers stateless @observer functions, stateful BaseObserver classes, built-ins like TokenMonitor and LoopDetector, Watch primitives, ObserverAlert severities, and halting on FATAL conditions.

  • Monitors an AG2 agent's stream: log events, detect loops, track token spend
  • Trigger-driven observers with Watch primitives and severity-based alerts
  • Routes alerts to the model and halts on FATAL conditions

Ag2 Observers And Alerts by the numbers

  • 33 all-time installs (skills.sh)
  • Ranked #8,975 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
  • Data as of Aug 1, 2026 (Skillselion catalog sync)
At a glance

ag2-observers-and-alerts capabilities & compatibility

Free skill; requires an LLM provider API key to run the agent.

Capabilities
agent observability · loop detection · token monitoring · runtime guardrails
Use cases
orchestration · token optimization · debugging
Pricing
Bring your own API key
npx skills add https://github.com/ag2ai/ag2-skills --skill ag2-observers-and-alerts

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs33
repo stars8
Last updatedJuly 27, 2026
Repositoryag2ai/ag2-skills

What it does

Add observability, runtime safety guards, and alerting to an AG2 beta agent's event stream.

Who is it for?

Developers who want observability, runtime safety guards, or reactive metrics on an AG2 agent.

Skip if: Projects not built on AG2 beta (autogen.beta).

When should I use this skill?

The user wants observability, runtime safety guards, alerts, or batch/time-based reactive logic.

What you get

Observers log events, detect loops, cap token spend, and halt the agent on FATAL alerts.

By the numbers

  • 4 alert severities (INFO, WARNING, CRITICAL, FATAL)
  • 2 built-in stateful observers (TokenMonitor, LoopDetector)

Files

SKILL.mdMarkdownGitHub ↗

Observers, watches, and alerts

When to use

  • Observability — log model responses, tool calls, token usage.
  • Runtime safety — block dangerous tool arguments, halt the agent.
  • Reactive metrics — fire on every Nth response, or every M seconds.
  • Loop / repetition detection — catch infinite tool-call loops.
  • Stateful monitoring — anything that needs to remember prior events to decide what to do next.

Two observer shapes

ShapeWhenUse
Stateless functionOne-off event hook (logging, metrics)@observer(EventType)
Stateful classCounters / windows / thresholds / composed triggersSubclass BaseObserver

Both are stream subscribers under the hood — registered on the agent rather than directly on the stream.

60-second recipe — @observer

from autogen.beta import Agent, observer
from autogen.beta.config import OpenAIConfig
from autogen.beta.events import ModelResponse

@observer(ModelResponse)
async def log_response(event: ModelResponse) -> None:
    print(f"Model said: {event.content}")

agent = Agent(
    "assistant",
    config=OpenAIConfig(model="gpt-4o-mini"),
    observers=[log_response],
)

Or attach after construction with @agent.observer(...). Per-call observers also supported (agent.ask("...", observers=[...])).

Observer callbacks support full dependency injection (Context, Inject, Variable, Depends). Filter by event type, multiple types (ModelRequest | ModelResponse), or field value (ToolCallEvent.name == "search"). Use interrupt=True to modify or suppress events before regular subscribers see them.

Built-in stateful observers

from autogen.beta import Agent
from autogen.beta.observers import LoopDetector, TokenMonitor

agent = Agent(
    "assistant",
    config=config,
    observers=[
        TokenMonitor(warn_threshold=50_000, alert_threshold=100_000),
        LoopDetector(window_size=10, repeat_threshold=3),
    ],
)
  • `TokenMonitor` — tracks cumulative tokens across ModelResponse and TaskCompleted. Emits WARNING / CRITICAL ObserverAlerts as thresholds are crossed. Read state via monitor.total_tokens.
  • `LoopDetector` — sliding window of recent tool calls. Emits a WARNING alert when repeat_threshold consecutive identical calls are seen.

Custom BaseObserver

A BaseObserver pairs a Watch (when to fire) with a process() method (what to do):

from autogen.beta import Context
from autogen.beta.observers import BaseObserver
from autogen.beta.watch import CadenceWatch
from autogen.beta.events import BaseEvent, ModelResponse
from autogen.beta.events.alert import ObserverAlert, Severity

class AvgCompletionObserver(BaseObserver):
    """Every N responses, emit an INFO alert with avg completion-token count."""

    def __init__(self, window: int = 5) -> None:
        super().__init__("avg-completion", watch=CadenceWatch(n=window, condition=ModelResponse))
        self._window = window

    async def process(self, events: list[BaseEvent], ctx: Context) -> ObserverAlert | None:
        tokens = [e.usage.completion_tokens for e in events if isinstance(e, ModelResponse) and e.usage]
        if not tokens:
            return None
        return ObserverAlert(
            source=self.name,
            severity=Severity.INFO,
            message=f"Avg completion tokens over last {self._window}: {sum(tokens) / len(tokens):.0f}",
        )

If process() returns an ObserverAlert, the base class emits it onto the stream. You can also send events manually via await ctx.send(...).

Watch primitives — picking when to fire

You needUse
Every matching eventEventWatch(EventType) or just stream.subscribe(fn, condition=...)
Every N matching eventsCadenceWatch(n=N, condition=EventType)
Every T seconds (buffered events)CadenceWatch(max_wait=T, condition=EventType)
Either thresholdCadenceWatch(n=N, max_wait=T, condition=EventType)
Once after delayDelayWatch(seconds)
Periodic timerIntervalWatch(seconds)
Cron scheduleCronWatch("0 9 * * MON")
All sub-watches must fireAllOf(w1, w2)
Any sub-watch firesAnyOf(w1, w2)
In orderSequence(w1, w2)

All importable from autogen.beta.watch. Callback signature is uniform: async def cb(events: list[BaseEvent], ctx: Context) -> None. Time-driven watches pass events=[].

ObserverAlert — the alert type

from autogen.beta.events.alert import ObserverAlert, Severity

ObserverAlert(
    source="my-observer",
    severity=Severity.WARNING,    # INFO, WARNING, CRITICAL, FATAL
    message="What happened",
)

Important: ObserverAlert is on the stream and persisted in history, but the default provider mappers do not render it back to the LLM. To make the agent see alerts, add AlertPolicy() to assembly=[...]:

from autogen.beta.policies import AlertPolicy
agent = Agent("assistant", config=config, assembly=[AlertPolicy()])

FATAL alerts → HaltEvent → short-circuit

AlertPolicy does two things on Severity.FATAL:

1. Emits a HaltEvent on the stream. 2. Appends a halt notice to the system prompt.

When assembly=[...] is non-empty, the harness automatically wires _HaltCheckMiddleware which sees the HaltEvent and short-circuits the next LLM call with a synthetic HALTED: ... response.

from autogen.beta import Context
from autogen.beta.observers import BaseObserver
from autogen.beta.events import BaseEvent, ToolCallEvent
from autogen.beta.events.alert import HaltEvent, ObserverAlert, Severity
from autogen.beta.policies import AlertPolicy
from autogen.beta.watch import EventWatch

class PathGuardian(BaseObserver):
    def __init__(self) -> None:
        super().__init__("path-guardian", watch=EventWatch(ToolCallEvent))

    async def process(self, events: list[BaseEvent], ctx: Context) -> ObserverAlert | None:
        for event in events:
            if not isinstance(event, ToolCallEvent) or event.name != "write_file":
                continue
            if "/etc/" in event.arguments or "/usr/" in event.arguments:
                return ObserverAlert(
                    source=self.name,
                    severity=Severity.FATAL,
                    message=f"blocked dangerous write: {event.arguments}",
                )
        return None

agent = Agent(
    "safe-shell",
    prompt="...",
    config=config,
    tools=[write_file],
    observers=[PathGuardian()],
    assembly=[AlertPolicy()],   # routes FATAL → HaltEvent
)

The first dangerous tool call triggers FATAL → halt; the agent's next ask is short-circuited. Full runnable demo: assets/safety_guard.py.

Subscribing to alerts and halts from outside

from autogen.beta import MemoryStream
from autogen.beta.events.alert import HaltEvent, ObserverAlert

stream = MemoryStream()
stream.where(ObserverAlert).subscribe(lambda e: print(f"[{e.severity}] {e.source}: {e.message}"))
stream.where(HaltEvent).subscribe(lambda e: print(f"HALT: {e.reason}"))
await agent.ask("...", stream=stream)

Observers vs Middleware vs Stream subscribers

FeatureObserverMiddlewareStream subscriber
Registered onAgentAgentStream
LifecycleScoped to executionScoped to executionManual
BoilerplateFunction (or BaseObserver)BaseMiddleware classFunction
Can modify eventsinterrupt=TrueYes (wraps execution)interrupt=True
DI supportYesYesYes
Use caseMonitoring, metrics, alertsCross-cutting (retry, auth, rate limit)Low-level event wiring

Going deeper

  • assets/token_watchdog.py — three observers (TokenMonitor, LoopDetector, custom AlertConsole) on one agent. Mirrors code_examples/04.
  • assets/safety_guard.pyPathGuardian → FATAL → AlertPolicyHaltEvent → short-circuit. Mirrors code_examples/08.
  • Source docs:
  • website/docs/beta/advanced/observers.mdx@observer, BaseObserver, registration, built-ins, ObserverAlert.
  • website/docs/beta/advanced/watches.mdx — every Watch primitive, composition rules.
  • website/docs/beta/advanced/stream.mdx — Stream API, where, subscribe, interrupters, RedisStream.
  • website/docs/beta/advanced/assembly.mdxAlertPolicy ordering and dedup.

Common pitfalls

  • Alerts not reaching the modelObserverAlert events are on the stream but invisible to the LLM by default. Add AlertPolicy() to assembly=[...].
  • FATAL not haltingAlertPolicy is what creates HaltEvent. Without assembly=[..., AlertPolicy(), ...] (or any non-empty assembly chain enabling _HaltCheckMiddleware), nothing halts.
  • Sharing one `AlertPolicy()` across agents — dedup state lives on the instance. Give each agent its own.
  • Watch callback assumes `events` is non-empty — for time-driven watches (DelayWatch, IntervalWatch, CronWatch), events is always [].
  • Forgetting `process()` is asyncBaseObserver.process must be async def.
  • Subscribing with `subscribe(fn)` when you wanted `subscribe()` decorator — both work; the bare-call form is stream.subscribe(fn), the decorator form is @stream.subscribe() (with parens).
  • `CadenceWatch` with no `n` and no `max_wait` — raises ValueError; at least one is required.

Related skills

FAQ

What are the two observer shapes?

Stateless @observer functions and stateful BaseObserver classes.

How do FATAL alerts stop the agent?

AlertPolicy emits a HaltEvent on the stream and appends a halt notice to the system prompt.

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.