When OpenAI introduced function calling, everyone celebrated. You could finally connect an LLM to real APIs, databases, and scripts. But there was a hidden limit nobody talked about: context window cost. Every tool definition you pass consumes tokens. Pass ten tools? Fine. Pass fifty? The model starts hallucinating arguments. Pass five hundred? Your local 27B model simply refuses to respond because its entire context is eaten by JSON schemas.
I needed nearly two thousand tools for my Agent Orchestrator — SSH hosts, database handlers, email modules, browser automation, WhatsApp contacts, and custom business logic. Most agent frameworks break at fifty. Loading them all was impossible. So I built a system that injects only the relevant tools just in time for each query.
Here is how it works.
The Tool Explosion Problem
# Naive approach: Load ALL tool definitions into context
tools = load_all_tools() # ~1800 schemas, ~450k tokens total
response = llm.chat(messages, tools=tools) # 💥 Context overflow on 27B model
A typical function-calling schema includes the tool name, description, and parameter types. For a system with 1800 specialized tools (one for each database operation, remote host command, email action, etc.), that’s easily 450,000 tokens of pure schema definitions — more than most local models can hold in their entire context window.
The industry answer has been “use a bigger model” or “reduce your tool count”. Neither was acceptable for me: I wanted to stay on my local Qwen 3.6 27B, and I didn’t want to lose granularity.
The Solution: Semantic Just-in-Time Tool Injection
Instead of loading everything, I index every tool into Qdrant with its name, description, and argument schema as an embedding. When a user query arrives, the system first asks: “Which tools are relevant?” — retrieves only the top 5 matches — and injects those schemas into the LLM’s context.
# Semantic tool search returns only what's needed
relevant = qdrant.search(user_query, limit=5) # ~10k tokens max
response = llm.chat(messages, tools=relevant) # ✅ Fits comfortably in 27B context

The result is a system that feels like it has infinite tools, but actually only ever loads what’s necessary for the current task.
How Tool Registration Works
Every tool in my system is a Python function decorated with @scriptable. This decorator does three things:
- Extracts the function signature and docstring automatically
- Generates a JSON schema compatible with OpenAI-style function calling
- Registers it into
tool_index.jsonfor fast lookup
from src.scriptable.decorators import scriptable, dynamic_tool
@dynamic_tool
@scriptable(mcp="context")
def email_search_db(query: str, from_email: str = "", limit: int = 20) -> dict:
"""Search emails in the hideide database. Returns matching results list."""
...

Running python scripts/generate_tool_index.py rebuilds the index and pushes embeddings to Qdrant. New tools are discoverable within seconds.
The Execution Pipeline
When a user sends a message, here is what happens under the hood:
`clip:tool-search-in-action
1. **Semantic Search:** The query vector is matched against all 1800 tool embeddings in Qdrant. Score threshold filters out irrelevant matches (default > 0.2).
2. **Schema Injection:** Top-5 tools are loaded with their full JSON schemas into the LLM's system prompt.
3. **Function Calling:** The local model decides which tool to call and generates arguments.
4. **Execution:** The Python function runs via `context_tools_execute()` or direct invocation.
5. **Result Return:** Output flows back to the user, optionally triggering follow-up tool calls in a loop.
`` ```clip:local-model-thinking
Handling Failures and Retries
With nearly two thousand possible failure points, robustness is critical. The system wraps every tool call in a retry mechanism with exponential backoff. If a remote SSH tool times out on the bonobo host, it retries twice before falling back to a cached result or notifying the user.
from src.scriptable.decorators import scriptable
@scriptable(mcp=True)
def deploy_to_remote(repo: str, feature: str) -> dict:
"""Commit, push to Gitea, pull on remote, and restart services."""
...
Why Local Matters
Running this entirely on local hardware (Qwen 3.6 27B on Bonobo’s RTX 3090) means zero latency to the model, zero data leaving my network, and zero API costs per query. The only external calls are to specific services when a tool actually needs them — email APIs, remote hosts, or browser automation servers.
clip:local-inference-server
``
The Numbers
| Metric | Naive Loading | Semantic Injection |
|---|---|---|
| Context tokens per call | ~450,000 | ~12,000 |
| Tools available | 1800 (if model supports it) | 1800 (dynamically filtered) |
| Latency overhead | N/A (fails before starting) | ~200ms for Qdrant search |
| Model size required | 70B+ minimum | 27B works fine |
Why Build This?
Most AI agent frameworks treat tool calling as a “small scale” problem. They assume you’ll have ten or twenty tools. But real-world automation needs hundreds: one per host, one per database table, one per contact, one per recurring task. Scaling past that requires architecture, not just bigger models.
By decoupling discovery from execution, I achieved what I call Tool Mastery. The model doesn’t need to know about all two thousand tools — it only needs to ask the right question, and the system hands it exactly what it needs.
This proves that local LLMs aren’t limited by their parameter count when you give them the right infrastructure around them. A 27B model with smart tool routing outperforms a 70B model drowning in schema definitions.
How This Compares to Industry Leaders (e.g., Hermes Agent)
Popular frameworks like Hermes Agent tackle this same “tool explosion” problem using progressive disclosure. They rely on BM25 keyword search and a three-step bridge: tool_search → tool_describe → tool_call.
My approach is different, and faster for local LLMs:
- Semantic Search over Keywords: Qdrant embeddings find tools based on intent (“find emails from Lalie”) even if the tool name doesn’t contain the word “email”.
- Zero Round-Trip Overhead: Hermes requires extra model calls to load a schema before using it. My system injects the full schema during the initial search, allowing immediate execution in two steps:
search→execute. - Context Efficiency: By keeping 1800+ tools completely out of the prompt until needed, we save tens of thousands of tokens per turn compared to Hermes’ “tiered listing” approach.
This isn’t just about scale; it’s about preserving the limited context window of a local model for actual reasoning, not tool definitions.
Do you think local LLMs with smart routing are the future of private AI agents? Let me know in the comments or on LinkedIn.
Best Regards,
Heikki Kupiainen / Metamatic Systems
