Skip to content

plot_config_agent

SensAI domain agent for the trial viewer plot: reads the plot config, changes it with small edits, and loads saved profiles.

current_plot async

Python
current_plot(ctx: RunContext[SensAIDeps]) -> str

The plot as it is now, as JSON with every default value left out, so it is short. It is built for every request to the model, so it already shows an edit made a moment ago.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.instructions
async def current_plot(ctx: RunContext[SensAIDeps]) -> str:
    """The plot as it is now, as JSON with every default value left out, so it is short. It is built for every request to the model, so it already shows an edit made a moment ago."""
    config = ctx.deps.current_plot_config
    if config is None:
        return "No plot config is currently loaded."
    return "The plot right now:\n" + json.dumps(compact_plot_config(config))

find_signals async

Python
find_signals(
    ctx: RunContext[SensAIDeps], query: str
) -> list[str] | list[dict[str, str]] | str

Searches this trial's signals by name, and by description where they have one, so a signal can be named exactly.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
query str

Words from the name or from what the signal measures, such as 'box1 xpos' or 'box1 angular velocity'. Case and separators (spaces, /, :, _) do not matter, and every word has to match.

required

Returns:

Type Description
list[str] | list[dict[str, str]] | str

Up to 25 exact signal names containing every word, shortest first; the closest spellings if none contain them all. When the trial's signals have descriptions, each is an object with its name and, where it has one, its description.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool
async def find_signals(
    ctx: RunContext[SensAIDeps], query: str
) -> list[str] | list[dict[str, str]] | str:
    """
    Searches this trial's signals by name, and by description where they have one, so a signal can be named exactly.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        query: Words from the name or from what the signal measures, such as 'box1 xpos' or 'box1 angular velocity'. Case and separators (spaces, `/`, `:`, `_`) do not matter, and every word has to match.

    Returns:
        Up to 25 exact signal names containing every word, shortest first; the closest spellings if none contain them all. When the trial's signals have descriptions, each is an object with its `name` and, where it has one, its `description`.

    """
    columns = ctx.deps.column_manifest["all"]
    if not columns:
        return "No signal list is available, so signal names cannot be checked."
    metadata = ctx.deps.column_manifest["column_metadata"]
    found = _find_signals(columns, query, metadata=metadata)
    logger.info("SensAI find_signals %r: %d match(es)", query, len(found))
    descriptions = {
        c: meta.description
        for c in found
        if (meta := metadata.get(c)) and meta.description
    }
    if not descriptions:
        return found
    return [
        {"name": c, "description": descriptions[c]}
        if c in descriptions
        else {"name": c}
        for c in found
    ]

add_signals async

Python
add_signals(
    ctx: RunContext[SensAIDeps], names: list[str]
) -> str

Plots more signals, each in an automatic color. The signals already plotted stay plotted.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
names list[str]

The exact names of the signals to plot, such as ["Bodies/box2/xvelr:y"]. One that is not a signal of this trial is refused, with the closest real names.

required

Returns:

Type Description
str

Which parts of the plot changed.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool(retries=3)
async def add_signals(ctx: RunContext[SensAIDeps], names: list[str]) -> str:
    """
    Plots more signals, each in an automatic color. The signals already plotted stay plotted.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        names: The exact names of the signals to plot, such as ["Bodies/box2/xvelr:y"]. One that is not a signal of this trial is refused, with the closest real names.

    Returns:
        Which parts of the plot changed.

    """
    config = ctx.deps.current_plot_config
    if config is None:
        return "No plot config is currently loaded, so nothing was changed."
    wanted = list(dict.fromkeys(names))
    if not wanted:
        raise _refusal(ctx, "Name at least one signal to add.")
    return _edit(ctx, "add_signals", config, {"yAxes": {name: {} for name in wanted}})

edit_signal async

Python
edit_signal(
    ctx: RunContext[SensAIDeps],
    name: str,
    changes: dict[str, Any],
) -> str

Changes how one plotted signal is drawn. Whatever you leave out of changes stays as it is.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
name str

The exact name of a signal that is plotted now, such as "Bodies/box1/xvelr:y". To plot one that is not, call add_signals first.

required
changes dict[str, Any]

Only the signal's fields to change, such as {"color": "#ff2056", "width": 4} or {"label": "spin", "dash": "dot"}. The fields are listed under "Signal fields". A color is one from the palette in your instructions. Never null.

required

Returns:

Type Description
str

Which parts of the plot changed.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool(retries=3)
async def edit_signal(
    ctx: RunContext[SensAIDeps], name: str, changes: dict[str, Any]
) -> str:
    """
    Changes how one plotted signal is drawn. Whatever you leave out of `changes` stays as it is.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        name: The exact name of a signal that is plotted now, such as "Bodies/box1/xvelr:y". To plot one that is not, call add_signals first.
        changes: Only the signal's fields to change, such as {"color": "#ff2056", "width": 4} or {"label": "spin", "dash": "dot"}. The fields are listed under "Signal fields". A color is one from the palette in your instructions. Never null.

    Returns:
        Which parts of the plot changed.

    """
    config = ctx.deps.current_plot_config
    if config is None:
        return "No plot config is currently loaded, so nothing was changed."
    if name not in config.y_axes:
        plotted = ", ".join(config.y_axes) or "none"
        raise _refusal(
            ctx,
            f'"{name}" is not plotted, so there is nothing to edit. Plotted signals: '
            f"{plotted}. To plot it, call add_signals.",
        )
    return _edit(ctx, "edit_signal", config, {"yAxes": {name: changes}})

edit_plot_config async

Python
edit_plot_config(
    ctx: RunContext[SensAIDeps], changes: dict[str, Any]
) -> str

Changes plot-wide fields such as the title, grid, axis ranges, legend or x-axis column. Whatever you leave out stays as it is. To add, remove or restyle signals use add_signals, remove_signals and edit_signal instead.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
changes dict[str, Any]

Only the fields to change, such as {"title": "Wheel speed", "grid": "none", "rangeX": [0, 5]} or {"xAxis": {"col": "time"}}. The fields are listed under "Plot-wide fields". Never null, except null for rangeX or rangeY to make a range automatic. A field that does not exist or a value that is not allowed is refused with the reason.

required

Returns:

Type Description
str

Which parts of the plot changed.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool(retries=3)
async def edit_plot_config(ctx: RunContext[SensAIDeps], changes: dict[str, Any]) -> str:
    """
    Changes plot-wide fields such as the title, grid, axis ranges, legend or x-axis column. Whatever you leave out stays as it is. To add, remove or restyle signals use add_signals, remove_signals and edit_signal instead.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        changes: Only the fields to change, such as {"title": "Wheel speed", "grid": "none", "rangeX": [0, 5]} or {"xAxis": {"col": "time"}}. The fields are listed under "Plot-wide fields". Never null, except null for rangeX or rangeY to make a range automatic. A field that does not exist or a value that is not allowed is refused with the reason.

    Returns:
        Which parts of the plot changed.

    """
    config = ctx.deps.current_plot_config
    if config is None:
        return "No plot config is currently loaded, so nothing was changed."
    return _edit(ctx, "edit_plot_config", config, changes)

remove_signals async

Python
remove_signals(
    ctx: RunContext[SensAIDeps], names: list[str]
) -> str

Stops plotting signals. The signals that are not named stay plotted.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
names list[str]

The exact names of the plotted signals to stop plotting, such as ["Bodies/box2/xvelr:y"].

required

Returns:

Type Description
str

Which parts of the plot changed.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool(retries=3)
async def remove_signals(ctx: RunContext[SensAIDeps], names: list[str]) -> str:
    """
    Stops plotting signals. The signals that are not named stay plotted.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        names: The exact names of the plotted signals to stop plotting, such as ["Bodies/box2/xvelr:y"].

    Returns:
        Which parts of the plot changed.

    """
    config = ctx.deps.current_plot_config
    if config is None:
        return "No plot config is currently loaded, so nothing was changed."
    logger.info("SensAI remove_signals: %s", names)
    try:
        edited = remove_plot_signals(config, names)
    except PlotConfigDeltaError as exc:
        logger.info("SensAI remove_signals refused: %s", exc)
        raise _refusal(ctx, str(exc)) from exc
    ctx.deps.plot_edit_refusal = None
    return _commit(ctx, config, edited)

current_versus async

Python
current_versus(ctx: RunContext[SensAIDeps]) -> str | None

Versus mode as it is now, rebuilt for every request so it shows a change made a moment ago. Nothing when there is no trial viewer to change it.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.instructions
async def current_versus(ctx: RunContext[SensAIDeps]) -> str | None:
    """Versus mode as it is now, rebuilt for every request so it shows a change made a moment ago. Nothing when there is no trial viewer to change it."""
    if ctx.deps.versus is None:
        return None
    job = ctx.deps.job_status
    return describe_versus(
        ctx.deps.versus, list(job.trial_nums) if job is not None else None
    )

set_versus async

Python
set_versus(
    ctx: RunContext[SensAIDeps],
    enabled: bool | None = None,
    trial_range: list[int] | None = None,
    no_range: bool = False,
    pin: list[int] | None = None,
    unpin: list[int] | None = None,
    failed_requirement: str | None = None,
    input_outliers: str | None = None,
    min_sigma: float = 2.0,
    clear_pins: bool = False,
) -> str

Changes versus mode, which draws other trials' traces behind the open trial's. What you leave out stays as it is, and pinned trials are added to the ones pinned already.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
enabled bool | None

True to show the comparison traces and false to turn versus mode off, such as true. Leave it out to keep it as it is: pinning trials or setting a range turns it on by itself.

None
trial_range list[int] | None

The first and last trial number to compare, such as [3, 9]. It replaces the range from before. Leave it out to keep the range.

None
no_range bool

True to compare only the pinned trials, with no range, such as true. Use it with pin or failed_requirement when the user wants only those trials.

False
pin list[int] | None

Trial numbers the user named, to add to the pinned ones, such as [12, 15]. For the trials that failed a requirement use failed_requirement, and for the ones that drew an input far from its mean use input_outliers; never write those numbers yourself.

None
unpin list[int] | None

Trial numbers to stop comparing, such as [12].

None
failed_requirement str | None

Pins the trials that missed a requirement, found by the server. A requirement's name or part of it, such as "touchdown_speed", or "any" for the trials that missed any requirement, or "error" for the trials that crashed.

None
input_outliers str | None

Pins the trials that drew a sampled input far from its mean, found by the server. The input's name or part of it, such as "wind_speed". How far is min_sigma.

None
min_sigma float

How many standard deviations from its mean an input must have been drawn for input_outliers to pin the trial, such as 2 (the default) or 3. It is only used with input_outliers.

2.0
clear_pins bool

True to drop every pinned trial first, such as true, when the user wants other trials instead of the ones shown now.

False

Returns:

Type Description
str

What versus mode is set to now, and how many trials were left out if there were too many to add in one message.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool(retries=3)
async def set_versus(
    ctx: RunContext[SensAIDeps],
    enabled: bool | None = None,
    trial_range: list[int] | None = None,
    no_range: bool = False,
    pin: list[int] | None = None,
    unpin: list[int] | None = None,
    failed_requirement: str | None = None,
    input_outliers: str | None = None,
    min_sigma: float = 2.0,
    clear_pins: bool = False,
) -> str:
    """
    Changes versus mode, which draws other trials' traces behind the open trial's. What you leave out stays as it is, and pinned trials are added to the ones pinned already.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        enabled: True to show the comparison traces and false to turn versus mode off, such as true. Leave it out to keep it as it is: pinning trials or setting a range turns it on by itself.
        trial_range: The first and last trial number to compare, such as [3, 9]. It replaces the range from before. Leave it out to keep the range.
        no_range: True to compare only the pinned trials, with no range, such as true. Use it with pin or failed_requirement when the user wants only those trials.
        pin: Trial numbers the user named, to add to the pinned ones, such as [12, 15]. For the trials that failed a requirement use failed_requirement, and for the ones that drew an input far from its mean use input_outliers; never write those numbers yourself.
        unpin: Trial numbers to stop comparing, such as [12].
        failed_requirement: Pins the trials that missed a requirement, found by the server. A requirement's name or part of it, such as "touchdown_speed", or "any" for the trials that missed any requirement, or "error" for the trials that crashed.
        input_outliers: Pins the trials that drew a sampled input far from its mean, found by the server. The input's name or part of it, such as "wind_speed". How far is min_sigma.
        min_sigma: How many standard deviations from its mean an input must have been drawn for input_outliers to pin the trial, such as 2 (the default) or 3. It is only used with input_outliers.
        clear_pins: True to drop every pinned trial first, such as true, when the user wants other trials instead of the ones shown now.

    Returns:
        What versus mode is set to now, and how many trials were left out if there were too many to add in one message.

    """
    state = ctx.deps.versus
    if state is None:
        return "Versus mode cannot be changed now: no trial is open in the trial viewer. Tell the user to open a trial and ask again."
    logger.info(
        "SensAI set_versus: %s",
        json.dumps(
            {
                "enabled": enabled,
                "trial_range": trial_range,
                "no_range": no_range,
                "pin": pin,
                "unpin": unpin,
                "failed_requirement": failed_requirement,
                "input_outliers": input_outliers,
                "min_sigma": min_sigma,
                "clear_pins": clear_pins,
            },
            default=str,
        )[:500],
    )
    job = ctx.deps.job_status
    known = list(job.trial_nums) if job is not None else None
    pins = list(pin or [])
    changes_something = bool(
        enabled is not None
        or trial_range is not None
        or no_range
        or pin
        or unpin
        or clear_pins
    )
    found_none: list[str] = []
    if failed_requirement:
        if job is None:
            return "No job is loaded, so there are no failed trials to look up. Pin the trial numbers the user names instead."
        found = trials_that_missed(job, failed_requirement)
        if isinstance(found, str):
            return found
        if not found:
            found_none.append(f"no trial missed '{failed_requirement}'")
        pins += found
    if input_outliers:
        if job is None:
            return "No job is loaded, so there are no sampled inputs to look up. Pin the trial numbers the user names instead."
        # reads every trial's saved draws, so it is kept off the event loop
        found = await asyncio.to_thread(trials_beyond, job, input_outliers, min_sigma)
        if isinstance(found, str):
            return found
        if not found:
            found_none.append(
                f"no trial drew '{input_outliers}' {min_sigma:g} or more standard deviations from its mean"
            )
        pins += found
    if found_none and not (pins or changes_something):
        nothing = ", and ".join(found_none) + ", so there is nothing to show."
        return nothing[0].upper() + nothing[1:]
    room = max(0, ctx.deps.max_versus_trials - ctx.deps.versus_trials_added)
    try:
        change = change_versus(
            state,
            room=room,
            known=known,
            enabled=enabled,
            trial_range=trial_range,
            no_range=no_range,
            pin=pins,
            unpin=unpin or [],
            clear_pins=clear_pins,
        )
    except VersusError as exc:
        logger.info("SensAI set_versus refused: %s", exc)
        raise _refusal(ctx, str(exc)) from exc
    ctx.deps.plot_edit_refusal = None
    ctx.deps.versus = change.state
    ctx.deps.versus_trials_added += change.added
    if change.state == state:
        text = "Nothing changed: versus mode already has those values."
    else:
        text = f"Done. {describe_versus(change.state, known)}"
    if change.left_out:
        text += (
            f" {change.left_out} more trial{'s were' if change.left_out != 1 else ' was'} not added: "
            f"one message adds at most {ctx.deps.max_versus_trials} comparison trials "
            "(dojo.sensai.max_versus_trials in settings). Tell the user how many were left out "
            "and that asking again adds the next batch."
        )
    return text

describe_filters async

Python
describe_filters(
    ctx: RunContext[SensAIDeps],
    filter_type: str | None = None,
) -> str

Describes the filters a signal or the x-axis can have.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
filter_type str | None

One filter type from the list, to get its parameters and how to write it. Leave it out to list every type.

None

Returns:

Type Description
str

The list of filter types, or the one type's parameters.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool
async def describe_filters(
    ctx: RunContext[SensAIDeps], filter_type: str | None = None
) -> str:
    """
    Describes the filters a signal or the x-axis can have.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        filter_type: One filter type from the list, to get its parameters and how to write it. Leave it out to list every type.

    Returns:
        The list of filter types, or the one type's parameters.

    """
    return filter_catalog(await get_filter_schema(), filter_type)

list_saved_plot_configs

Python
list_saved_plot_configs() -> list[str]

List the names of every saved plot config profile.

Returns:

Type Description
list[str]

Every saved profile's name (including sub-folder paths, e.g. 'robotics/baseline'), most recently modified first.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool_plain
def list_saved_plot_configs() -> list[str]:
    """
    List the names of every saved plot config profile.

    Returns:
        Every saved profile's name (including sub-folder paths, e.g. 'robotics/baseline'), most recently modified first.

    """
    d = _get_profiles_dir()
    return [
        f.relative_to(d).with_suffix("").as_posix()
        for f in sorted(
            d.rglob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True
        )
    ]

load_plot_config async

Python
load_plot_config(
    ctx: RunContext[SensAIDeps], name: str
) -> str

Load a previously saved plot config profile by name, replacing the plot with it.

Parameters:

Name Type Description Default
ctx RunContext[SensAIDeps]

The run context holding the dashboard state; it is not something you send.

required
name str

The profile name to load, e.g. 'robotics/baseline'.

required

Returns:

Type Description
str

What was loaded.

Raises:

Type Description
ModelRetry

If no profile with this name exists, so the caller can retry with a corrected name.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/plot_config_agent.py
Python
@plot_config_agent.tool
async def load_plot_config(ctx: RunContext[SensAIDeps], name: str) -> str:
    """
    Load a previously saved plot config profile by name, replacing the plot with it.

    Args:
        ctx: The run context holding the dashboard state; it is not something you send.
        name: The profile name to load, e.g. 'robotics/baseline'.

    Returns:
        What was loaded.

    Raises:
        ModelRetry: If no profile with this name exists, so the caller can retry with a corrected name.

    """
    path = _resolve_profile_path(name)
    if not path.exists():
        raise _refusal(ctx, f"No saved profile named {name!r} found.")
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        profile = _parse_profile(data, name)
    except (json.JSONDecodeError, ValidationError) as exc:
        raise _refusal(
            ctx, f"Profile {name!r} failed validation and cannot be loaded: {exc}"
        ) from exc
    config = profile.tabs[profile.active_tab_index].config
    ctx.deps.plot_edit_refusal = None
    ctx.deps.current_plot_config = config
    return f"Loaded {name!r}: it plots {len(config.y_axes)} signal(s)."