Agent skill

Ag2 Observers And Alerts

by ag2ai in ag2ai/build-with-ag2

Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions.

Apache-2.0Auto-check passedDevOps & Cloud

Install Ag2 Observers And Alerts

skills CLI
$ npx skills add ag2ai/build-with-ag2 --skill ag2-observers-and-alerts -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ag2ai/build-with-ag2 ag2-observers-and-alerts --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ag2ai/build-with-ag2.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/ag2-observers-and-alerts .claude/skills/ag2-observers-and-alerts && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
ag2-observers-and-alerts
GitHub stars
252
Token cost
~2.5k tokens
SKILL.md length
644 words
Files
3 (incl. assets)
Skills in repo
16
Repo updated
First seen
Licence
Apache-2.0

At a glance

Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions.

  • Works in 2 steps: Emits a HaltEvent on the stream. → Appends a halt notice to the system…
  • The user wants observability
  • SKILL.md covers When to use, Two observer shapes, 60-second recipe — @observer and Built-in stateful observers, plus 8 more sections
  • Runs Python scripts from its folder

What it does

Ag2 Observers And Alerts is an agent skill from ag2ai/build-with-ag2. Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions. Covers @observer(...) (stateless), BaseObserver (stateful), built-ins (TokenMonitor, LoopDetector), Watch primitives (EventWatch, CadenceWatch, DelayWatch, IntervalWatch, CronWatch, AllOf, AnyOf, Sequence), ObserverAlert (Severity.INFO/WARNING/CRITICAL/FATAL), AlertPolicy, and HaltEvent. Use when the user wants…

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files, including assets (for example `assets/safety_guard.py` and `assets/token_watchdog.py`).

It sits in DevOps & Cloud, covering Observability. The repository describes itself as: Sample code and application showcases to get you going with AG2 (formally AutoGen). The licence is Apache-2.0.

When your agent uses it

  • The user wants observability
  • Runtime safety guards
  • Batch/time-based reactive logic

Example prompts

  • “/ag2-observers-and-alerts”

Requirements

  • Python 3

Workflow steps

2 steps, taken from the first numbered list in SKILL.md.

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

What it can do on your machine

Read from SKILL.md and the folder at commit 29eeac3. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Ag2 Observers And Alerts loads about 2.5k tokens when it runs. Until then it costs about 162 tokens; SKILL.md has 644 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~162
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ag2ai/build-with-ag2 at commit 29eeac3, republished under its Apache-2.0 licence (© ag2ai). 644 words, ~2,527 tokens.

Download SKILL.mdSave it as .claude/skills/ag2-observers-and-alerts/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
name
ag2-observers-and-alerts
description
Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions. Covers `@observer(...)` (stateless), `BaseObserver` (stateful), built-ins (`TokenMonitor`, `LoopDetector`), `Watch` primitives (`EventWatch`, `CadenceWatch`, `DelayWatch`, `IntervalWatch`, `CronWatch`, `AllOf`, `AnyOf`, `Sequence`), `ObserverAlert` (`Severity.INFO/WARNING/CRITICAL/FATAL`), `AlertPolicy`, and `HaltEvent`. Use when the user wants observability, runtime safety guards, alerts, or batch/time-based reactive logic.
license
Apache-2.0

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

python
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

python
from autogen.beta import Agent
from autogen.beta.observer 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):

python
from autogen.beta import Context
from autogen.beta.observer 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

python
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=[...]:

python
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.

python
from autogen.beta import Context
from autogen.beta.observer 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.

Show full SKILL.md (231 more words)Show less

Subscribing to alerts and halts from outside

python
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.py — PathGuardian → FATAL → AlertPolicy → HaltEvent → 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.mdx — AlertPolicy ordering and dedup.

Common pitfalls

  • Alerts not reaching the model — ObserverAlert events are on the stream but invisible to the LLM by default. Add AlertPolicy() to assembly=[...].
  • FATAL not halting — AlertPolicy 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 async — BaseObserver.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 — invalid; at least one is required.

© ag2ai, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files (assets) in .agents/skills/ag2-observers-and-alerts of ag2ai/build-with-ag2.

  • SKILL.md
  • assets/safety_guard.py
  • assets/token_watchdog.py

Open the folder on GitHubat commit 29eeac3

Compare with similar skills

Ag2 Observers And Alerts next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Ag2 Observers And Alerts compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Ag2 Observers And Alerts this skillag2ai/build-with-ag2252—~2.5kAutomated safety check: PassApache-2.0
Vercel Optimize Auditvercel-labs/agent-skills32k8 repos~4.3kAutomated safety check: PassNone
Kubeshark Installerkubeshark/kubeshark12k—~3.6kAutomated safety check: NotesApache-2.0
Kubeshark KFL2 Filter Referencekubeshark/kubeshark12k—~3.6kAutomated safety check: PassApache-2.0
KubeSphere ServiceMesh Managerkubesphere/kubesphere17k—~2.4kAutomated safety check: PassCustom licence
Kubernetes Network Root Cause Analysiskubeshark/kubeshark12k—~5.3kAutomated safety check: PassApache-2.0

Similar skills

  • Vercel Optimize Audit

    vercel-labs/agent-skills

    Official

    Runs a metrics-first audit of a deployed Vercel project, gating investigations on real signals to produce ranked, citation-backed cost and performance recommendations.

    32k GitHub starsUsed in 8 repos~4.3k tokens
    DevOps & CloudAuto-check passed
  • Kubeshark Installer

    kubeshark/kubeshark

    Installs and configures Kubeshark on a Kubernetes cluster, choosing between the quick CLI path and a Helm install with custom values.

    12k GitHub stars~3.6k tokensUpdated yesterday
    DevOps & CloudAuto-check: notes
  • Syntax reference for KFL2, the CEL-based display filter language used to search Kubernetes network traffic captured by Kubeshark, loaded before any filter is written.

    12k GitHub stars~3.6k tokensUpdated yesterday
    DevOps & CloudAuto-check passed
  • KubeSphere ServiceMesh Manager

    kubesphere/kubesphere

    Installs, checks and troubleshoots the KubeSphere ServiceMesh extension (Istio, Kiali, Jaeger), including grayscale release, sidecar injection, topology and tracing issues.

    17k GitHub stars~2.4k tokensUpdated 2 mo ago
    DevOps & CloudAuto-check passed
  • Investigates past Kubernetes incidents from Kubeshark traffic snapshots: takes captures, dissects API calls, extracts PCAPs and compares traffic over time.

    12k GitHub stars~5.3k tokensUpdated yesterday
    DevOps & CloudAuto-check passed
  • Caveman Gateway Setup

    JuliusBrussee/caveman

    Routes every LLM call in a repository through the Caveman Cloud gateway in record mode, so requests and costs are measured without changing behavior.

    111k GitHub starsUsed in 1 repo~2.6k tokens
    DevOps & CloudAuto-check: warnings

More from ag2ai/build-with-ag2

All 16 skills in this repo
  • Ag2 Add Custom Tool

    ag2ai/build-with-ag2

    Add a custom Python tool to an AG2 beta Agent using the @tool decorator.

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Middleware

    ag2ai/build-with-ag2

    Intercept the AG2 beta agent loop with BaseMiddleware — wrap full turns (onturn), each LLM call (onllmcall), each tool execution (ontoolexecution), or each human-input request (onhumaninput).

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Use Builtin Tools

    ag2ai/build-with-ag2

    Wire AG2 beta's shipped tools into an Agent — both provider-native server-side tools (web search, web fetch, code execution, MCP, image generation, memory) and locally-executed common toolkits…

    252 GitHub stars~1.3k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Knowledge And Memory

    ag2ai/build-with-ag2

    Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window.

    252 GitHub stars~2.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Quickstart

    ag2ai/build-with-ag2

    Build a minimal AG2 beta Agent end to end — pick a model provider, set a prompt, call agent.ask(), then continue the conversation with reply.ask() (multi-turn).

    252 GitHub stars~1.7k tokensUpdated 1 mo ago
    Auto-check: notes
  • Ag2 Structured Output

    ag2ai/build-with-ag2

    Get a typed Python value back from an AG2 beta Agent instead of free text.

    252 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed

Categories

Questions about Ag2 Observers And Alerts

What does Ag2 Observers And Alerts do?

Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions. Ag2 Observers And Alerts is an agent skill from ag2ai/build-with-ag2. Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions.

When should I use Ag2 Observers And Alerts?

Ag2 Observers And Alerts fits situations like: the user wants observability; runtime safety guards; batch/time-based reactive logic.

How do I install Ag2 Observers And Alerts in Claude Code?

Run `npx skills add ag2ai/build-with-ag2 --skill ag2-observers-and-alerts -a claude-code`. Or copy the skill folder (.agents/skills/ag2-observers-and-alerts in ag2ai/build-with-ag2) into .claude/skills/ag2-observers-and-alerts in your project. Claude Code loads it when a task matches its description.

How do I install Ag2 Observers And Alerts in Codex?

Run `npx skills add ag2ai/build-with-ag2 --skill ag2-observers-and-alerts -a codex`. Or copy the skill folder (.agents/skills/ag2-observers-and-alerts in ag2ai/build-with-ag2) into .agents/skills/ag2-observers-and-alerts in your project. Codex loads it when a task matches its description.

Can I use Ag2 Observers And Alerts in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ag2ai/build-with-ag2 --skill ag2-observers-and-alerts -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/ag2-observers-and-alerts, .gemini/skills/ag2-observers-and-alerts, .github/skills/ag2-observers-and-alerts and .opencode/skills/ag2-observers-and-alerts in your project.

What does Ag2 Observers And Alerts need to run?

Going by SKILL.md and its folder, Ag2 Observers And Alerts needs Python for the scripts in its folder. Our summary lists: Python 3.

Does Ag2 Observers And Alerts access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Ag2 Observers And Alerts safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Ag2 Observers And Alerts use?

Ag2 Observers And Alerts is published under the Apache-2.0 licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Ag2 Observers And Alerts use?

About 2.5k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Ag2 Observers And Alerts?

Skills that share tags, products or a category with Ag2 Observers And Alerts: Vercel Optimize Audit (vercel-labs/agent-skills, 32k stars), Kubeshark Installer (kubeshark/kubeshark, 12k stars), Kubeshark KFL2 Filter Reference (kubeshark/kubeshark, 12k stars) and KubeSphere ServiceMesh Manager (kubesphere/kubesphere, 17k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Ag2 Observers And Alerts?

ag2ai (a GitHub organization) maintains it in ag2ai/build-with-ag2, which has 252 GitHub stars. The repository holds 16 skills in this directory. The repository was last updated on September 6, 2026.

Source: ag2ai/build-with-ag2 on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.