{"slug": "how-to-load-agent-tools-on-demand-with-the-gemini-api", "title": "How to load agent tools on demand with the Gemini API", "summary": "A 50-tool test against gemini-4-hydrogen found that Gemini's built-in server-side tool_search cut total model input tokens 74%, from 13,277 to 3,499, and finished 4.5 seconds faster (9.1 s versus 13.6 s) than sending all 50 JSON schemas on every turn, according to a benchmark published by developer Flavio. Client-side retrieval backed by the Gemini Decisions API dropped Turn 1 input tokens on the main model to 129, a 98% reduction, and cut total main-model input tokens 86%, with the search itself costing 3,469 input tokens on gemini-decision-1 at $0.10 per 1M tokens and 0 output tokens. Dynamic Tool Retrieval, available via the tool_search tool in the v1beta Interactions API, keeps most tools on standby with defer_loading set to true so Gemini sees only a roughly 26-token summary per deferred tool until it loads the full definition.", "body_md": "# How to load agent tools on demand with the Gemini API\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [AI](https://flaviocopes.com/tags/ai/)\n\nWhen an agent has dozens of tools, sending every JSON schema on every turn burns tokens. Here's how Gemini's built-in tool_search and client-side Decisions API filtering work, tested across 50 real tools.\n\nIf your agent only has 5 or 10 tools, you put every JSON parameter schema in the request and you’re good to go.\n\nBut once you connect a billing system, a warehouse API, and a couple of [MCP servers](https://flaviocopes.com/what-is-mcp/), you end up with 50 or 100 tools, and most turns only need one of them.\n\nSending 50 full schemas on every turn burns thousands of input tokens before the user even says hello, and it makes tool selection noisier.\n\nGoogle added **Dynamic Tool Retrieval** (via the `tool_search` tool) to the Gemini Interactions API in `v1beta`. If you’re new to deferred schemas in general, see the [tool search](https://flaviocopes.com/ai-glossary/tool-search/) glossary entry.\n\nInstead of sending every parameter schema upfront, you keep most tools on standby, and you load their full definitions only when a task calls for them.\n\nI built a 50-tool catalog across 10 domains (billing, shipping, orders, accounts, inventory, support, CRM, analytics, notifications, and admin) and ran the same billing query against `gemini-4-hydrogen` in three setups: static loading, built-in server-side `tool_search`, and custom client-side retrieval backed by the [Gemini Decisions API](https://flaviocopes.com/gemini-decisions-api/).\n\n## What I measured across 50 tools\n\nEvery test asked `gemini-4-hydrogen` the same question: `\"Look up the billing history for user 123 and check if they have any unpaid invoices.\"` Each tool had a realistic description and four to five typed parameters.\n\n| Mode | API turns | Turn 1 input tokens | Total model input tokens | Model output tokens | Decision 1 input tokens | Wall time | \n|---|---|---|---|---|---|---|\n| Static (50 schemas) | 2 | 6,522 | 13,277 | 149 | 0 | 13.6 s | \n| Server-side `tool_search` (3 loaded, 47 deferred) | 2 | 1,533 | 3,499 | 185 | 0 | 9.1 s | \n| Client-side `tool_search` + Decision 1 | 3 | 129 | 1,826 | 181 | 3,469 | 12.2 s | \n\nTwo numbers stand out right away.\n\nFirst, server-side `tool_search` cut total input tokens by 74% (from 13,277 down to 3,499) and finished 4.5 seconds faster than sending all 50 schemas, using the same two API turns.\n\nSecond, client-side retrieval with `gemini-decision-1` dropped Turn 1 on the main model down to 129 input tokens (a 98% drop) and cut total main-model input tokens by 86%. The search itself cost 3,469 input tokens on `gemini-decision-1` at $0.10 per 1M tokens and 0 output tokens.\n\n## Two ways dynamic tool retrieval works\n\nYou pick between server-side search (zero retrieval code, one round trip) and client-side search (your own catalog, permissions, or custom ranker).\n\nDynamic tool retrieval does not add any extra cost on top of normal model pricing.\n\nDeferred parameter schemas are not billed until the model loads them.\n\nIf you keep the `tools` list identical across turns, prompt caching stays in place.\n\n## Setup\n\nInstall version 3.2 or later of the Google GenAI SDK and export your Gemini API key. In Node.js:\n\n```\nnpm install @google/genai@latest\nexport GEMINI_API_KEY=your-key-here\n```\n\nIn Python, install `google-genai`:\n\n```\npip install -U google-genai\n```\n\nBoth retrieval modes run on the `v1beta` Interactions API (`interactions.create`), the same endpoint behind the [Gemini API CLI](https://flaviocopes.com/gemini-api-cli/).\n\n## Mode 1: built-in server-side retrieval\n\nFor most large tool sets, you’ll want to start with server-side retrieval.\n\nYou add `{ type: 'tool_search' }` to `tools`, keep your 3 to 5 most common functions loaded normally, and mark the rest with `defer_loading: true`.\n\nWhen `defer_loading` is `true`, Gemini strips the parameter schema from the initial prompt and only sees a one-line summary (around 26 tokens per tool, or fewer if you supply `short_description`):\n\n``` js\nimport { GoogleGenAI } from '@google/genai'\n\nconst ai = new GoogleGenAI({ apiVersion: 'v1beta' })\n\nconst tools = [\n  { type: 'tool_search' },\n  {\n    type: 'function',\n    name: 'get_user_profile',\n    description: 'Read account metadata, plan tier, and team role.',\n    parameters: {\n      type: 'object',\n      properties: { user_id: { type: 'integer' } },\n      required: ['user_id']\n    }\n  },\n  {\n    type: 'function',\n    name: 'get_billing_history',\n    description: 'Retrieve past invoices, receipts, and payment status for a customer account.',\n    short_description: 'Get customer invoices and payment history.',\n    defer_loading: true,\n    parameters: {\n      type: 'object',\n      properties: {\n        user_id: { type: 'integer' },\n        limit: { type: 'integer' }\n      },\n      required: ['user_id']\n    }\n  },\n  {\n    type: 'mcp_server',\n    name: 'order_service',\n    url: 'https://gemini-api-demos.uc.r.appspot.com/mcp',\n    defer_loading: true\n  }\n]\n```\n\nNotice the remote MCP server at the end. Setting `defer_loading: true` on an `mcp_server` entry defers every tool exposed by that server without listing them one by one.\n\nBe careful with one rule I hit right away while running my benchmark: you can only set `short_description` when `defer_loading: true` is also set on that tool. Leaving `short_description` on an always-loaded tool throws a 400 error:\n\n```\n400 GenerateContentRequest.tools[1].function_declarations[10].short_description:\nshort_description can only be set if defer_loading is true\n```\n\nStrip `short_description` from your non-deferred tools before sending the array.\n\nFrom there, your agent loop looks like normal function calling. Search, schema loading, and the function call happen inside one API call:\n\n``` js\nlet input = 'Look up the billing history for user 123 and check if they have any unpaid invoices.'\nlet prevId\nlet interaction\n\nwhile (true) {\n  interaction = await ai.interactions.create({\n    model: 'gemini-4-hydrogen',\n    previous_interaction_id: prevId,\n    input,\n    tools\n  })\n  prevId = interaction.id\n\n  const calls = (interaction.steps ?? []).filter((s) => s.type === 'function_call')\n  if (calls.length === 0) break\n\n  input = calls.map((fc) => ({\n    type: 'function_result',\n    name: fc.name,\n    call_id: fc.id,\n    result: [{ type: 'text', text: JSON.stringify(runLocalTool(fc.name, fc.arguments)) }]\n  }))\n}\n\nconsole.log(interaction.output_text)\n```\n\nSend the same `tools` array back on every turn so the prompt prefix stays cacheable.\n\n### The same call in Python\n\nIn Python (`google-genai` 3.2 or later), pass `api_version` as `v1beta` and send the same `tool_search` and `defer_loading` dictionaries:\n\n``` python\nfrom google import genai\n\nclient = genai.Client(http_options={'api_version': 'v1beta'})\n\ntools = [\n    {'type': 'tool_search'},\n    {\n        'type': 'function',\n        'name': 'get_billing_history',\n        'description': 'Retrieve past invoices, receipts, and payment status for a customer account.',\n        'short_description': 'Get customer invoices and payment history.',\n        'defer_loading': True,\n        'parameters': {\n            'type': 'object',\n            'properties': {'user_id': {'type': 'integer'}},\n            'required': ['user_id'],\n        },\n    },\n]\n\ninteraction = client.interactions.create(\n    model='gemini-4-hydrogen',\n    input='Look up the billing history for user 123.',\n    tools=tools,\n)\n\ncalls = [s for s in (interaction.steps or []) if getattr(s, 'type', None) == 'function_call']\nprint([(c.name, c.arguments) for c in calls])\n# [('get_billing_history', {'user_id': 123})]\n```\n\n## Mode 2: client-side retrieval with the Decisions API\n\nServer-side retrieval expects all your tools to live in the request payload.\n\nIf your tools live in an external database, vary by user permissions, or need custom ranking logic, you can switch `tool_search` to `execution: 'client'`.\n\nIn this mode, you don’t send your 50 tools in `tools` at all. You send one `tool_search` declaration with any name and parameters you want:\n\n``` js\nconst tools = [\n  {\n    type: 'tool_search',\n    execution: 'client',\n    name: 'search_tool_registry',\n    description: 'Search the 50-tool catalog for billing, shipping, order, account, inventory, support, CRM, analytics, notification, or admin tools.',\n    parameters: {\n      type: 'object',\n      properties: { query: { type: 'string' } },\n      required: ['query']\n    }\n  }\n]\n```\n\nWhen Gemini calls `search_tool_registry`, your app scores the external registry using [Gemini Decision 1](https://flaviocopes.com/gemini-decisions-api/) in one parallel request (up to 1,000 tools per call, 0 output tokens) and returns the matching full function schemas inside `function_result`:\n\n```\nasync function searchRegistryWithDecisions(query, registry, threshold = 0.35) {\n  const questions = Object.fromEntries(\n    Object.entries(registry).map(([name, schema]) => [\n      name,\n      {\n        type: 'noul',\n        instructions: `Is the tool '${name}' (${schema.description}) needed for this request?`\n      }\n    ])\n  )\n\n  const decision = await ai.decisions.create({\n    model: 'gemini-decision-1',\n    input: query,\n    questions\n  })\n\n  return Object.entries(decision.answers ?? {})\n    .filter(([, ans]) => ans.type === 'noul' && (ans.noul ?? 0) >= threshold)\n    .sort((a, b) => b[1].noul - a[1].noul)\n    .slice(0, 5)\n    .map(([name]) => registry[name])\n}\n```\n\nThen inside your loop, handle `search_tool_registry` by returning the matched tool objects directly in `result`:\n\n``` js\nif (fc.name === 'search_tool_registry') {\n  const query = String(fc.arguments?.query ?? '')\n  const matches = await searchRegistryWithDecisions(query, registry)\n  return {\n    type: 'function_result',\n    name: fc.name,\n    call_id: fc.id,\n    result: matches.length ? matches : [{ type: 'text', text: 'No matching tools found.' }]\n  }\n}\n```\n\nHere’s the real three-turn trace from running `client-loop.mjs` against our 50-tool registry:\n\nOn Turn 1, `gemini-4-hydrogen` called `search_tool_registry({\"query\":\"billing history unpaid invoices\"})`. `gemini-decision-1` scored all 50 tools in 367 ms (3,470 input tokens, 0 output tokens) and injected 2 schemas: `get_billing_history` (0.96) and `get_company_account` (0.50).\n\nOn Turn 2, the main model saw those 2 schemas, called `get_billing_history({\"user_id\":123})`, and on Turn 3 wrote the final answer mentioning unpaid invoice `inv_914`.\n\nThe `tools` array stayed the same in every turn.\n\n## When to use which mode\n\n| Mode | Best for | Extra round trips | Remote MCP | \n|---|---|---|---|\n| Static loading | Under 20 stable tools | None | Supported | \n| Server-side `tool_search` | 20+ fixed tools, zero retrieval code, lowest latency | None (1 API call) | Supported with `defer_loading` | \n| Client-side `tool_search` + Decision 1 | External registries, per-user permissions, custom ranking | 1 per search | Handled in your app | \n\nIf you want to go deeper on how tool loops, prompt caching, and strict JSON schemas behave under load, see [structured outputs and few-shot examples](https://flaviocopes.com/structured-outputs-few-shot/) and my free [AI Fundamentals Handbook](https://flaviocopes.com/ebooks/ai-fundamentals-handbook/).\n\n## How I would use it\n\nI don’t run a 50-tool production agent today, so I haven’t put `tool_search` in front of live customer traffic yet. Most of my own scripts and coding workflows use fewer than ten tools, where static loading is simpler and faster to debug.\n\nIf I were building a multi-tenant support or ops agent with 30+ tools or multiple MCP servers, I would start with server-side `tool_search`, keep the 3 to 5 everyday tools loaded, and defer the rest. In my 50-tool test it cut input tokens by 74% and shaved 4.5 seconds off the run without writing a single line of search glue.\n\nI would only move to client-side retrieval with `gemini-decision-1` when tools depend on the logged-in user’s permissions or live in an external catalog that changes per workspace. That extra round trip is worth it when you need to filter out unauthorized tools before the model ever sees their schemas, and unnecessary when every user shares the same tool list.\n\nFor the full reference, see Google’s [Dynamic tool retrieval guide](https://aistudio.google.com/learn/dynamic-tool-retrieval-gemini-api) and the [Gemini Decisions API tutorial](https://flaviocopes.com/gemini-decisions-api/).\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/how-to-load-agent-tools-on-demand-with-the-gemini-api", "canonical_source": "https://flaviocopes.com/gemini-dynamic-tool-retrieval/", "published_at": "2026-12-06 09:00:00+00:00", "updated_at": "2026-12-06 09:45:50.076246+00:00", "lang": "en", "topics": ["ai-agents", "large-language-models", "ai-tools", "developer-tools"], "entities": ["Google", "Gemini API", "gemini-4-hydrogen", "gemini-decision-1", "Google GenAI SDK", "Flavio", "Model Context Protocol"], "also_reported_by": [], "takeaway": "Server-side tool_search with defer_loading cut total input tokens 74% (13,277 to 3,499) and ran 4.5 s faster than loading all 50 schemas, while client-side Decisions API retrieval cut main-model input tokens 86% at the cost of 3,469 tokens on gemini-decision-1.", "recommendation": {"advice": "Defer rarely used tool schemas with defer_loading and tool_search instead of sending every JSON schema each turn; the test cut input tokens 74% and wall time by 4.5 s across 50 tools.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/how-to-load-agent-tools-on-demand-with-the-gemini-api", "markdown": "https://wpnews.pro/news/how-to-load-agent-tools-on-demand-with-the-gemini-api.md", "text": "https://wpnews.pro/news/how-to-load-agent-tools-on-demand-with-the-gemini-api.txt", "jsonld": "https://wpnews.pro/news/how-to-load-agent-tools-on-demand-with-the-gemini-api.jsonld"}}