Spring AI 2.0: Build tool and token logging advisors

Learn to build two Spring AI advisors for tool visibility and token usage, using ChatResponse metadata in a Java project with Spring Boot 4.1.

Player not loading? Watch on YouTube

Dan Vega builds two custom advisors to inspect tool use and token consumption in Spring AI. He describes advisors as AOP-like interceptors that can work before and after an LLM call. The tutorial introduces the Advisor API and reviews built-in advisors before moving into Java code.

The example starts with Spring Boot 4.1, web and Anthropic dependencies, and an API key supplied through an environment variable. It uses an API-backed model; the tutorial does not demonstrate local inference or offline operation. Vega first returns a ChatResponse to inspect usage metadata, then returns plain text while advisors handle the console output.

AvailableToolsLoggingAdvisor lists the tool names visible to the model before a request. Its after method examines response tool calls and logs names and arguments, truncating argument text to 160 characters. A date and time tool supplies context for a question about tomorrow's date.

TokenCounterAdvisor reads prompt, completion and total token usage from ChatResponse metadata and keeps running totals across calls. One demonstrated request reports 368 prompt tokens and 51 completion tokens, totaling 419. The coding walkthrough also catches a missing advisor registration and stresses returning the response from the interceptor. Vega presents these logs as preparation for a later tool search tutorial, where he plans to examine how tool definitions consume context.