Building an AI Shirt Agent with Spring AI and Tool Calling
Why a Shirt Recommender Is a Good First Spring AI Project Most tutorials that introduce large language models to Java developers start with a chatbot that answers questions. That is a useful starting point, but it hides the part that makes LLM features valuable inside a real application: the model has to take an action that your code controls. A chatbot that only produces text is a demo. An agent…
Building an AI Shirt Agent with Spring AI and Tool Calling
A language model's knowledge is limited to what it has been trained on, which is public text up to a certain date. It does not have access to your product catalog, inventory, customer records, or internal APIs. Asking a model for a shirt recommendation without any extra help will only result in a guess, not a valid recommendation for a shop to sell.
There are several ways to connect a model to your data, but the most effective method is tool calling. This involves describing a set of Java methods to the model, allowing it to ask for one of those methods to be executed when it needs information or wants to perform an action. Your code then runs the method and returns the result, which the model uses to complete its answer. In the shirts-agent project, this approach is used to retrieve shirt information from a catalog.
The architecture of the shirts-agent project consists of four steps. The request is first received by the ShirtController, which validates the input and passes it to the ShirtService for further processing. The ShirtAgent then asks the model to find a shirt based on the user's input. The model calls the ShirtCatalogTool.findShirtByColor method, which retrieves the appropriate shirt from the catalog, and returns a structured Shirt object.
Invalid input is rejected with HTTP 400 before the model is ever called, emphasizing the importance of validation in ordinary Java code.
The separation of responsibilities between the controller, service, and agent layers is crucial when working with tool calling. This allows for independent testing of validation logic, tool functionality, and model providers without rewriting the business logic. The tool is defined as a Spring bean with a method annotated with @Tool, which the model is allowed to call. The parameter names and descriptions in the @Tool annotation are important, as the model relies on them to correctly fill in the arguments.
By returning structured data, such as a Shirt object, the recommendation becomes easy to use in an application, test, and downstream services. Structured output reduces the number of bugs caused by parsing free-form text and makes changes easier to manage.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.