Docs contents

LLM tools

Let the model call functions in your plugin.

Users type commands themselves; tools are for the model. When a user asks "Will it rain in London tomorrow?", the model decides on its own to call your weather tool, then writes its reply from the result.

One of ShiritaiBot's design principles is "everything is a tool". Tools give the LLM more freedom, so ShiritaiBot can handle more work through natural language.

Register a tool

Decorate a method with @hook.llm_tool:

main.py
from shiritaibot.api import Plugin, ToolContext, hook


class Weather(Plugin):
    @hook.llm_tool("weather_query", risk="safe", chat=True)
    async def weather_query(self, ctx: ToolContext, city: str, days: int = 1):
        """Get the weather forecast for a city for the next few days.

        Args:
            city(string): City name, such as "London"
            days(integer): Number of days, 1 to 7
        """
        forecast = await self.fetch(city, days)
        return {"city": city, "forecast": forecast}
  • The first argument is the tool name, which the model calls the tool by. Tool names must be unique across all plugins, so prefix them with your plugin's name. Without it, the method name is used.
  • The docstring before Args: is the tool description. The model relies on it to decide when to call the tool, so say clearly what the tool does. The part after it defines the tool's parameters (see below).
  • risk is the risk level. It's required; see below.
  • ctx is the context of this call. The parameters after it are filled in by the model.

Parameters

ShiritaiBot works out a tool's parameters from these, in order:

  1. The docstring's Args: (recommended). Write each line as name(type): description. The type can be string, number, integer, boolean, object or array, or an array with an element type such as array[string].
  2. Type annotations. Without Args:, parameters are built from str, int, float, bool, list and dict annotations, but without descriptions the model has a harder time using them correctly.
  3. An explicit schema. For enums, length limits and other constraints, pass a JSON Schema:
main.py
@hook.llm_tool(
    "note_save",
    risk="normal",
    description="Save a note",
    parameters={
        "type": "object",
        "properties": {
            "title": {"type": "string", "maxLength": 100},
            "tag": {"type": "string", "enum": ["work", "life", "study"]},
        },
        "required": ["title"],
        "additionalProperties": False,
    },
)
async def note_save(self, ctx: ToolContext, title: str, tag: str = "life"):
    ...

Parameters without a default are marked required. The model's arguments are checked against the definition first; when they don't fit, the tool isn't called and the model gets an error message.

Risk levels

Every tool must declare a risk level, and ShiritaiBot sets the tool's default permission from it:

LevelForExamples
safeRead-only, no side effectsChecking the weather, searching, listing files
normalWrites data, but with limited reach and can be undoneSaving a note, creating an issue
sensitiveAffects the outside world, or is hard to undoSending email, merging a PR, pushing code
dangerousCould have serious consequencesChanging repository settings, deleting data

The risk level sets the tool's default permission in the permission presets. In the WebUI, users can set each tool to denied, manual approval, auto-approved by a model, or no approval; the risk level only decides the default.

Declare your tools' risk levels honestly. A tool that sends email but is marked safe could be called without the user knowing. If you're unsure of a tool's risk level, use sensitive: by default it needs the user's approval, and the user can loosen its permission themselves.

Use in Chat mode

By default, plugin tools are only offered to the model in Agent mode. If your tool is read-only and useful in everyday conversation (such as checking the weather), add chat=True so it's available in Chat mode too, for example in group chats.

Call context

ctx is a ToolContext, which tells you who called the tool and where:

FieldDescription
sessionThe session ID
actorThe user who started this turn
ownerWhether it's the owner
groupWhether it's in a group chat
backgroundWhether it's a background task, such as handling a proactive event
modechat or agent

For example, a tool only the owner may use, in a private chat, can check:

main.py
if not ctx.owner or ctx.group:
    raise PublicError("Only the owner can use this tool, in a private chat")

Results and errors

A tool can return a string, number, dict or list, which ShiritaiBot converts to JSON for the model. What you return enters the model's context, so return only what the model needs. Don't pass a whole API response through as it is: that wastes a lot of tokens and makes the logs nearly unreadable.

On errors, raise PublicError. Its message is passed to the model as is, so the model can adjust its arguments or explain to the user. Any other exception only tells the model "Tool failed", with the details in the log, so internal information doesn't leak. So when you design a tool, make its error messages clear enough for the model to see what went wrong, without flooding the context.

Tools run for at most 60 seconds by default. Change this with timeout, as in @hook.llm_tool("slow_job", risk="normal", timeout=300).

Register dynamically

When whether to register a tool depends on the settings, call register_tool() in initialize():

main.py
from shiritaibot.api import Plugin, TEXT, schema


class Notes(Plugin):
    async def initialize(self):
        if self.config["allow_write"]:
            self.context.register_tool(
                "note_save",
                "Save a note",
                schema({"text": TEXT}, required=["text"]),
                self.save,
                risk="normal",
            )

    async def save(self, ctx, args):
        ...
        return {"saved": True}