toolSearch(): fixed top-5 keyword ranking misses related tools and costs an extra model step
Description
toolSearch() ranks deferred tools with a fixed keyword scorer and returns the top 5. Neither is configurable. When a search misses a tool the model needs, the model searches again, and every extra search is a full model step.
The scorer adds 2 per query token found in the tool name and 1 per token found in the description, exact tokens only (prepare-tool-search.ts#L105-L116):
const score = terms.reduce(
(score, term) =>
score +
(nameTerms.includes(term) ? 2 : 0) +
(descriptionTerms.includes(term) ? 1 : 0),
0,
);
// ...
.slice(0, 5);What it costs in production
We defer connector tools (Gmail, Linear, and others) behind toolSearch() in a WorkflowAgent chat. A user asked the agent to read today's emails and summarize the important ones. The model (Gemini 3.7 Flash) needs gmail_list_messages and gmail_get_message, and searched "gmail list messages":
| Tool | Score | Returned |
|---|---|---|
gmail_list_messages |
9 | yes |
gmail_list_drafts, gmail_list_labels, gmail_list_threads |
6 | yes |
linear_list_teams |
3, matches list |
yes, 5th |
gmail_get_message |
3, matches gmail only (messages is not message) |
no |
gmail_get_message ties with a Linear tool and loses on insertion order. The model's next step was a second search ("gmail get message") before it read a single email. That is one extra model round trip, about 5 s and 6.4k input tokens on that turn. Every task that needs two actions from the same service pays it.
The app can't work around this. Prompting for combined queries still hits the 5-result cap, and prepareStep / activeTools can't expose a deferred tool, because the SDK filters on its internal discovered set (#L72).
Proposal
Let the app own ranking. The SDK keeps candidate filtering, discovery, and next-step binding.
toolSearch({
maxResults?: number; // default 5
search?: (options: {
query: string;
tools: Array<{ name: string; description?: string }>; // eligible deferred tools
}) => string[] | PromiseLike<string[]>; // ranked names; default is today's scorer
});- Names not in
toolsare ignored, so a custom search can't expose a tool the caller rules exclude. - The model-facing description ("Returns up to five matching tools") follows
maxResults. - Backward compatible.
This lets an app return a service's related actions together, stem, or use BM25 or embeddings, without the SDK choosing one policy for everyone.
A better default scorer doesn't solve this. With plural stemming, gmail_get_message scores 6 and ties with gmail_list_drafts, gmail_modify_message, gmail_trash_message and gmail_untrash_message for the last two slots. Tool groups on deferLoading (like the OpenAI namespaces in #13874) could be built on top of search.
Related: #20856 (introduced toolSearch()), #21140 (deferred tools in WorkflowAgent).
Happy to send a PR if the shape looks right.
Reproduction
MockLanguageModelV4 searches on step 1. The output shows which tools the model can call on step 2.
import { generateText, jsonSchema, stepCountIs, tool, toolSearch } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
const deferred = (description: string) =>
tool({ description, inputSchema: jsonSchema({ type: 'object' }), execute: async () => ({}), deferLoading: true });
const usage = {
inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
outputTokens: { total: 1, text: 1, reasoning: 0 },
};
const model = new MockLanguageModelV4({
doGenerate: [
{
content: [{ type: 'tool-call', toolCallId: '1', toolName: 'search_tools', input: '{"query":"gmail list messages"}' }],
finishReason: { unified: 'tool-calls', raw: undefined },
usage,
warnings: [],
},
{ content: [{ type: 'text', text: 'done' }], finishReason: { unified: 'stop', raw: undefined }, usage, warnings: [] },
],
});
await generateText({
model,
prompt: 'Read my emails from today and summarize the important ones.',
stopWhen: stepCountIs(2),
tools: {
search_tools: toolSearch(),
gmail_list_messages: deferred('List recent Gmail messages with sender, subject, and received time.'),
gmail_list_drafts: deferred('List Gmail drafts with subject and recipients.'),
gmail_list_labels: deferred('List Gmail labels (system and user) with ids for filtering and modify_message.'),
gmail_list_threads: deferred('List Gmail conversation threads with snippet and message count.'),
linear_list_teams: deferred('List the teams in the Linear workspace with their ids and keys.'),
gmail_get_message: deferred('Read one Gmail message including its body, recipients, and inbound attachment metadata.'),
},
});
console.log(model.doGenerateCalls[1].tools?.map(t => t.name));Output:
[ 'search_tools', 'gmail_list_messages', 'gmail_list_drafts', 'gmail_list_labels', 'gmail_list_threads', 'linear_list_teams' ]AI SDK Version
- ai: 7.0.114 (
src/tool-search/is unchanged in 7.0.124 and onmainat eb93c81) - @ai-sdk/workflow: 2.0.45
Source: vercel/ai