200 个工具全塞进提示词?Gemini API 上线动态工具检索
Gemini API 动态工具检索上线,每个工具只发一行摘要,需要时再加载完整参数。两种模式、代码示例、常见疑问,都在这里。
Gemini API 上线了动态工具检索,预览版。如果你的 Agent 还在每个回合把 200 个工具 schema 全发给模型,这个功能正好对症。
动态工具检索解决的是工具列表膨胀的问题。工具一多,完整 schema 全量发给模型,既烧 token,又让工具选择的准确率下降。现在 Agent 可以只上传紧凑的工具名称和描述,默认每个工具约 26 tokens,等任务需要时再加载完整参数。
两种模式。
内置服务端检索:在 tools 列表加 {type: 'tool_search'},对函数或远程 MCP 服务器设 defer_loading: true。Gemini 把完整参数 schema 留在初始 prompt 之外,模型只看到一行摘要。需要时,模型在同一个 API 请求里完成搜索、加载 schema、发出 function_call。注意:API 不会跨轮保留工具声明,即使传了 previous_interaction_id,也要每次请求重新发送完整 tools 数组。使用 @google/genai 时,记得传 apiVersion: 'v1beta'。
服务端模式的关键循环(简化示意):
function runLocalTool(name: string, args: Record<string, unknown>) {
if (name === 'issue_refund') {
return { status: 'refunded', order_id: args.order_id, amount: args.amount };
}
return { error: `Unknown tool: ${name}` };
}
const tools = [
{ type: 'tool_search' },
{
type: 'function',
name: 'issue_refund',
description: 'Refund an order to the original payment method.',
short_description: 'Refund an order.',
defer_loading: true,
parameters: {
type: 'object',
properties: {
order_id: { type: 'string' },
amount: { type: 'number' }
},
required: ['order_id', 'amount']
}
}
];
while (true) {
const interaction = await ai.interactions.create({
model: 'gemini-4-neon',
previous_interaction_id: previousId,
input: nextInput,
tools
});
previousId = interaction.id;
const calls = (interaction.steps ?? []).filter(s => s.type === 'function_call');
if (calls.length === 0) break;
nextInput = calls.map(fc => ({
type: 'function_result',
name: fc.name,
call_id: fc.id,
result: [{ type: 'text', text: JSON.stringify(runLocalTool(fc.name, fc.arguments)) }]
}));
}
第一个响应里,steps 会依次出现 tool_search_call、tool_search_result、function_call。你只需要执行自己的 function_call,搜索部分由服务端完成。
自定义客户端检索:声明一个 tool_search 工具,设 execution: 'client',名称和参数自己定。所有函数完全外部管理,不进 tools[]。模型调用搜索工具后,你用任何逻辑检索,比如向量搜索、按用户过滤权限,或并行用 Gemini Decisions API 打分,然后把匹配的完整 schema 放进 function_result.result。
有网友在客户端模式里踩过坑:第一次没加阈值,系统把 without the tilt 匹配到了描述里带 40 degree tilt 的工具。加上 0.5 的 noul 阈值后才正常。阈值不是装饰品。
也有网友担心:检索 miss 时模型会不会自信地抓一个次优工具?服务端检索时,搜索排名只看描述还是也看 schema?这些问题在原文里没有展开,建议自己测一测。在工具少于 20 个时,静态加载仍然更简单;多于 20 个时,defer 长尾能显著减少输入 token。动态检索没有额外费用,使用标准 token 定价。
完整指南、错误参考和 token 计算见官方文档。原文:原文
发布时间: 2026-11-21 02:41