My proposal as better alternative than tools_as_service
📝 Markdown RenderedThe amount of tools that an AI agent can use are often limited by provider. For OpenAI (for people still using that garbage) it is around 125 last time I checked.
Besides that, all that tool information costs a lot of context while only a few are interesting for the model every time.
So, here my proposal.
Dynamic Tool Sections and BM25 Tool Search: Concept Specification
Status: normative specification. This document is authoritative. Where anything else (chat history, earlier drafts, a model's memory) conflicts with this document, this document wins.
1. Purpose
Replace the agent_as_tool delegation pattern for tool-set management.
agent_as_tool is used to spare context and to expose more functions than a backend can handle in one schema. It is slow, it loses data, it causes duplicate calls, it costs resources, and it loses context. This specification defines a cheaper and more reliable mechanism with the same benefit.
The mechanism: one meta-tool that lets a model change its tool category (section), search for tools with BM25 plus fuzzy matching, and mount exact tools by name. The resulting set is the default toolset for the rest of the session until changed again, or forced per turn where correctness beats cost.
Three ways to obtain tools, one function:
- Sections: predefined, described for the model, picked by name.
- BM25 plus fuzzy keyword search across all tools.
- Hard defaults: a small forced set that is always available.
2. Goals
- Cut context cost of tool schemas to roughly a section description plus the forced set.
- Keep a single actor: the model keeps its own conversation, no sub-agent round trip.
- Eliminate duplicate calls and data loss caused by the parent/delegate boundary.
- Make the model choose tools deterministically from a small, well described menu.
- Survive restarts: the resolved toolset is persistent per session.
- Have a search path for tools the model does not know exist.
3. Non-goals
- Not a sub-agent mechanism.
- Not a permissions or sandbox system. Access control stays where it already is.
- Not a workflow engine. No chaining or planning inside the meta-tool.
- Not a replacement for well named tools. Poor tool names still hurt.
4. The meta-tool
The only added tool the model sees, plus two always-present listing helpers.
use_tools(
section: str | None = None, # pick a section by name
query: str | None = None, # BM25 plus fuzzy search across all tools
tools: list[str] | None = None, # explicit tool names to mount
mode: str = None, # "replace" | "add"; defaults per call type, see 4.3
) -> dict
4.1 Always injected
use_toolslist_sections()list_tools(section: str | None = None)
These three are injected by the harness and are never part of a section definition and can never be unmounted.
4.2 Argument semantics
section="data"resolves the section, mounts its tools plus the forced set.query="send email"runs BM25 plus fuzzy, mounts the top k hits, default semanticsadd.tools=["gmail_send"]mounts exact names. Unknown names are rejected with suggestions.- At least one of
section,query,toolsmust be given. More than one is rejected. modeoverrides the default for that call type.
4.3 Default modes
section: defaultreplace. The mounted set becomes forced set plus the section.query: defaultadd. Search results do not evict what is already mounted.tools: defaultadd.replacenever removes forced tools.addnever removes anything.
4.4 Return payload
Short and structured. This is the only feedback channel, so it must be complete and honest.
{
"ok": true,
"section": "data",
"mounted": ["shell", "read_file", "write_file", "record_read", "record_search"],
"forced": ["shell", "read_file", "write_file"],
"sections_available": [{"name": "data", "description": "..."}],
"suggestions": ["record_read", "record_save"],
"error": null
}
Rules:
- If a tool name is not in
mounted, it is not available. - Unknown section, unknown tool, cap exceeded, budget exceeded:
ok: false, everything else in the payload still filled in, plus a suggestion list. - No silent failure and no partial success without reporting it.
5. Section registry
Declarative data, loaded at start, validated before use.
sections:
data:
description: >
Reading and writing stored records, tables and exports. Use when the user asks about
stored data, reports, lists, CSV or JSON. Examples: "show my saved records",
"export the last month as CSV".
keywords: [records, tables, export, csv, json, data]
tools: [record_search, record_read, record_save, export_csv]
forced: false
comms:
description: >
Sending and reading messages, email and chat. Use for anything that reaches another
person. Examples: "email Jan the report", "what did she reply".
keywords: [email, message, chat, inbox, send]
tools: [send_message, read_inbox, search_inbox]
forced: false
core:
description: Always available core tools.
keywords: [core, base]
tools: [shell, read_file, write_file]
forced: true
5.1 Field rules
description: what jobs the section takes, plus 1 to 2 example user requests. Written for the model, not for humans. Mandatory.keywords: extra search vocabulary, editable without code. Mandatory, minimum 1.tools: 5 to 10 tools. Hard cap enforced at load time. Mandatory.forced: boolean, default false. Forced sections are always mounted and never replaced.- Section names are unique, lowercase, and stable, they are part of the public interface.
5.2 Validation at load time
Every check below fails startup, not runtime:
- No unknown tool names.
- No duplicate tool inside a section.
- Section size within cap.
- Description present and above a minimum length.
- Keywords present.
- Tool appears in at most one non-forced section unless the duplicate is explicitly declared allowlisted.
- Forced set size within cap.
use_toolsand the listing helpers are not in any section.
5.3 Design rules for sections
- Mutually exclusive: two plausible sections is a model ping-pong bug waiting to happen.
- Small: 5 to 10 tools. Discrimination collapses above that.
- Described by job, not by vendor. "Messages" beats "gmail and slack".
6. Hard defaults
- The forced set is mounted on every turn, in every mode, and survives
replace. - Keep the forced set to 3 to 6 tools. Every forced tool is permanent context cost.
- Rule for admission to the forced set: the tool is needed on almost every turn, and the model breaks or stalls without it. Typical: shell, read_file, write_file.
- Forced sections (
forced: true) are equivalent to listing their tools in the forced set. - Forced tools can never be removed, only added to.
- The forced set is resolved from the registry at start and cached in session state.
7. BM25 and fuzzy search
7.1 Index
Built once per start over every tool in every section.
Indexed fields, with weights (weights are tunable constants):
- Tool name: highest weight.
- Tool keywords: high.
- Tool description: medium.
- Parameter names: low.
- Section name and section keywords: medium.
Tokenization: lowercase, split on non-alphanumeric, drop single characters, optional light stemming later. No external dependency, no server.
7.2 BM25 parameters
- Standard BM25 with
k1 = 1.5,b = 0.75. Constants live in one place. - Score is the sum of weighted per-field scores.
- Normalize the BM25 score per query so the fuzzy blend is scale free.
7.3 Fuzzy
difflib.SequenceMatcherover the tool name and over query tokens.- Catches typos and stemming misses that BM25 alone drops.
- Combined score:
final = 0.7 * bm25_norm + 0.3 * fuzzy. Decimals are tuning knobs, not law.
7.4 Result rules
- Top k default 8, hard cap 12.
- A score floor, so a nonsense query returns nothing instead of random hits.
- Balanced selection: at most 3 tools from the same section in a search payload, so a broad query does not silently mount ten tools from one section.
- Empty or whitespace query is rejected, not run.
- Deterministic: same query and same index produce the same list. This is required so tests can run without a model.
7.5 Synonyms
- A small explicit dictionary, for example mail to email, save to write, find to search, msg to message.
- Applied at query expansion time.
- Kept small on purpose. When it grows past a screen it becomes a maintenance bug farm.
7.6 Section search
- Sections are indexed too, so a section name can be resolved fuzzily.
- A query that clearly matches one section resolves to that section, and the return payload names it.
8. Session state
Per session: (chat id, bot id) in GRR.
{
"section": "data" | None,
"mounted": ["shell", "read_file", "write_file", "record_read"],
"forced": ["shell", "read_file", "write_file"],
"mode": "sticky" | "per_turn",
"history": [{"at": ts, "action": "section", "arg": "data", "result": "ok"}],
}
8.1 Resolution per turn
- Effective schema = forced set union mounted set union the three meta-tools.
- No re-resolution cost unless state changed, the resolved set is cached.
sticky, the default: the mounted set persists for the rest of the session.per_turn: after the turn ends, the mounted set resets to the forced set.
8.2 Persistence
- Store in SQLite, keyed on chat id and bot id.
- On restart, re-mount the stored set. Validate names against the current registry first.
- A stored name that no longer exists is dropped and reported in the next tool result, never silently.
9. What the model sees
One compact block in the system prompt, generated from the registry:
Tools: use use_tools to load a section or search for tools.
Sections: data - stored records, tables, exports. comms - email, messages, chat.
Always available: shell, read_file, write_file.
Current section: data.
- One line per section. No full schemas until mounted.
- Target cost of the block: about 150 tokens, against roughly 1500 for a full schema dump.
- Regenerated only when the registry or session state changes.
10. Guards and limits
- Max mounted tools at once: 25. Exceeding is rejected with the current count and the limit.
- Max section size: 10, enforced at load time.
- Max forced tools: 6, enforced at load time.
- Max switches per turn: 4. Exceeding returns a budget message: finish the turn with the tools you have.
- Max result count from search: 12.
- Unknown section or tool: rejected with suggestions from the fuzzy matcher.
- One
use_toolsin flight per session at a time. Concurrent calls are serialized. - Every switch is logged: session, from, to, action, arg, ok, approximate tokens saved. The log feeds section description tuning.
11. Failure modes and mitigations
| Failure | Cause | Mitigation |
|---|---|---|
| Stale section | Model never switches, keeps a wrong set | One-line current section reminder each turn |
| Ping-pong | Two sections both plausible | Mutually exclusive descriptions, examples per section, switch-frequency logging |
| Wrong fuzzy hit | Query noise | Score floor, top k cap, at most 3 per section, did-you-mean suggestions |
| Search blind spot | Keyword missing | Explicit keywords field per tool and section, editable without code |
| Cost inversion | A switch every turn costs more than it saves | Sticky default, per-bot default section |
| Silent unmount | Model assumes a tool stayed | Return payload is authoritative, unmounted means gone |
12. Build order
- Registry: loader, schema validation, caps, tests.
- Index: BM25 plus fuzzy, synonyms, deterministic, tests.
- Session state: SQLite store, forced set, resolution function, tests.
use_toolshandler: three call types, mode defaults, guards, structured return.- Prompt block generator from the registry.
- Harness integration: swap the tool schema per turn.
- Tests: section pick, search pick, exact mount, forced persistence, unknown input, every cap, per_turn reset, restart re-mount.
- Demo harness on a dummy backend: measure tokens and latency per turn against full mount and against one
agent_as_toolbaseline.
13. Acceptance criteria
- A section can be selected and its tools are callable in the same turn and every later turn while sticky.
- A query returns the expected tool in the top k for a maintained test query set.
- Forced tools are present in the schema on every turn, in every mode.
- No tool outside the resolved set is ever callable.
- The prompt block stays under the token budget.
- Restart restores the resolved set.
- All limits reject with an explicit message, never a silent no-op.
14. Open decisions
- Default session mode: sticky (recommended) or per_turn.
- Where the code lives: standalone package or deep implementation.
- Names and initial content of the first sections and the forced set.
15. Important
- Add tests
- Amount of sections doesn't matter much, just give more detailed names if they overlap
Comments
No comments yet. Start the discussion.