Skip to content

AI Steering Directives & Fallback Chains

Steering directives let you dynamically control an active AI tool loop from external code — hooks, other channels, or background tasks. Combined with fallback provider chains, they give you fine-grained control over AI behavior in production.

Quick Start

from __future__ import annotations

from roomkit.models import Cancel, InjectMessage, UpdateSystemPrompt

# Every steer names the room whose turn it is for
# Cancel the agent's running turns in the room
await kit.steer("room-a", "ai-assistant", Cancel(reason="user_left"))

# Inject context between tool rounds
await kit.steer(
    "room-a", "ai-assistant", InjectMessage(content="User just uploaded a document.", role="user")
)

# Append to the system prompt
await kit.steer(
    "room-a", "ai-assistant", UpdateSystemPrompt(append="\nIMPORTANT: User is a VIP customer.")
)

Directive Types

Cancel

Stops the current tool loop. Sets a fast-path cancel event so the loop exits without waiting for the next round.

Cancel(reason="timeout")       # reason is logged
Cancel(reason="user_disconnected")

InjectMessage

Adds a message to the AI context between tool rounds. The AI sees it on the next generation call.

InjectMessage(content="New data available: Q4 revenue is $2.3M", role="user")
InjectMessage(content="Remember to check permissions first.", role="system")
Field Default Description
content required Message text to inject
role "user" Message role ("user" or "system")

UpdateSystemPrompt

Appends text to the system prompt between tool rounds. Useful for dynamic context injection.

UpdateSystemPrompt(append="\n\nUser language preference: French")
UpdateSystemPrompt(append="\n\nNew policy: all refunds require manager approval.")

How It Works

Each AI tool loop creates an isolated _ToolLoopContext with its own steering queue and cancel event. Directives flow through two checkpoints:

┌─────────────────────────────────────────────────────┐
│                   Tool Loop                          │
│                                                      │
│  ┌──────────────────┐                                │
│  │ Checkpoint 1     │  Fast-path cancel check        │
│  │ (before generate)│  before expensive API call     │
│  └────────┬─────────┘                                │
│           ▼                                          │
│  ┌──────────────────┐                                │
│  │ AI Generation    │  Provider API call             │
│  └────────┬─────────┘                                │
│           ▼                                          │
│  ┌──────────────────┐                                │
│  │ Tool Execution   │  Run tools in parallel         │
│  └────────┬─────────┘                                │
│           ▼                                          │
│  ┌──────────────────┐                                │
│  │ Checkpoint 2     │  Drain full queue: apply       │
│  │ (after tools)    │  Cancel, Inject, UpdatePrompt  │
│  └────────┬─────────┘                                │
│           ▼                                          │
│      Next round...                                   │
└─────────────────────────────────────────────────────┘
  • Checkpoint 1: Fast cancel check — avoids expensive API calls if already cancelled
  • Checkpoint 2: Full queue drain — applies all pending directives to the context
  • After the answer: once the model has answered, the loop reads its queue one last time. An InjectMessage that came while the model wrote the answer has the same turn ask the model again, the answer then the message, so nothing steer() counted goes unread; with none, the loop is reached no more and steer() returns 0 for it.

Writing to an Agent While It Works

A host that lets a person write while the agent works (a coding agent's terminal, say) builds the agent with steer_room_turns=True and sends the person's message as any message:

coder = Agent("coder", provider=provider, tools=[list_files], steer_room_turns=True)

await kit.process_inbound(
    InboundMessage(channel_id="ws", sender_id="dev", content=TextContent(body="Only the .py files.")),
    room_id="session",
)

The message is stored in the room, passes the hooks and the permissions, and, while the agent's turn runs in the room, is handed to that turn rather than starting a second turn beside it: the model reads it before its next round, or the same turn asks the model again once it has answered. The agent's turns in the room run one after the other (serialize_room_turns, which it implies), so a message that comes before the turn can be reached waits a turn of its own, which reads the first turn's answer. In a room where several people speak, the turn reads the message under its speaker's label. Runnable: examples/agent_steered_turn.py.

The steer() method is safe to call from any async context. Cancel directives also set the fast-path event for immediate exit.

Practical Patterns

Cancel on User Disconnect

from __future__ import annotations

from roomkit import HookTrigger
from roomkit.models import Cancel

@kit.hook(HookTrigger.ON_SESSION_ENDED)
async def cancel_on_disconnect(event, ctx):
    ai = kit.get_channel("ai-assistant")
    # The channel serves every room it is bound to: stop this room's turns only.
    ai.steer(Cancel(reason="user_disconnected"), room_id=ctx.room.id)

Inject Real-Time Context from Another Channel

from __future__ import annotations

from roomkit import HookTrigger, ChannelType
from roomkit.models import InjectMessage
from roomkit.tools import fence

@kit.hook(HookTrigger.BEFORE_BROADCAST, channel_types={ChannelType.SMS})
async def inject_sms_context(event, ctx):
    ai = kit.get_channel("ai-assistant")
    ai.steer(
        InjectMessage(
            # The sender's words in a block they cannot close (RFC §6.4).
            content="An SMS was received:\n" + fence("message", event.content.body),
            role="user",
        ),
        room_id=event.room_id,
    )

Dynamic VIP System Prompt

from __future__ import annotations

from roomkit.models import UpdateSystemPrompt

async def on_vip_detected(room_id: str, participant_id: str):
    ai = kit.get_channel("ai-assistant")
    ai.steer(
        UpdateSystemPrompt(
            append=f"\n\nUser {participant_id} is a VIP. Prioritize their requests."
        ),
        room_id=room_id,
    )

Target a Room or a Loop

One channel object serves every room it is bound to, so its running loops can belong to several members' turns at once. A directive names exactly one of the room, the loop or the turn it is for (RFC §21.3):

# A member's Stop: every loop of their room, and no other room's
reached = ai.steer(Cancel(reason="stop pressed"), room_id="room-a")

# Another directive reaches the room's most recent loop
ai.steer(InjectMessage(content="The user attached a file."), room_id="room-a")

# Or one loop by its id
ai.steer(Cancel(reason="timeout"), loop_id="loop-abc123")

steer() returns how many loops it reached. Naming none of loop_id, room_id and turn_id, or several, raises ValueError: the most recent loop may be another member's turn. A loop is reachable once its turn has started (its response stream is read): a directive that comes before reaches none, and steer() returns 0. See examples/ai_shared_agent_rooms.py.

Steering through the kit

Every agent turn runs through the kit's turn backend (RFC §10.6), in the kit's process by default and, with a distributed backend, wherever an executor runs it. kit.steer(room_id, channel_id, directive) reaches the turns the kit started in that room, wherever they run, under the same rules:

reached = await kit.steer("room-a", "ai-assistant", Cancel(reason="stop pressed"))
await kit.steer("room-a", "ai-assistant", InjectMessage(content="The user attached a file."))

It answers the loops it reached. A channel without steering of its own (an ACP agent) takes a Cancel as its turn's cancel, which counts as one; any other directive reaches nothing there. With kit.steer(..., organization_id=...) (RFC §17.2), a room of another organization raises RoomNotFoundError. ai.steer() reaches the loops running in the process it is called in: the channel holds no store, and the kit's steer() is the door that reads the room.

One turn of the room is addressed by its id, which a tool or a hook of that turn reads with current_turn_id(); a turn of another room is reached by nothing:

from roomkit import current_turn_id

turn_id = current_turn_id()          # inside a tool call or a hook of the turn
await kit.steer("room-a", "ai-assistant", InjectMessage(content="Budget is 100."), turn_id=turn_id)

A channel that overrides steer() receives turn_id= from the kit; an override without that keyword is given the turn's room_id instead.

A directive reaches the turns that have started. To stop the turns of one message, whether they have started or not (a task waiting behind another in the same room), cancel that message's delivery instead of steering its room: result.delivery.cancel(), or kit.cancel_delivery(key) for a message sent with delivery_key=key (see Cancelling a Delivery). The room's other turns go on.

An agent built with serialize_room_turns=True runs its turns in a room one after the other: a task waits behind the one before it and starts once that answer is written, reading it (see An agent's turns one after the other). A Cancel reaches the running turn only: stop a waiting task by cancelling its delivery.

Fallback Provider Chain

A fallback provider is a router (router=, see A provider per turn): FallbackRouter starts every turn on the primary and hands a generation to the fallback once its retries are spent:

from __future__ import annotations

from roomkit.channels import AIChannel, FallbackRouter
from roomkit.models import RetryPolicy
from roomkit.providers.anthropic import AnthropicAIProvider, AnthropicConfig
from roomkit.providers.openai import OpenAIAIProvider, OpenAIConfig

primary = AnthropicAIProvider(AnthropicConfig(api_key="...", model="claude-opus-5"))
fallback = OpenAIAIProvider(OpenAIConfig(api_key="...", model="gpt-4o"))

ai = AIChannel(
    "ai-assistant",
    router=FallbackRouter(primary, fallback),
    retry_policy=RetryPolicy(max_retries=2, base_delay_seconds=1.0),
)

Fallback Flow

Primary provider
  ├─ Success → return response
  ├─ Retryable error (408, 409, 429, 5xx, lost connection) → retry with backoff
  │     ├─ Retry succeeds → return response
  │     └─ All retries exhausted → try fallback
  │           ├─ Fallback succeeds → return response
  │           └─ Fallback fails → raise original error
  └─ Non-retryable error (other 4xx, unreadable body) → fail immediately (skip fallback)

Works for both streaming and non-streaming generation. A turn the fallback served stays on it for its later rounds; a generation it fails is handed back to the primary, once its own retries are spent.

The fallback receives the rounds the primary already ran in the turn, in a form its vendor takes. A reasoning block without a signature (DeepSeek, Qwen, vLLM and every vendor but Anthropic) does not go to Anthropic, which refuses it and takes the round without it. A round of the current turn none of whose calls carries a thought signature goes to a Gemini 3 model as text (what the primary said, each call, each result with its images), since Gemini 3 refuses a call it did not sign in the current turn; an earlier turn's round keeps its form. Both were measured on the vendors' APIs (2026-10-03).

Retry Policy

from roomkit.models import RetryPolicy

policy = RetryPolicy(
    max_retries=3,
    base_delay_seconds=1.0,
    exponential_base=2.0,
    max_delay_seconds=30.0,
)
Field Default Description
max_retries 0 Maximum retry attempts
base_delay_seconds 1.0 Initial delay between retries
exponential_base 2.0 Backoff multiplier
max_delay_seconds 30.0 Maximum delay cap

Delay formula: min(base_delay * exponential_base^attempt, max_delay)

Tool Loop Configuration

ai = AIChannel(
    "ai",
    provider=provider,
    max_tool_rounds=50,             # Max tool loop iterations (default: 50)
    tool_loop_timeout_seconds=300,   # Hard timeout in seconds (default: 300)
    tool_loop_warn_after=25,         # Soft warning at this round count (default: 25)
)
Parameter Default Description
max_tool_rounds 50 Maximum iterations before forced stop
tool_loop_timeout_seconds 300.0 Hard timeout (seconds). None disables
tool_loop_warn_after 25 Log warning at this round count

Testing

from __future__ import annotations

from roomkit.channels import AIChannel
from roomkit.models import Cancel, InjectMessage
from roomkit.providers.ai import MockAIProvider

ai = AIChannel("ai", provider=MockAIProvider(responses=["Hello"]))

# Verify steer enqueues correctly
# (requires an active loop — see test_ai_steering.py for full patterns)

Tip

The MockAIProvider with preset responses is ideal for testing steering behavior without API calls. See tests/test_channels/test_ai_steering.py for comprehensive test patterns.