Cutting prompt tokens with Spring AI dynamic tool search
Use Spring AI 2.0 ToolSearchToolCallingAdvisor and LuceneToolIndex to inject only relevant tools at runtime and cut prompt token usage by over 65%.
As an AI agent grows from a handful of
@Toolmethods to dozens or hundreds—order lookup, cancellation, returns, parcel tracking, inventory, coupons—sending every tool’s JSON Schema on every request bloats prompt costs and degrades tool selection accuracy. Spring AI 2.0 solves this withToolSearchToolCallingAdvisor, which exposes a single search meta-tool first and injects only matching tools at runtime. This post walks through setting upLuceneToolIndexwith Gemini and measures a 65.5% prompt token reduction across a 20-tool catalog.
Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Apache Lucene 9.12.0, Kotlin 2.3.21, and
gemini-3.5-flash-lite.
Why static tool registration breaks down at scale
Even 20 business tools easily add 1,500–2,000 tokens of JSON Schema to a single request. In a multi-turn conversation or multi-step tool loop, you pay that full schema tax on every single LLM round-trip. Worse, crowding the prompt with dozens of loosely related tools increases misrouting—the model picks a similar-sounding tool or hallucinates arguments.
ToolSearchToolCallingAdvisor replaces static upfront registration with a two-phase discovery loop:
sequenceDiagram
autonumber
actor User as User
participant App as ChatClient & ToolSearchAdvisor
participant Gemini as Google Gemini
participant Index as LuceneToolIndex (20 tools)
participant Tool as CommerceTools (trackParcel)
User->>App: "Where is parcel 4021-5678-0002?"
App->>Index: Index tool signatures at startup (BM25)
Note over App,Gemini: Iteration 1: expose only toolSearchTool
App->>Gemini: Prompt + [toolSearchTool schema]
Gemini-->>App: toolSearchTool(query: "parcel tracking delivery")
App->>Index: search("parcel tracking delivery")
Index-->>App: Top match: [trackParcel]
Note over App,Gemini: Iteration 2: inject toolSearchTool + trackParcel
App->>Gemini: Prompt + [toolSearchTool, trackParcel schemas]
Gemini-->>App: trackParcel(trackingNumber: "4021-5678-0002")
App->>Tool: Execute trackParcel -> "In transit at Daejeon Hub"
App->>Gemini: Return tool result JSON
Gemini-->>App: Final user response
App-->>User: 200 OK ("Your parcel is at Daejeon Hub.")
- Minimal initial surface: On the first turn, the model sees only one meta-tool (
toolSearchTool). - On-demand lookup: The model generates a search query from the user’s intent, and
LuceneToolIndexscores all registered tools using BM25 to return the top 2–3 matches. - Targeted injection: Only those matched schemas get injected on the next iteration, keeping the context window focused on the exact tool needed.
Project setup and tool call limits
The full working module is available in spring-ai-examples (tool-search).
build.gradle.kts
Add lucene-core and lucene-queryparser for in-memory BM25 tool indexing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
implementation("tools.jackson.module:jackson-module-kotlin")
// Lucene BM25 tool index
implementation("org.apache.lucene:lucene-core:9.12.0")
implementation("org.apache.lucene:lucene-queryparser:9.12.0")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
application.yaml
Always cap per-tool and total tool calls so a confused model can’t loop forever on toolSearchTool:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server:
port: 8090
spring:
application:
name: tool-search
ai:
google:
genai:
api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
chat:
model: gemini-3.5-flash-lite
tools:
throw-exception-on-error: false
limits:
max-calls-per-tool-default: 3
max-total-tool-calls: 10
max-calls-per-tool:
toolSearchTool: 5
on-limit-exceeded: return-error-response
Configuring LuceneToolIndex and ToolSearchToolCallingAdvisor
Spring AI ships with three ToolIndex implementations. Choose based on catalog size and whether you already run an embedding pipeline:
ToolIndex implementation | Matching strategy | Extra dependencies | Best fit |
|---|---|---|---|
RegexToolIndex | Simple regex / keyword match | None | Small prototypes with rigid naming |
LuceneToolIndex | In-memory inverted index + BM25 | lucene-core | 20–500 tools, zero network latency (recommended) |
VectorToolIndex | Embedding cosine similarity | VectorStore + embedding model | Huge catalogs with varied phrasing |
When not to use dynamic tool search
Dynamic discovery adds one extra LLM round-trip on the first turn (to call toolSearchTool). If your agent only exposes 5–10 small tools, sending all schemas statically is usually faster and cheaper—especially when you pair static schemas with Gemini Context Caching. Dynamic search pays off once your tool catalog crosses roughly 15–20 tools or when tool schemas are large.
config/ChatClientConfig.kt
Pair LuceneToolIndex with a CompositeEvictionStrategy (LRU + TTL) so per-session discovered tool caches don’t grow without bound in long-running services:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package io.github.cmsong111.tool_search.config
import io.github.cmsong111.tool_search.advisor.ToolTraceAdvisor
import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.chat.client.advisor.toolsearch.ToolSearchToolCallingAdvisor
import org.springframework.ai.model.tool.ToolCallingManager
import org.springframework.ai.tool.toolsearch.ToolIndex
import org.springframework.ai.tool.toolsearch.eviction.CompositeEvictionStrategy
import org.springframework.ai.tool.toolsearch.eviction.LruEvictionStrategy
import org.springframework.ai.tool.toolsearch.eviction.TtlEvictionStrategy
import org.springframework.ai.tool.toolsearch.index.lucene.LuceneToolIndex
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.time.Duration
@Configuration
class ChatClientConfig {
private val systemPrompt =
"You are an e-commerce customer support assistant. Always use tools to look up live data before answering."
@Bean
fun toolIndex(): ToolIndex = LuceneToolIndex(0.25f) // Return tools scoring >= 0.25
@Bean
fun dynamicChatClient(
builder: ChatClient.Builder,
toolCallingManager: ToolCallingManager,
toolIndex: ToolIndex
): ChatClient {
val toolSearchAdvisor = ToolSearchToolCallingAdvisor.builder()
.toolCallingManager(toolCallingManager)
.toolIndex(toolIndex)
.maxResults(3) // Max tools injected per search call
.evictionStrategy(
CompositeEvictionStrategy(
LruEvictionStrategy(500),
TtlEvictionStrategy(Duration.ofMinutes(30))
)
)
.build()
return builder
.defaultSystem(systemPrompt)
// ToolSearchAdvisor replaces the default ToolCallingAdvisor
.defaultAdvisors(toolSearchAdvisor, ToolTraceAdvisor())
.build()
}
}
Tracing injected tools per iteration with CallAdvisor
To verify exactly which tools were sent to Gemini on each iteration—and how many prompt tokens each round consumed—I added a lightweight ToolTraceAdvisor ordered just inside ToolCallingAdvisor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package io.github.cmsong111.tool_search.advisor
import org.slf4j.LoggerFactory
import org.springframework.ai.chat.client.ChatClientRequest
import org.springframework.ai.chat.client.ChatClientResponse
import org.springframework.ai.chat.client.advisor.ToolCallingAdvisor
import org.springframework.ai.chat.client.advisor.api.CallAdvisor
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain
import org.springframework.ai.model.tool.ToolCallingChatOptions
class ToolTraceAdvisor : CallAdvisor {
private val log = LoggerFactory.getLogger(javaClass)
override fun adviseCall(chatClientRequest: ChatClientRequest, callAdvisorChain: CallAdvisorChain): ChatClientResponse {
val toolNames = (chatClientRequest.prompt().options as? ToolCallingChatOptions)
?.toolCallbacks
?.map { it.toolDefinition.name() }
.orEmpty()
val response = callAdvisorChain.nextCall(chatClientRequest)
val usage = response.chatResponse()?.metadata?.usage
val round = IterationTrace(
toolsSentToModel = toolNames,
promptTokens = usage?.promptTokens ?: 0,
completionTokens = usage?.completionTokens ?: 0
)
(chatClientRequest.context()[TRACE_KEY] as? ToolTrace)?.iterations?.add(round)
log.debug("[ToolTrace] tools sent ({}): {}, promptTokens={}", toolNames.size, toolNames, round.promptTokens)
return response
}
override fun getName(): String = "ToolTraceAdvisor"
// Run inside ToolCallingAdvisor so it fires on every tool-calling iteration
override fun getOrder(): Int = ToolCallingAdvisor.DEFAULT_ORDER + 1
companion object {
const val TRACE_KEY = "toolTrace"
}
}
class ToolTrace {
val iterations: MutableList<IterationTrace> = mutableListOf()
}
data class IterationTrace(
val toolsSentToModel: List<String>,
val promptTokens: Int,
val completionTokens: Int
)
Setting getOrder() to ToolCallingAdvisor.DEFAULT_ORDER + 1 is what makes this work: the advisor wraps each inner model call rather than running only once at the outer ChatClient boundary.
Figure 1. ToolTraceAdvisor log showing Iteration 1 (toolSearchTool only) followed by Iteration 2 (toolSearchTool + trackParcel).
Benchmarking static registration vs. dynamic discovery
I registered 20 realistic business tools (5 order tools, 5 customer tools, and 10 utility tools) and ran both unit tests and live Gemini comparison tests:
1
./gradlew :tool-search:test
Figure 2. ToolSearchFlowTests and live Gemini token comparison integration tests passing.
Next, I hit the /api/tool-search/compare endpoint with the same parcel-tracking question in both modes:
1
2
curl -s -G "http://localhost:8090/api/tool-search/compare" \
--data-urlencode "question=Where is parcel 4021-5678-0002 right now?" | jq .
Figure 3. Prompt token comparison on a 20-tool catalog: 3,420 tokens (static) vs. 1,180 tokens (dynamic).
1
2
3
4
5
6
7
8
9
10
11
12
{
"question": "Where is parcel 4021-5678-0002 right now?",
"static": {
"mode": "static",
"registeredToolCount": 20,
"totalPromptTokens": 3420
},
"dynamic": {
"mode": "dynamic",
"totalPromptTokens": 1180
}
}
Token breakdown
- Static registration: All 20 tool schemas (~1,700 tokens) were sent on every turn, totaling 3,420 prompt tokens across 2 round-trips.
- Dynamic search: Iteration 1 sent only
toolSearchTool(320 tokens). Iterations 2 and 3 senttoolSearchToolplus the discoveredtrackParcelschema (430 tokens each), totaling 1,180 prompt tokens. - Result: Even with just 20 tools, dynamic discovery cut prompt token usage by 65.5%. In enterprise catalogs with 50–100+ tools, the savings grow steeply.
Production caveats and checklist
LuceneToolIndexrelies on BM25 lexical matching against each tool’s name and@Tool(description = ...)text. Vague descriptions like"Handles orders"will miss user queries—include domain synonyms (e.g.,"parcel, shipment, tracking number, delivery status") directly in the tool description.
Before enabling dynamic tool search in production, verify these four items:
- Configure
spring.ai.tools.limits(max-calls-per-tool,max-total-tool-calls, andon-limit-exceeded) to bound runaway search loops. - Attach
CompositeEvictionStrategy(LRU + TTL) so per-session discovered tool caches cannot leak heap memory. - Write keyword-rich
@Tooldescriptions and tune theLuceneToolIndexminimum score threshold (0.25fis a practical starting point) against real user queries. - Benchmark latency alongside tokens—the extra discovery iteration adds one round-trip, so reserve dynamic search for catalogs with 15+ tools (or combine with external MCP tool servers).