Skip to content

sensai

CHAT_AGENT module-attribute

Python
CHAT_AGENT = 'chat'

The agent of a call the chat agent made itself, which is a hand-off to a specialist. A specialist's own calls carry the specialist's route (job_status, plot_config, ...).

PlotEditFailed

Bases: Exception

The plot agent could not make the change. The message is what to tell the user, and the chat agent is not asked to put it in its own words: a model that was told the change failed would keep sending the same request to the plot agent again.

SensAIDeps dataclass

Python
SensAIDeps(
    job_status: JobStatus | None,
    column_manifest: ColumnManifest,
    current_plot_config: PlotConfig | None,
    plot_edit_refusal: str | None = None,
    trace: ToolTrace | None = None,
    versus: VersusState | None = None,
    versus_trials_added: int = 0,
    max_requests: int = DEFAULT_MAX_REQUESTS,
    max_versus_trials: int = DEFAULT_MAX_VERSUS_TRIALS,
)

Runtime context available to the SensAI chat agent and every domain agent it delegates to.

job_status instance-attribute

Python
job_status: JobStatus | None

The current job, or None if no job is loaded.

column_manifest instance-attribute

Python
column_manifest: ColumnManifest

Signal column names available in the current trial's telemetry data.

current_plot_config instance-attribute

Python
current_plot_config: PlotConfig | None

The plot config currently active in the trial viewer, or None if not set.

plot_edit_refusal class-attribute instance-attribute

Python
plot_edit_refusal: str | None = None

Why the plot agent's latest edit or profile load was refused, or None if it was not. When the model keeps repeating a refused call until it runs out of tries, the chat agent tells the user this instead of the turn failing.

trace class-attribute instance-attribute

Python
trace: ToolTrace | None = None

Where the tool calls of this message are recorded for the chat to show, or None when nothing is watching. The chat agent hands it to each specialist's run, which is how a specialist's own tool calls are seen.

versus class-attribute instance-attribute

Python
versus: VersusState | None = None

Versus mode as the trial viewer has it, or None when the message did not come from a trial viewer. set_versus replaces it, and the router sends the browser the new one if it differs.

versus_trials_added class-attribute instance-attribute

Python
versus_trials_added: int = 0

Trials this message has added to versus mode so far, which max_versus_trials is checked against.

max_requests class-attribute instance-attribute

Python
max_requests: int = DEFAULT_MAX_REQUESTS

dojo.sensai.max_requests. The specialists' runs are given it too, since they share the message's count.

max_versus_trials class-attribute instance-attribute

Python
max_versus_trials: int = DEFAULT_MAX_VERSUS_TRIALS

dojo.sensai.max_versus_trials.

ToolTrace dataclass

Python
ToolTrace(
    emit: Emit | None = None,
    calls: list[ToolCallRecord] = list(),
)

The tool calls one chat message made, from the chat agent and from every specialist it handed the request to.

Each agent's run gets a handler from handler (the chat agent's own goes through tap), which records a call when it starts and its outcome when it ends, and tells emit so the chat can show each one live. calls is the whole list once the message is done.

emit class-attribute instance-attribute

Python
emit: Emit | None = None

Called with tool_start as a call begins and tool_end as it finishes, or None to only record.

calls class-attribute instance-attribute

Python
calls: list[ToolCallRecord] = field(default_factory=list)

Every call so far, in the order it started.

tap async

Python
tap(
    agent: str, events: AsyncIterable[AgentStreamEvent]
) -> AsyncIterator[AgentStreamEvent]

Records the tool calls in events as they pass and gives every event on, unchanged, so a caller that reads the events for something else can use it in place of events.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/tool_trace.py
Python
async def tap(
    self, agent: str, events: AsyncIterable[AgentStreamEvent]
) -> AsyncIterator[AgentStreamEvent]:
    """Records the tool calls in `events` as they pass and gives every event on, unchanged, so a caller that reads the events for something else can use it in place of `events`."""
    async for event in events:
        await self._record(agent, event)
        yield event

handler

Python
handler(
    agent: str,
) -> Callable[
    [RunContext[Any], AsyncIterable[AgentStreamEvent]],
    Awaitable[None],
]

An event_stream_handler for the run of agent that records its tool calls and does nothing else.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/tool_trace.py
Python
def handler(
    self, agent: str
) -> Callable[[RunContext[Any], AsyncIterable[AgentStreamEvent]], Awaitable[None]]:
    """An `event_stream_handler` for the run of `agent` that records its tool calls and does nothing else."""

    async def record(
        _: RunContext[Any], events: AsyncIterable[AgentStreamEvent]
    ) -> None:
        async for _event in self.tap(agent, events):
            pass

    return record

finish

Python
finish() -> None

Marks every call that never returned as failed. Call it when the message is over, since a specialist that gave up or a message that ran out of requests leaves its call open.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/tool_trace.py
Python
def finish(self) -> None:
    """Marks every call that never returned as failed. Call it when the message is over, since a specialist that gave up or a message that ran out of requests leaves its call open."""
    for record in self._running.values():
        record.status = "failed"
    self._running.clear()

usage_limits

Python
usage_limits(max_requests: int) -> UsageLimits

The cap on model requests for one chat message, to pass to the chat agent's run and to each specialist's run so that the specialists count against the same total (they share the run's usage).

max_requests is dojo.sensai.max_requests. A request takes one to three (route it, edit, answer) and a refused edit adds one to three more, so the default of 12 leaves room to correct a mistake or two. When a model loops, or rate limits make every request cost several attempts, it is what stops the message from sending dozens.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/chat_agent.py
Python
def usage_limits(max_requests: int) -> UsageLimits:
    """
    The cap on model requests for one chat message, to pass to the chat agent's run and to each specialist's run so that the specialists count against the same total (they share the run's `usage`).

    `max_requests` is `dojo.sensai.max_requests`. A request takes one to three (route it, edit, answer) and a refused edit adds one to three more, so the default of 12 leaves room to correct a mistake or two. When a model loops, or rate limits make every request cost several attempts, it is what stops the message from sending dozens.
    """
    return UsageLimits(request_limit=max_requests)

build_fallback_model

Python
build_fallback_model() -> FallbackModel

Builds the FallbackModel shared by every SensAI agent from SensAISettings.models, in the priority order the user configured there - the first (provider, model name) pair is tried first, and each later one is only used if every earlier one errors.

Each entry's Model comes from ModelProvider.build_model, which builds that entry's provider exactly as Agent('provider:model') would - reading whatever environment variable that provider looks for by default (see ModelProvider.env_var_name) - and sends its requests to the entry's own base_url when it has one. Every provider is treated alike, Ollama included: an entry with no base_url keeps its provider's own default endpoint.

Raises:

Type Description
ValueError

If SensAISettings.models is empty - FallbackModel needs at least one model to try - or an entry sets a base_url its provider doesn't accept.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/model.py
Python
def build_fallback_model() -> FallbackModel:
    """
    Builds the `FallbackModel` shared by every SensAI agent from `SensAISettings.models`, in the priority order the user configured there - the first `(provider, model name)` pair is tried first, and each later one is only used if every earlier one errors.

    Each entry's `Model` comes from `ModelProvider.build_model`, which builds that entry's provider exactly as `Agent('provider:model')` would - reading whatever environment variable that provider looks for by default (see `ModelProvider.env_var_name`) - and sends its requests to the entry's own `base_url` when it has one. Every provider is treated alike, Ollama included: an entry with no `base_url` keeps its provider's own default endpoint.

    Raises:
        ValueError: If `SensAISettings.models` is empty - `FallbackModel` needs at least one model to try - or an entry sets a `base_url` its provider doesn't accept.

    """
    settings = MujocoMojoSettings().dojo.sensai
    if not settings.models:
        msg = "dojo.sensai.models is empty; configure at least one (provider, model name) pair."
        raise ValueError(msg)

    models = [
        entry.provider.build_model(entry.model_name, base_url=entry.base_url)
        for entry in settings.models
    ]

    return FallbackModel(
        models[0],
        *models[1:],
        # pydantic-ai's Google model only wraps errors.APIError as ModelAPIError when
        # opening the connection, not when the first streamed chunk raises it (the actual
        # 503 case). Include the raw SDK error type too so streaming failures still fall back.
        # This only helps entries that are actually Google models - a non-Google-only
        # fallback chain gets no equivalent coverage for its own provider's raw SDK errors.
        fallback_on=(ModelAPIError, google_errors.APIError),
    )