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:
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). riskis the risk level. It's required; see below.ctxis 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:
- The docstring's
Args:(recommended). Write each line asname(type): description. The type can bestring,number,integer,boolean,objectorarray, or an array with an element type such asarray[string]. - Type annotations. Without
Args:, parameters are built fromstr,int,float,bool,listanddictannotations, but without descriptions the model has a harder time using them correctly. - An explicit schema. For enums, length limits and other constraints, pass a JSON Schema:
@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:
| Level | For | Examples |
|---|---|---|
safe | Read-only, no side effects | Checking the weather, searching, listing files |
normal | Writes data, but with limited reach and can be undone | Saving a note, creating an issue |
sensitive | Affects the outside world, or is hard to undo | Sending email, merging a PR, pushing code |
dangerous | Could have serious consequences | Changing 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:
| Field | Description |
|---|---|
session | The session ID |
actor | The user who started this turn |
owner | Whether it's the owner |
group | Whether it's in a group chat |
background | Whether it's a background task, such as handling a proactive event |
mode | chat or agent |
For example, a tool only the owner may use, in a private chat, can check:
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():
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}