Intro to Tool Calling in Spring AI 2.0

2026-11-24来源 BaeldungEnglish
Intro to Tool Calling in Spring AI 2.0

1. Introduction

Tool calling lets a model request an application operation by supplying a tool name and arguments. Spring AI executes the tool and returns its result to the model, which can request another tool or produce an answer.

In Spring AI 1.x, each ChatModel owned its tool loop. In 2.0, ToolCallingAdvisor runs it within the ChatClient advisor chain, allowing other advisors to participate. The Spring engineering article on composable tool calling introduces this architecture.

We’ll build a travel assistant, compose advisors around its tool loop, and control execution manually.

2. Maven Dependencies

We’ll use the OpenAI chat model in our examples. First, let’s add the Spring AI starter:

<properties> <spring-ai.version>2.0.2</spring-ai.version> </properties> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId> <version>${spring-ai.version}</version> </dependency> 

The latest version of spring-ai-starter-model-openai is available in the Maven Repository.

We also need to provide the API key in application.properties:

spring.ai.openai.api-key=${OPENAI_API_KEY} 

The same tool API works with other chat models that support tool calling.

3. Defining Tools

3.1. Defining Tool Methods

We can define a tool by annotating a method with @Tool. Spring AI derives the tool name, description, and JSON input schema from the method signature.

Let’s start with a weather tool:

@Component public class WeatherTools { private final WeatherService weatherService; public WeatherTools(WeatherService weatherService) { this.weatherService = weatherService; } @Tool(description = "Get the current weather in a city") public WeatherForecast getCurrentWeather( @ToolParam(description = "City name, for example Amsterdam") String city) { return weatherService.getCurrentWeather(city); } } 

The model uses the tool description to select a method. @ToolParam describes each argument.

Next, let’s define a booking tool that changes application state:

@Component public class BookingTools { private final BookingService bookingService; public BookingTools(BookingService bookingService) { this.bookingService = bookingService; } @Tool(description = "Book a one-way flight") public BookingConfirmation bookFlight( @ToolParam(description = "IATA code of the departure airport") String origin, @ToolParam(description = "IATA code of the destination airport") String destination, @ToolParam(description = "Travel date in ISO-8601 format") LocalDate date) { return bookingService.book(origin, destination, date); } } 

We’ll return small records with only the fields the model needs:

public record WeatherForecast(String city, String conditions, int temperatureCelsius) { } public record BookingConfirmation( String reference, String flightNumber, LocalDate date) { } 

Spring AI serializes these results for the model; descriptive field names preserve each value’s meaning.

3.2. Registering Default and Per-Call Tools

Checking the weather is a read-only operation. Booking changes application state. We expose the weather tool by default and add the booking tool only to calls that need it:

@Bean ChatClient travelChatClient(ChatClient.Builder builder, WeatherTools weatherTools) { return builder .defaultTools(weatherTools) .build(); } 

In our service, planTrip() adds the booking tool to every call it makes. Section 6 shows how to require approval before executing the tool:

public String planTrip(String request) { return chatClient.prompt() .system("Help the user plan a trip. Never book a flight without an explicit request.") .user(request) .tools(bookingTools) .call() .content(); } 

Spring AI appends per-call tools to the default tools; they do not replace them. Consequently, this request can use both getCurrentWeather() and bookFlight().

3.3. Following a Complete Request

For example, given the request:

Check the weather in Amsterdam. If it is sunny, book a flight from LHR to AMS for 2026-11-12. 

the model can first request getCurrentWeather(). If its result reports sunny weather, the next model response can request bookFlight(). A possible final response is:

Amsterdam is sunny and 18°C. I booked flight BA432 from LHR to AMS for November 12, 2026. The booking reference is A7KF21. 

The model chooses the wording and tool sequence; our services supply the results.

4. How the Tool-Calling Loop Works

DefaultChatClient automatically adds one ToolCallingAdvisor to the advisor chain. We normally don’t need to construct it ourselves.

For our travel request, the advisor performs the following steps:

  1. It sends the user message, system message, and available tool definitions to the model.
  2. It inspects the model response for tool calls.
  3. ToolCallingManager resolves and executes every requested ToolCallback.
  4. It appends the model’s request and the tool results to the conversation history.
  5. It calls the model again with that history.

The loop stops when the model returns no tool calls. Our example may require three model invocations: weather selection, booking selection, and the final answer.

In ToolCallingLoopUnitTest, ScriptedChatModel replays two tool requests and a final answer without contacting an LLM. After the travel request, we verify:

assertThat(answer).isEqualTo("Amsterdam is sunny. Your flight is booked."); assertThat(chatModel.getPrompts()).hasSize(3); 

The model can only request callbacks we register. Our Java services still handle validation, authorization, transactions, and auditing.

The loop supports both .call() and .stream(). DefaultChatClient permits at most one ToolAdvisor, preventing duplicate tool execution.

5. Composing Advisors With the Tool Loop

With the loop in the advisor chain, we can observe its iterations through other advisors. We control their visibility through ordering.

ToolCallingAdvisor.DEFAULT_ORDER is Ordered.HIGHEST_PRECEDENCE + 300. An advisor with a lower order wraps the tool advisor and runs outside the loop. An advisor with a higher order sits downstream and runs once for every model invocation.

5.1. Observing Every Iteration

Suppose we want to record every model response, including intermediate tool-call requests. We can implement a regular CallAdvisor and place it inside the loop:

public class ToolIterationLoggingAdvisor implements CallAdvisor { private static final Logger log = LoggerFactory.getLogger(ToolIterationLoggingAdvisor.class); @Override public String getName() { return ToolIterationLoggingAdvisor.class.getSimpleName(); } @Override public int getOrder() { return ToolCallingAdvisor.DEFAULT_ORDER + 100; } @Override public ChatClientResponse adviseCall( ChatClientRequest request, CallAdvisorChain chain) { ChatClientResponse response = chain.nextCall(request); log.info("Tool-loop response: {}", response.chatResponse()); return response; } } 

Next, we register it on the client:

@Bean ChatClient travelChatClient( ChatClient.Builder builder, WeatherTools weatherTools) { return builder .defaultTools(weatherTools) .defaultAdvisors(new ToolIterationLoggingAdvisor()) .build(); } 

The caller receives the final answer, while our logging advisor observes every iteration. An order below ToolCallingAdvisor.DEFAULT_ORDER would expose only the final response.

ToolCallingLoopUnitTest uses RecordingAdvisor, a helper that collects responses after chain.nextCall(). We register two instances around the tool advisor:

RecordingAdvisor outer = new RecordingAdvisor( "outer", ToolCallingAdvisor.DEFAULT_ORDER - 100); RecordingAdvisor inner = new RecordingAdvisor( "inner", ToolCallingAdvisor.DEFAULT_ORDER + 100); 

After the scripted weather-and-booking request, we verify which responses each advisor sees:

assertThat(outer.getResponses()).hasSize(1); assertThat(inner.getResponses()).hasSize(3); assertThat(inner.getResponses()) .extracting(response -> response.chatResponse().hasToolCalls()) .containsExactly(true, true, false); 

This example uses SLF4J with Logback through Spring Boot. In production, we should redact sensitive tool arguments and results. The same ordering rule applies to metrics and policy checks.

5.2. Memory Inside and Outside the Loop

The default MessageChatMemoryAdvisor order is Ordered.HIGHEST_PRECEDENCE + 200, so memory stays outside the tool loop. It loads history once and stores the user’s message together with the final answer. ToolCallingAdvisor maintains intermediate tool requests and responses in its internal history.

In ChatMemoryPlacementUnitTest, we script one weather call and a final answer. With default memory ordering, we verify:

assertThat(chatMemory.get(CONVERSATION_ID)) .extracting(Message::getMessageType) .containsExactly(MessageType.USER, MessageType.ASSISTANT); 

We can place memory inside the loop when subsequent user turns need the full tool transcript:

MessageChatMemoryAdvisor memoryAdvisor = MessageChatMemoryAdvisor .builder(chatMemory) .order(ToolCallingAdvisor.DEFAULT_ORDER + 100) .build(); 

When we repeat the request with this ordering, memory also stores the assistant’s tool request and the tool result:

assertThat(chatMemory.get(CONVERSATION_ID)) .extracting(Message::getMessageType) .containsExactly(MessageType.USER, MessageType.ASSISTANT, MessageType.TOOL, MessageType.ASSISTANT); 

With an auto-registered tool advisor, DefaultChatClient notices this arrangement and disables the advisor’s internal conversation history. Otherwise, both components would maintain the same messages. When we construct ToolCallingAdvisor manually, we need to call disableInternalConversationHistory() ourselves.

We need a memory repository that supports tool request and response messages. The backend compatibility documentation lists in-memory, Redis, and Neo4j as supporting the full message set in 2.0. Otherwise, we should keep memory outside the loop.

6. Controlling Tool Execution Ourselves

For approval workflows or custom stop conditions, we can disable automatic execution per request.

6.1. Preparing a Request for Manual Execution

We’ll pass the question and a booking approval predicate to our service method:

public String planTrip(String question, Predicate<ToolCall> bookingApprover) { 

Inside this method, we prepare the callbacks and chat options:

ToolCallingManager toolCallingManager = ToolCallingManager.builder().build(); ToolCallback[] callbacks = ToolCallbacks.from(weatherTools, bookingTools); ToolCallingChatOptions options = ToolCallingChatOptions.builder() .toolCallbacks(callbacks) .build(); Prompt prompt = new Prompt(List.of(new UserMessage(question)), options); 

Then, we make the initial call without automatic tool execution:

ChatClientResponse response = chatClient.prompt() .messages(prompt.getInstructions()) .options(options.mutate()) .advisors(AdvisorParams.toolCallingAdvisorAutoRegister(false)) .call() .chatClientResponse(); 

6.2. Executing and Continuing the Loop

Spring AI still sends the tools to the model, but the application now receives the model’s tool-call response. We can inspect it, request approval when necessary, and continue the loop through ToolCallingManager:

while (response.chatResponse() != null && response.chatResponse().hasToolCalls()) { approveIfRequired(response.chatResponse(), bookingApprover); ToolExecutionResult result = toolCallingManager .executeToolCalls(prompt, response.chatResponse()); prompt = new Prompt(result.conversationHistory(), options); response = chatClient.prompt() .messages(result.conversationHistory()) .options(options.mutate()) .advisors(AdvisorParams.toolCallingAdvisorAutoRegister(false)) .call() .chatClientResponse(); } 

approveIfRequired() checks booking calls against bookingApprover and throws BookingNotApprovedException if approval fails. Weather lookups need no approval. We own history and termination; we can use an advisor inside the automatic loop when we only need observation.

Our two tools use the default returnDirect = false. In a general-purpose manual loop, we must also inspect result.returnDirect() after execution. When it is true, we must treat the tool output as the final response and avoid sending it to the model again; ToolExecutionResult.buildGenerations(result) converts it into response generations.

7. Further Considerations

Large MCP registries can consume substantial context with tool schemas. ToolSearchToolCallingAdvisor replaces the regular tool advisor and discovers tools progressively. The advisor searches a tool index. Our tool-search profile uses Lucene for keyword search. We can also use a regex-based index for pattern matching or a vector store for semantic search.

The 2.0 tool-calling upgrade notes explain how to replace model-level execution settings with advisor configuration. For function-style tools, we now register explicit ToolCallback instances rather than resolving function beans by name. Our examples use the 2.0 APIs.

8. Conclusion

We defined tools, followed the execution loop, and used advisor ordering to observe iterations and manage memory. Manual execution gives us control when operations require approval.

The code backing this article is available over on GitHub.

The post Intro to Tool Calling in Spring AI 2.0 first appeared on Baeldung.

原文:https://www.a8q9.cn/en/article/intro-to-tool-calling-in-spring-ai-2-0-f0749c.html

相关文章