Gateway Status Tool

Let an agent inspect its own live gateway state mid-turn — run status, active sessions, delivery backlog, and degraded channels

Gateway Status lets a running agent look at its own live gateway state — whether it’s busy or idle, how many conversations are active, the delivery backlog, and whether any channel is degraded — so it can proactively warn the user instead of silently under-delivering.

python
from praisonaiagents import Agent
from praisonaiagents.tools import gateway_status

agent = Agent(
    name="Ops Assistant",
    instructions=(
        "If a user asks how you're doing or whether their message went out, "
        "call gateway_status and answer from the live snapshot."
    ),
    tools=[gateway_status],
)
agent.start("Are you busy right now, and did my last message to #ops go out?")

A user asks the agent how it’s doing; the agent reads its own live gateway snapshot and answers from the current state — all within a single turn.

Diagram

Gateway Status Flow

🤖 Agent

📊 gateway_status

🛰️ Gateway Snapshot

✅ JSON Live State

Which tool?

gateway_status is easy to confuse with its two siblings. This decision diagram picks the right one.

Diagram

Deliver a message to a target

Ask a target and wait for reply

Inspect the gateway’s own state

Which gateway tool?

What do you need?

send_message

ask_conversation

gateway_status

ToolPurposeWaits?Returns
send_messageDeliver to a targetNoDeliveryResult
ask_conversationAsk a target, await replyYes (bounded)JSON string, typed status
gateway_statusInspect self-stateNoJSON string, live snapshot

Quick Start

  1. Enable the Tool
    python
    from praisonaiagents import Agent
    from praisonaiagents.tools import gateway_status
    
    agent = Agent(
        name="Ops Assistant",
        instructions="Report your live state when asked how you're doing.",
        tools=[gateway_status],
    )
    
    agent.start("How busy are you right now?")
    # Model call:
    #   gateway_status()
    # Returns JSON:
    #   {"run": "busy", "queued": 2, "active_sessions": 7, ...}
  2. React to a Busy State
    python
    agent = Agent(
        name="Ops Assistant",
        instructions=(
            "Call gateway_status before answering. "
            "If run is 'busy' or queued > 0, tell the user you'll get back to them shortly."
        ),
        tools=[gateway_status],
    )
  3. Detect Degraded Channels
    python
    agent = Agent(
        name="Ops Assistant",
        instructions=(
            "Call gateway_status. "
            "If degraded lists the channel the user is on, "
            "warn them their next message may be delayed."
        ),
        tools=[gateway_status],
    )
  4. Detect Redis pub/sub outage
    python
    agent = Agent(
        name="Ops Assistant",
        instructions=(
            "Call gateway_status. "
            "If push.redis_degraded is true, warn the user their message "
            "may not have fanned out to other gateway instances."
        ),
        tools=[gateway_status],
    )

How It Works

The running gateway registers a live source into the per-turn context; gateway_status resolves it and serializes a snapshot, returning the no-gateway message when nothing is registered.

Diagram
GatewayGatewayStatusProtocolSessionContextgateway_statusAgentGatewayGatewayStatusProtocolSessionContextgateway_statusAgentalt[no gateway][gateway active]gateway_status()get_gateway_status()source (or None)“No active gateway: …”snapshot()read health / metrics / sessionslive stateGatewayStatusJSON string
ComponentPurpose
gateway_status toolAgent-callable function; resolves the live source from context
GatewayStatusProtocolRead-only interface the gateway registers per-turn via register_gateway_status
SessionContext slotTask-local get_gateway_status() — no globals, safe for concurrent handlers
Concrete bindingReads health() / metrics_snapshot() / the session registry in the praisonai-bot wrapper

Core ships only the protocol, the snapshot shape, and the built-in tool; when no source is registered (CLI / one-shot), the tool returns the no-gateway message instead of raising.


Fields Reference

gateway_status() takes no arguments and returns a JSON string serialized from GatewayStatus.as_dict(). Every field defaults to empty so a partial binding is valid.

FieldTypeDefaultDescription
runstr"idle"Current turn/run status (e.g. "idle", "busy", "queued").
queuedint0Number of turns queued behind the current one.
active_sessionsint0Count of active sessions (visibility-scoped).
sessions_by_channeldict[str, int]{}Active-session counts keyed by channel/platform (e.g. {"telegram": 5, "slack": 2}).
deliverydict[str, Any]{}Delivery-health facts, e.g. {"outbox_depth": 0, "dlq": 1, "dead_targets": ["slack:C123"]}.
degradedlist[dict][]Degraded owners as {"owner": ..., "reason": ...} entries (channels/capabilities/routes flagged configured-unavailable).
detailstr""Optional free-form extra context for the model.

Push HA state

When the gateway runs with Redis pub/sub fan-out (PushConfig(redis=...)), the push block reports the health of the cross-instance transport.

FieldTypeDescription
push.redis_connectedboolTrue only when the adapter has a live client and is not marked degraded.
push.redis_degradedboolTrue for the duration of a Redis pub/sub outage; False after recovery.
push.redis_dropped_writesintMonotonically increasing count of writes (publish / presence / message-store) attempted while disconnected.

When degraded, route:redis-pubsub also appears in degraded_owners:

json
{
  "push": {
    "redis_connected": false,
    "redis_degraded": true,
    "redis_dropped_writes": 3,
    "online_clients": 12
  },
  "degraded_owners": [
    {
      "owner_kind": "route",
      "owner_id": "redis-pubsub",
      "state": "stale",
      "reason": "redis pub/sub disconnected: Connection refused",
      "retry_hint": "check Redis connectivity; see `praisonai gateway doctor`"
    }
  ]
}

See Real-Time Push Notifications → HA & cross-instance delivery for the full outage-and-recovery contract.

Durability-degraded owners

When a durable state store cannot initialise, the gateway falls back to in-memory and records a gateway owner under degraded_owners — owner_id = "durability:idempotency" (webhook dedup) or owner_id = "durability:session" (session history). The reason is redacted; the raw store path stays in the log.

json
{
  "degraded_owners": [
    {
      "owner_kind": "gateway",
      "owner_id": "durability:idempotency",
      "state": "cold",
      "reason": "durable idempotency store unavailable (running in-memory)",
      "retry_hint": "praisonai gateway doctor --fix"
    }
  ]
}

The entry clears automatically once the durable store comes up (a restart or hot-reload that repairs the path). See Gateway State Durability.

Example returned JSON:

json
{
  "run": "busy",
  "queued": 2,
  "active_sessions": 7,
  "sessions_by_channel": {"telegram": 5, "slack": 2},
  "delivery": {"outbox_depth": 0, "dlq": 1, "dead_targets": ["slack:C123"]},
  "degraded": [{"owner": "channel:telegram", "reason": "credential_unavailable"}],
  "detail": ""
}

When It’s Available

gateway_status needs a running bot/gateway to read live self-state; a plain CLI run has nothing to report.

Diagram

Yes — Telegram, Slack, Discord, etc.

No — CLI or one-shot run

Runtime

Gateway running?

✅ gateway_status works

⚠️ Returns no-gateway message

RuntimeBehaviour
Bot / Gateway (Telegram, Slack, Discord, WhatsApp, …)Reads the live snapshot; returns a JSON string
CLI / one-shot (agent.start(...) directly)Returns the string below — does not raise

When no gateway is active the tool returns:

No active gateway: gateway_status is only available inside a running bot/gateway (e.g. Telegram, Slack, Discord). It is unavailable for CLI/one-shot runs.

If the bound source’s snapshot() raises, the tool logs and returns "Error reading gateway status: {e}" — it never raises into the agent turn.


User Interaction Flow

A user in Telegram asks the ops assistant “Are you swamped right now?” The agent calls gateway_status(), sees run: "busy", queued: 3, active_sessions: 12, and replies with a grounded estimate instead of a silent delay.

Diagram
🤖 Ops Assistant📱 User (Telegram)🤖 Ops Assistant📱 User (Telegram){“run”: “busy”, “queued”: 3, …}“Are you swamped right now?”gateway_status()“Handling 12 chats, 3 queued — ~1 min to yours.”

Common Patterns

Proactive backlog warning

python
agent = Agent(
    name="Ops Assistant",
    instructions=(
        "Call gateway_status first. "
        "If queued > 0, preface your reply with how many turns are ahead."
    ),
    tools=[gateway_status],
)

Delivery health check before a critical send

python
from praisonaiagents import Agent
from praisonaiagents.tools import gateway_status, send_message

agent = Agent(
    name="Ops Assistant",
    instructions=(
        "Before sending to a sensitive channel, call gateway_status. "
        "If delivery.dlq > 0 or the target is in delivery.dead_targets, "
        "warn the user before calling send_message."
    ),
    tools=[gateway_status, send_message],
)

Degraded-channel apology

python
agent = Agent(
    name="Ops Assistant",
    instructions=(
        "Call gateway_status. "
        "If the current channel appears in degraded, "
        "apologise proactively for slow delivery."
    ),
    tools=[gateway_status],
)

Best Practices

Use it to warn, not to gate

Report state and continue. Don’t loop until run == "idle" — that stalls the turn. A single call gives the agent enough to set expectations.

Prefer it over polling

One call returns the whole picture — run status, sessions, delivery, and degraded owners. There’s no reason to combine multiple health tools.

Combine with send_message for reliable delivery

Check delivery.dead_targets and delivery.dlq before sending to sensitive channels, so the agent can warn the user first.

Tolerate the no-gateway string in CLI runs

In tests and one-shot runs the tool returns the no-gateway message. Write instructions that handle that string instead of assuming a JSON snapshot.


Related