Chapter 4: Tools

This chapter gives the model one tool to count error events.

Objectives:

  • Write countErrors as a Spring AI tool.
  • Attach it to the Assistant.
  • Compare replies with and without the tool.

A tool is a Java method. The model chooses tools from their names and descriptions alone. A vague description causes wrong choices.

Step 1: The tool

package com.garageeducation.harness;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * Log tools the model can call.
 *
 * <p>The model sees only the tool name, the {@link Tool} description, and each
 * {@link ToolParam} description. It never sees the method body.
 */
@Slf4j
@Component
public class LogTools {

    /**
     * Counts error log events for one service.
     *
     * <p>The data is fake. The {@code checkout} service returns 412. Every other service returns 3.
     *
     * @param service the service name, for example {@code checkout}
     * @param minutes the look-back window in minutes, from 1 to 1440; the fake data ignores it
     * @return the number of error events
     */
    @Tool(description = "Count error log events for one service in the last N minutes. Use this to check for a current error spike.")
    public int countErrors(@ToolParam(description = "Service name, for example checkout") String service,
                           @ToolParam(description = "Look-back window in minutes, from 1 to 1440") int minutes) {
        int count = "checkout".equals(service) ? 412 : 3; // fake data
        log.debug("[tool] countErrors(service={}, minutes={}) returned {}", service, minutes, count);
        return count;
    }
}
  • @Tool names the method as a tool. Its description tells the model when to use it.
  • @ToolParam describes each argument. The model fills them in.
  • @Component makes LogTools a bean, so Spring can pass it to other classes.

LangChain’s @tool works on plain functions, not on methods. Two small helpers make a method a tool, like Spring AI’s @Tool. Create tool_support.py:

"""Marks methods as tools and wraps them, like Spring AI's ``@Tool`` and ``ToolCallbacks.from``."""

import inspect
from collections.abc import Callable
from typing import Any, Final, TypeVar

from langchain_core.tools import BaseTool, StructuredTool

F = TypeVar("F", bound=Callable[..., Any])

DESCRIPTION: Final = "_tool_description"


def tool(description: str) -> Callable[[F], F]:
    """Marks a method as a tool the model can call.

    It plays the part of Spring AI's ``@Tool(description = ...)``.

    Args:
        description: what the tool does and when to use it; the model reads it

    Returns:
        the same method, marked
    """

    def mark(method: F) -> F:
        setattr(method, DESCRIPTION, description)
        return method

    return mark


def tools_from(target: object) -> list[BaseTool]:
    """Wraps each ``@tool`` method of ``target`` in a LangChain tool.

    It plays the part of Spring AI's ``ToolCallbacks.from(target)``.

    Args:
        target: an object with ``@tool`` methods

    Returns:
        one tool per marked method, named after the method
    """
    return [
        StructuredTool.from_function(method, description=getattr(method, DESCRIPTION))
        for _, method in inspect.getmembers(target, inspect.ismethod)
        if hasattr(method, DESCRIPTION)
    ]
  • @tool(description=…) marks a method, like @Tool(description = …).
  • tools_from(target) wraps each marked method in a LangChain tool, like ToolCallbacks.from(target).
  • StructuredTool.from_function reads the method’s parameters and types. It builds the schema the model sees.

Create log_tools.py:

"""Log tools the model can call."""

import logging
from typing import Annotated, Final

from pydantic import Field

from harness.tool_support import tool

log: Final = logging.getLogger(__name__)


class LogTools:
    """Log tools the model can call.

    The model sees only the tool name, the ``@tool`` description, and each parameter
    description. It never sees the method body.
    """

    @tool(description="Count error log events for one service in the last N minutes. Use this to check for a current error spike.")
    def count_errors(
        self,
        service: Annotated[str, Field(description="Service name, for example checkout")],
        minutes: Annotated[int, Field(description="Look-back window in minutes, from 1 to 1440")],
    ) -> int:
        """Counts error log events for one service.

        The data is fake. The ``checkout`` service returns 412. Every other service returns 3.

        Args:
            service: the service name, for example ``checkout``
            minutes: the look-back window in minutes, from 1 to 1440; the fake data ignores it

        Returns:
            the number of error events
        """
        count = 412 if service == "checkout" else 3  # fake data
        log.debug("[tool] count_errors(service=%s, minutes=%s) returned %s", service, minutes, count)
        return count
  • @tool names the method as a tool. Its description tells the model when to use it.
  • Annotated[str, Field(description=…)] describes each argument, like @ToolParam. The model fills them in.
  • create_app() creates one LogTools and passes it to other classes, like a Spring bean.
  • The tool name is the method name: count_errors.

Figure 4.1 shows what the model sees.

What the model seesnamecountErrorsdescriptionCount error log events for one servicein the last N minutes. Use this to checkfor a current error spike.serviceService name, for example checkoutminutesLook-back window in minutes, from 1 to 1440This is all it has to choose with.What it never seesthe method bodyreturn "checkout".equals(service)? 412 : 3; // fake datathe class nameLogTools
Figure 4.1. A tool, as the model sees it. A vague description on the left means a wrong choice, however good the code on the right is.

Step 2: Attach the tool

Make two changes to the Assistant from Chapter 3:

  • Add a private final LogTools logTools; field. Lombok adds it to the constructor, and Spring passes in the bean.
  • Pass the tools with .tools(logTools).
@Slf4j
@Service
@RequiredArgsConstructor
public class Assistant {

    private static final String SYSTEM = "You are a careful assistant. Answer in two sentences or fewer.";

    private final ChatClient chat;
    private final LogTools logTools;

    /**
     * Asks the model one question and lets {@link ChatClient} run the tools.
     *
     * <p>{@link ChatClient} registers a {@code ToolCallingAdvisor} by default. The advisor runs each
     * tool call, sends the result back to the model, and repeats until the reply has no tool calls.
     *
     * @param question the user's question, in plain text
     * @return the model's final text reply
     */
    public String askAutoToolCall(String question) {
        log.debug("[auto] Spring AI runs every tool call. Question: {}", question);
        String answer = chat.prompt()
                .system(SYSTEM)
                .user(question)
                .tools(logTools)
                .call()
                .content();
        log.debug("[auto] Final answer: {}", answer);
        return answer;
    }
}

ChatClient runs the tool for you. It does so through an advisor. Step 3 explains advisors. Step 4 shows the tool loop.

Replace assistant.py. The assistant now builds an agent that runs the tools:

"""Sends one question to the chat model, with the tools in LogTools."""

import logging
from typing import Final

from langchain.agents import create_agent
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import HumanMessage

from harness.log_tools import LogTools
from harness.observation_logging import ToolExecutionHandler
from harness.tool_support import tools_from

log: Final = logging.getLogger(__name__)


class Assistant:
    """Sends one question to the chat model, with the tools in ``LogTools``."""

    SYSTEM: Final = "You are a careful assistant. Answer in two sentences or fewer."

    def __init__(self, chat: BaseChatModel, log_tools: LogTools) -> None:
        self.chat = chat
        self.log_tools = log_tools
        self.agent = create_agent(chat, tools=tools_from(log_tools), system_prompt=self.SYSTEM).with_config(
            callbacks=[ToolExecutionHandler()]
        )

    def ask_auto_tool_call(self, question: str) -> str:
        """Asks the model one question and lets the agent run the tools.

        ``create_agent`` builds a loop. It runs each tool call, sends the result back to the
        model, and repeats until the reply has no tool calls.

        Args:
            question: the user's question, in plain text

        Returns:
            the model's final text reply
        """
        log.debug("[auto] LangChain runs every tool call. Question: %s", question)
        state = self.agent.invoke({"messages": [HumanMessage(question)]})
        answer: str = state["messages"][-1].text
        log.debug("[auto] Final answer: %s", answer)
        return answer
  • The constructor receives LogTools too. create_app() passes it in.
  • create_agent builds a loop around the chat model and the tools. It runs each tool call for you.
  • The constructor builds the agent once. Each question reuses it.
  • with_config(callbacks=[ToolExecutionHandler()]) logs each tool run, like Spring AI’s Executing tool call line.
  • invoke returns the agent’s state. Its last message is the final answer.

Create LogTools in create_app() and pass it to the Assistant:

def create_app() -> FastAPI:
    """Creates every object and wires them together.

    It plays the part of Spring's application context: one place builds each object once
    and passes it to the constructors that need it.

    Returns:
        the web app, with the ``TestController`` routes
    """
    properties = ApplicationProperties.load()
    chat = AiConfig(properties).chat_model()
    log_tools = LogTools()
    controller = TestController(Assistant(chat, log_tools))
    app = FastAPI(title="harness")
    app.include_router(controller.router)
    return app

The agent runs the tool for you. It does so with middleware, LangChain’s version of advisors. Step 3 explains advisors. Step 4 shows the tool loop.

Step 3: Advisors

ChatClient does not send your request straight to the model. The request first passes through a chain of advisors. An advisor is a class that runs around the model call. It can change the request, change the reply, or skip the model call. Servlet filters work the same way around a controller.

Figure 4.2 shows one request through the chain.

Advisor chainsorted by getOrder(): lower runs first on the way inAssistant.call().content()ToolCallingAdvisorbefore: reads orchanges the requestafter: reads orchanges the replyadded by ChatClientYour advisorslogging, memory, …beforeafteradded by youChatModelCallAdvisorsends the promptreturns the replyalways lastGemmathe model123456
Figure 4.2. The advisor chain. Orange is the request on the way in. Teal is the reply on the way out. Your advisors can sit before or after ToolCallingAdvisor, by their order. Redrawn from the Spring AI reference, Advisors.

The numbers in Figure 4.2 match these steps:

  1. Wrap. ChatClient wraps your prompt in a ChatClientRequest. The request carries an empty context map that advisors can share.
  2. Advise the request. Each advisor reads or changes the request, then passes it to the next advisor.
  3. Call the model. The last advisor, ChatModelCallAdvisor, sends the prompt to the model.
  4. Wrap the reply. The model’s reply comes back as a ChatClientResponse.
  5. Advise the reply. Each advisor reads or changes the reply, in reverse order.
  6. Return. .content() takes the text from the reply.

Each advisor implements one method. This is the interface in Spring AI 2.0.1:

public interface CallAdvisor extends Advisor {
    ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain);
}
  • Code before chain.nextCall(request) runs on the way in.
  • Code after it runs on the way out.
  • An advisor that never calls chain.nextCall skips the model. It must build the reply itself.
  • getOrder() sets the position. The advisor with the lowest number sees the request first and the reply last.

Spring AI ships each common job as one advisor. Table 4.1 lists the built-in advisors.

AdvisorJobCourse topic
ToolCallingAdvisorRuns each tool call and sends the result back to the modelChapter 4. Chapter 5 turns it off.
MessageChatMemoryAdvisorAdds earlier messages of the conversation to the requestMemory, Chapter 10
QuestionAnswerAdvisor, RetrievalAugmentationAdvisorAdd retrieved documents to the requestRetrieval, Chapter 12
SafeGuardAdvisorBlocks a request that contains listed wordsGuardrails, Chapter 7
StructuredOutputValidationAdvisorChecks a JSON reply against a schema and retries on failure
SimpleLoggerAdvisorLogs each request and replyObservability, Part 5

Table 4.1. Built-in advisors in Spring AI 2.0.1. Each one adds a job without changing your model call.

Add an advisor in one of two places:

  • On one request: .advisors(…), next to .user(…).
  • On every request: .defaultAdvisors(…) on the ChatClient.Builder in AiConfig.

The model call code stays the same. Memory, retrieval, and safety each plug into the same chain.

ChatClient adds ToolCallingAdvisor for you. Its order is HIGHEST_PRECEDENCE + 300, near the front of the chain. MessageChatMemoryAdvisor defaults to HIGHEST_PRECEDENCE + 200, so it runs before the tool loop starts. It saves the question and the final answer, not the tool steps. Step 4 shows why the order matters.

LangChain calls advisors middleware. A middleware class overrides the hooks it needs. These are the main hooks of AgentMiddleware in LangChain 1.4 (signatures shortened):

class AgentMiddleware:
    def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: ...
    def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: ...
    def after_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: ...
    def wrap_tool_call(self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage]) -> ToolMessage: ...
  • wrap_model_call plays the part of adviseCall. Code before handler(request) runs on the way in. Code after it runs on the way out.
  • A middleware that never calls handler skips the model. It must return the reply itself.
  • before_model and after_model are shorter hooks for one side only.
  • wrap_tool_call wraps each tool run.
  • The order of the middleware list sets the position. The first middleware sees the request first and the reply last.

LangChain ships each common job as one middleware. Table 4.1 lists the closest match for each Spring AI advisor.

Spring AI advisorLangChain 1.4Course topic
ToolCallingAdvisorBuilt into create_agent: a model node and a tools nodeChapter 4. Chapter 5 uses bind_tools without an agent.
MessageChatMemoryAdvisorA checkpointer on create_agent; SummarizationMiddleware to shorten itMemory, Chapter 10
QuestionAnswerAdvisor, RetrievalAugmentationAdvisorNo built-in middleware. A retrieval tool or a before_model middlewareRetrieval, Chapter 12
SafeGuardAdvisorNo built-in word list. PIIMiddleware blocks or masks personal data. Chapter 7 writes a SafeGuardMiddleware.Guardrails, Chapter 7
StructuredOutputValidationAdvisorresponse_format on create_agent
SimpleLoggerAdvisorNo built-in middleware. A callback handler, like observation_logging.pyObservability, Part 5

Table 4.1. Built-in advisors in Spring AI 2.0.1, and the closest LangChain 1.4 match. Each one adds a job without changing your model call.

Add middleware in one place: create_agent(…, middleware=[…]). The model call code stays the same.

create_agent runs the tool loop as a graph, not as a middleware. Every wrap_model_call middleware wraps each model call inside the loop. To run code once per question, use before_agent or after_agent.

Step 4: The tool calling loop

One .call() can reach the model more than once. ToolCallingAdvisor runs a loop until the model stops asking for tools. Figure 4.3 shows the loop.

ToolCallingAdvisorChatClient adds it when a request has toolsLogTools@Tool countErrorsthe tools you wroteAssistantaskAutoToolCall().tools(logTools)+Messages sentTools: countErrorsSystem: rulesUser: questionAI: tool callTool: 412GemmadecidesToolcall?yesToolCallingManagerfinds and runs the toolTool: 412Append to the historythe tool call and its resultfind and call countErrors(checkout, 15)nofinal answer: .content() returns the text1234
Figure 4.3. The tool calling loop. Orange is one request in and one answer out. Teal is the loop the advisor runs. Redrawn from the Spring AI reference, Tool Calling, for the Log Incident Watcher.

The numbers in Figure 4.3 match these steps:

  1. Send. The advisor sends the messages and the tool definitions to the model. A tool definition holds the name, the description, and the parameters from Figure 4.1.
  2. Decide. The model replies with text or with a tool call. A tool call names the tool and its arguments. It holds no answer.
  3. Run. For a tool call, the advisor does three things:
    1. ToolCallingManager finds the matching tool and calls your method.
    2. The advisor appends the tool call and its result to the history.
    3. The advisor sends the longer history back to the model, at step 1.
  4. Return. A reply with no tool call ends the loop. .content() returns its text to Assistant.
  • Your code calls .call() once. The loop runs inside it. One question about checkout costs two model calls.
  • The model never runs code. It asks. ToolCallingManager runs your method in your app.
  • The model keeps no state. Each model call resends the full history. The list of messages grows by two per tool call.
  • Spring AI caps tool calls only. DefaultToolCallingManager allows 40 calls per tool and 150 in total for each question. Nothing caps tokens or time. Chapter 6 adds those limits.
  • Order decides what runs inside the loop. An advisor with a higher order than ToolCallingAdvisor runs on every model call. An advisor with a lower order runs once for each .call().
  • Your code calls .invoke() once. The agent’s loop runs inside it. One question about checkout costs two model calls.
  • The model never runs code. It asks. The agent’s tools node runs your method in your app.
  • The model keeps no state. Each model call resends the full history. The list of messages grows by two per tool call.
  • LangChain caps nothing by default. The graph stops after 10,007 steps. Add ToolCallLimitMiddleware or ModelCallLimitMiddleware for real limits. Chapter 6 writes its own.
  • Middleware hooks decide what runs inside the loop. wrap_model_call runs on every model call. before_agent and after_agent run once for each .invoke().

Figure 4.4 shows the same run in time order, with the checkout question from Step 5.

Figure 4.4. One .call(), two model calls. Your code sees only the first and last arrows. The figure leaves out ChatModelCallAdvisor, which carries each model call.
  • Arrows 2 and 3 are the first model call. The log shows its completion as [].
  • Arrows 4 to 7 are the tool run. The log shows Executing tool call: countErrors, then the [tool] line.
  • Arrows 8 and 9 are the second model call. Its prompt holds four messages.

Chapter 5 turns the advisor off. Your code then runs steps 3 and 4 itself. Compare Figure 4.4 with Figure 5.4 there.

Step 5: Run it with the tool

Restart the app. Table 4.2 lists three questions and the replies from one run.

QuestionReply
how many error events?Please specify which service you would like to check and the time window (in minutes) for the error count.
how many error events in search service?There were 3 error events in the search service in the last 10 minutes.
how many error events in checkout service?There are currently 412 error events in the checkout service over the last 15 minutes.

Table 4.2. Replies from Gemma with the tool attached. Your wording will differ.

  • Without a service name, the model asks for one. It does not guess.
  • The counts match the fake data: 412 for checkout, 3 for the rest.
  • The model chose minutes itself: 10 and 15. The question gave no window.

Send the last question:

curl -G http://localhost:8080/askAutoToolCall --data-urlencode "input=how many error events in checkout service?"

The three Chapter 4 requests in requests/harness.http send all three questions.

Read the log for a question with a service and a window:

00:15:45.254 DEBUG DispatcherServlet                        GET "/askAutoToolCall?input=how+many+error+events+in+the+checkout+service+in+the+last+15+minutes%3F", parameters={masked}
00:15:45.254 DEBUG Assistant                                [auto] Spring AI runs every tool call. Question: how many error events in the checkout service in the last 15 minutes?
00:15:47.501 INFO  ChatModelCompletionObservationHandler    Chat Model Completion:
[]
00:15:47.501 INFO  ChatModelPromptContentObservationHandler Chat Model Prompt Content:
["You are a careful assistant. Answer in two sentences or fewer.", "how many error events in the checkout service in the last 15 minutes?"]
00:15:47.501 DEBUG DefaultToolCallingManager                Executing tool call: countErrors
00:15:47.503 DEBUG LogTools                                 [tool] countErrors(service=checkout, minutes=15) returned 412
00:15:47.803 INFO  ChatModelCompletionObservationHandler    Chat Model Completion:
["There were 412 error events in the checkout service over the last 15 minutes."]
00:15:47.803 INFO  ChatModelPromptContentObservationHandler Chat Model Prompt Content:
["You are a careful assistant. Answer in two sentences or fewer.", "how many error events in the checkout service in the last 15 minutes?", "", ""]
00:15:47.804 DEBUG Assistant                                [auto] Final answer: There were 412 error events in the checkout service over the last 15 minutes.
00:15:47.804 DEBUG DispatcherServlet                        Completed 200 OK
  • Two model calls for one request. The first reply is a tool call, so its completion is [].
  • Executing tool call: countErrors means Spring AI ran the tool. Your code did not.
  • [tool] shows the arguments the model chose and the result.
  • The second prompt has four messages. The two "" entries are the tool call and the tool result. They hold data, not text.
16:07:21.876 DEBUG harness.assistant                        [auto] LangChain runs every tool call. Question: how many error events in the checkout service in the last 15 minutes?
16:07:21.879 INFO  ChatModelPromptContent                   Chat Model Prompt Content:
['You are a careful assistant. Answer in two sentences or fewer.', 'how many error events in the checkout service in the last 15 minutes?']
16:07:24.634 INFO  httpx2                                   HTTP Request: POST http://localhost:1234/v1/chat/completions "HTTP/1.1 200 OK"
16:07:24.641 INFO  ChatModelCompletion                      Chat Model Completion:
[]
16:07:24.642 DEBUG ToolCalling                              Executing tool call: count_errors
16:07:24.642 DEBUG harness.log_tools                        [tool] count_errors(service=checkout, minutes=15) returned 412
16:07:24.643 INFO  ChatModelPromptContent                   Chat Model Prompt Content:
['You are a careful assistant. Answer in two sentences or fewer.', 'how many error events in the checkout service in the last 15 minutes?', '', '412']
16:07:24.942 INFO  httpx2                                   HTTP Request: POST http://localhost:1234/v1/chat/completions "HTTP/1.1 200 OK"
16:07:24.943 INFO  ChatModelCompletion                      Chat Model Completion:
['There were 412 error events in the checkout service over the last 15 minutes.']
16:07:24.943 DEBUG harness.assistant                        [auto] Final answer: There were 412 error events in the checkout service over the last 15 minutes.
16:07:24.944 INFO  uvicorn.access                           127.0.0.1:55589 - "GET /askAutoToolCall?input=how%20many%20error%20events%20in%20the%20checkout%20service%20in%20the%20last%2015%20minutes%3F HTTP/1.1" 200
  • Two model calls for one request. Each one has an httpx2 line. The first reply is a tool call, so its completion is [].
  • Executing tool call: count_errors means LangChain ran the tool. Your code did not.
  • [tool] shows the arguments the model chose and the result.
  • The second prompt has four messages. The '' entry is the tool call, which holds no text. '412' is the tool result.

Exercise: Rename the tool, then remove its description. Compare the model’s choices each time.

Summary: One @Tool method lets the model answer from data. The description decides when the model calls it.

docs