Enterprise Java

Spring AI Agent Skills Example

Large Language Models (LLMs) excel at reasoning, generating natural language, and answering complex questions, but enterprise AI applications require capabilities that go far beyond conversational responses. Modern AI agents must interact with business systems by retrieving customer information, checking inventory, booking appointments, querying databases, sending emails, and invoking enterprise APIs. Spring AI addresses this need by enabling developers to expose Java methods as AI tools, allowing language models to perform real business operations. As applications grow, organizing these tools into reusable, domain-specific modules becomes essential. These collections of related tools, known as Agent Skills, group business capabilities such as Customer, Weather, Inventory, Finance, HR, and Travel into logical units, resulting in AI applications that are more modular, maintainable, reusable, and easier to extend.

1. Introduction to Agent Skills in Spring AI

An Agent Skill is a logical collection of closely related AI tools that work together to provide a specific business capability. Rather than exposing numerous unrelated tools to an AI agent, enterprise applications organize them into domain-specific skills, making the application easier to develop, maintain, and scale. For example, a system might define separate skills such as Customer Skill, Order Skill, Inventory Skill, Payment Skill, Flight Booking Skill, and Employee Skill, with each skill exposing only the operations relevant to its business domain. Conceptually, a Tool represents a single capability, such as retrieving customer details or checking inventory, a Skill groups multiple related tools into a reusable business module, and an Agent combines one or more skills to understand user requests and invoke the appropriate tools to complete a task.

1.1 What are Agent Skills?

An Agent Skill is a reusable module that contains multiple AI tools focused on a specific business domain. Instead of defining and managing individual tools throughout different parts of an application, skills organize related capabilities together and provide a clear separation of concerns. This modular approach improves code organization, reusability, and maintainability while allowing AI agents to access domain-specific capabilities in a structured way.

1.2 Understanding Tools, Skills, and Agents

SkillTools
Customer SkillfindCustomer(), getOrders(), updateCustomer()
Inventory SkillcheckStock(), reserveStock(), releaseStock()
Weather SkillcurrentWeather(), forecast()
Flight SkillsearchFlights(), seatAvailability(), flightStatus()

The AI agent receives the required skills as part of its available capabilities and intelligently determines which tool should be invoked based on the user’s request. This allows developers to build flexible AI systems where agents can dynamically select and execute the appropriate business operation without requiring hardcoded decision logic.

1.3 Advantages of Agent Skills

  • Better code organization
  • High reusability
  • Domain-driven design
  • Simplified maintenance
  • Easier testing
  • Independent business modules
  • Scales well for enterprise applications
  • Supports multi-agent architectures

1.4 Best Practices for Designing Agent Skills

  • Group related tools into a single skill.
  • Keep each tool focused on one responsibility.
  • Write meaningful tool descriptions.
  • Avoid placing business logic directly inside tool methods.
  • Delegate work to service classes.
  • Return structured objects whenever possible.
  • Keep skills independent and reusable.
  • Register only the skills required by the agent.

2. Building Agent Skills with Spring AI: A Complete Example

In this section, we will build a Spring Boot application that demonstrates how to create and integrate Agent Skills using Spring AI. To keep the example focused and easy to understand, we will cover the main classes responsible for AI integration, skill creation, and execution flow. Standard Spring Boot classes, boilerplate configurations, and supporting classes that do not directly contribute to the Agent Skill implementation have been omitted for brevity.

2.1 Maven Dependencies

The following Maven dependencies are required to build a Spring AI application with OpenAI integration and expose REST endpoints using Spring Boot. The Spring AI starter provides the required AI model integration, while Spring Web enables the creation of web-based APIs.

<dependencies>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-openai</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

The spring-ai-starter-model-openai dependency provides the integration between Spring Boot and OpenAI models, allowing the application to communicate with Large Language Models through Spring AI abstractions. The spring-boot-starter-web dependency adds support for building REST APIs by providing Spring MVC, embedded server support, and HTTP request handling capabilities. Together, these dependencies create the foundation for developing an AI-powered Spring Boot application where users can interact with language models through web endpoints.

2.2 Configuring Spring AI with OpenAI Model

The application configuration file defines the connection details required for Spring AI to communicate with the OpenAI model. It specifies the API key required for authentication and configures the language model that will be used by the AI agent. The OpenAI API key acts as a secure credential that allows the Spring Boot application to access OpenAI models and process AI requests. To generate an OpenAI API key, visit the OpenAI Platform, sign in with your account, navigate to the API Keys section, and click on the Create new secret key option. Once generated, copy the API key and configure it in your Spring Boot application. For production environments, it is recommended to store the API key using environment variables or secret management solutions instead of directly adding it to the configuration file.

spring:
  ai:
    openai:
      api-key: YOUR_API_KEY
      chat:
        options:
          model: gpt-4.1

The spring.ai.openai.api-key property provides the authentication credential required to access OpenAI services. The chat.options.model property specifies the LLM model that Spring AI should use for processing user requests and generating responses. In this example, the application is configured to use the gpt-4.1 model, which will handle conversations, reasoning, and tool selection for the AI agent. By externalizing these settings in application.yml, the application configuration remains separate from the source code and can be easily changed across different environments.

2.3 Implementing the Customer Service Layer

The Customer Service class contains the core business logic for managing customer-related operations. This service is responsible for retrieving customer information and customer orders, while keeping the business logic independent from the AI layer. The AI agent will later invoke these methods through an Agent Skill.

package com.example.service;

import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CustomerService {
  private final Map < Integer, String > customers = Map.of(
    1, "John Smith",
    2, "Alice Johnson",
    3, "Michael Brown"
  );

  public String findCustomer(int id) {
    return customers.getOrDefault(id, "Customer not found");
  }

  public String customerOrders(int id) {
    return switch (id) {
		case 1 -> "Laptop, Mouse";
		case 2 -> "Keyboard";
		case 3 -> "Monitor, Webcam";
		default -> "No Orders";
    };
  }
}

The @Service annotation registers the CustomerService class as a Spring-managed service component. The customers map acts as a simple in-memory data store containing customer IDs and names. The findCustomer() method retrieves a customer’s name based on the provided ID and returns a default message when the customer does not exist. The customerOrders() method uses a Java switch expression to return the list of orders associated with a specific customer ID. This service layer keeps the business operations separate from the AI tool definitions, following a clean architecture approach where Agent Skills can reuse existing application services.

2.4 Creating the Customer Agent Skill

The Customer Skill acts as a bridge between the AI agent and the underlying customer business logic. It exposes customer-related operations as AI tools that can be automatically discovered and invoked by the language model based on the user’s request.

package com.example.skills;

import com.example.service.CustomerService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Component;

@Component
public class CustomerSkill {

  private final CustomerService service;

  public CustomerSkill(CustomerService service) {
    this.service = service;
  }

  @Tool(description = "Find customer by id")
  public String findCustomer(int id) {
    return service.findCustomer(id);
  }

  @Tool(description = "Retrieve customer orders")
  public String customerOrders(int id) {
    return service.customerOrders(id);
  }
}

The @Component annotation registers the CustomerSkill class as a Spring-managed component, allowing it to be injected into other application components. The class uses constructor injection to receive an instance of CustomerService, which contains the actual business logic. The @Tool annotation from Spring AI exposes Java methods as tools that the AI agent can invoke. The description provided in the annotation helps the language model understand when a specific tool should be selected. In this example, findCustomer() allows the AI agent to retrieve customer details, while customerOrders() enables the agent to fetch customer order information. This separation keeps AI-specific logic inside the skill layer while reusing existing business services.

2.5 Creating the Weather Agent Skill

The Weather Skill demonstrates how an AI agent can access external domain capabilities through a dedicated skill module. Similar to the Customer Skill, this class exposes weather-related operations as AI tools, allowing the language model to automatically invoke the appropriate method when a user asks for weather information.

package com.example.skills;

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

@Component
public class WeatherSkill {

  @Tool(description = "Current weather")
  public String currentWeather(String city) {
    return "Weather in " + city + " : 24°C, Sunny";
  }
}

The @Component annotation registers the WeatherSkill class as a Spring-managed component so that it can be discovered and injected into the AI agent configuration. The @Tool annotation exposes the currentWeather() method as an AI-callable tool. The tool description provides context to the language model, helping it understand when this capability should be selected. When a user asks about the weather for a specific city, the AI agent identifies the request, selects the Weather Skill, invokes the currentWeather() method, and uses the returned information to generate the final response. In a real-world application, this method can be extended to integrate with external weather APIs and return real-time weather data.

2.6 Registering Agent Skills with Spring AI Chat Client

The Chat Client configuration connects the Spring AI application with the available Agent Skills. This configuration registers the skills that the AI agent can access, allowing the language model to discover and invoke the appropriate tools based on user requests.

package com.example.config;

import com.example.skills.CustomerSkill;
import com.example.skills.WeatherSkill;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ChatConfig {

    @Bean
    ChatClient chatClient(ChatClient.Builder builder,
                          CustomerSkill customerSkill,
                          WeatherSkill weatherSkill){
        return builder
                .defaultTools(customerSkill,
                              weatherSkill)
                .build();
    }
}

The @Configuration annotation marks this class as a Spring configuration component where application beans can be defined. The chatClient() method creates and configures a ChatClient bean using Spring AI’s ChatClient.Builder. The CustomerSkill and WeatherSkill components are injected through constructor parameters and registered as default tools using the defaultTools() method. Once registered, these skills become available to the AI agent during conversations. When a user sends a request, the language model analyzes the intent, selects the relevant skill and tool, executes the corresponding Java method, and uses the returned result to generate the final response.

2.7 Building the REST API Controller

The REST Controller provides an HTTP endpoint that allows users or external applications to interact with the AI agent. It receives user messages, sends them to the Spring AI Chat Client, and returns the AI-generated response.

package com.example.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/chat")
public class ChatController {

  private final ChatClient chatClient;

  public ChatController(ChatClient chatClient) {
    this.chatClient = chatClient;
  }

  @GetMapping
  public String chat(@RequestParam String message) {
    return chatClient.prompt()
      .user(message)
      .call()
      .content();
  }
}

The @RestController annotation marks this class as a Spring MVC controller that handles HTTP requests and returns responses directly. The @RequestMapping("/chat") annotation defines the base URL path for AI interactions. The ChatClient instance is injected through constructor injection and is responsible for communicating with the language model. The chat() method accepts a user message through the @RequestParam annotation and passes it to the AI model using the prompt() and user() methods. The call() method triggers the AI request, where the model analyzes the prompt, determines whether any registered Agent Skill or tool needs to be invoked, executes the required operation, and generates the final response returned through the content() method.

2.8 Running the Application and Understanding Agent Execution Flow

After completing the configuration and registering the required Agent Skills, run the Spring Boot application using the following command. Once the application starts successfully, the AI agent endpoint will be available to process user requests.

mvn spring-boot:run

The application starts on the default Spring Boot port 8080. Users can now send natural language queries through the REST endpoint. The Chat Controller receives the request, forwards it to the Spring AI Chat Client, and the AI agent determines the appropriate skill and tool required to complete the request.

In the following example, the user wants to retrieve customer information. The AI agent analyzes the request, identifies that customer-related data is required, selects the Customer Skill, and invokes the appropriate tool to fetch the required information.

GET http://localhost:8080/chat?message=Who%20is%20customer%202?

When the above request is received, the application processes the request through the Agent execution workflow. The generated application logs show how the request moves from the REST layer to the AI agent, skill selection, tool execution, business service invocation, and final response generation.

2026-07-26 10:15:32 INFO  SpringApplication : Started SpringAiApplication in 3.8 seconds
2026-07-26 10:16:10 INFO  ChatController   : Received user message: Who is customer 2?
2026-07-26 10:16:10 INFO  ChatClient       : Sending prompt to LLM
2026-07-26 10:16:11 INFO  AgentExecutor    : Analyzing user intent
2026-07-26 10:16:11 INFO  AgentExecutor    : Identified required capability: Customer Information
2026-07-26 10:16:11 INFO  AgentExecutor    : Selected Skill: Customer Skill
2026-07-26 10:16:11 INFO  AgentExecutor    : Selected Tool: findCustomer(2)
2026-07-26 10:16:11 INFO  CustomerService  : Searching customer details for id: 2
2026-07-26 10:16:11 INFO  CustomerService  : Customer found: Alice Johnson
2026-07-26 10:16:11 INFO  AgentExecutor    : Tool execution completed
2026-07-26 10:16:11 INFO  AgentExecutor    : Tool Response: Alice Johnson
2026-07-26 10:16:12 INFO  ChatClient       : Generating final AI response
2026-07-26 10:16:12 INFO  ChatController   : Response sent successfully

After the tool execution completes, the returned information is provided back to the LLM as additional context. The LLM uses this information to generate a user-friendly response instead of exposing the internal tool execution details.

Customer 2 is Alice Johnson.

This execution demonstrates how Spring AI enables an agent-based workflow where the LLM understands the user’s intent, selects the appropriate Agent Skill, invokes the required tool, executes the underlying Java business logic, and generates a final response without requiring manually written routing logic.

3. Conclusion

Agent Skills provide a clean and scalable way to organize AI capabilities in Spring AI. Instead of exposing dozens of unrelated tools to an AI model, developers can package related business operations into cohesive skills that are easy to maintain and reuse. This approach encourages modular design, improves readability, and simplifies testing while allowing the language model to dynamically select the most appropriate tool during a conversation. As enterprise AI applications continue to grow in complexity, organizing functionality into domain-specific skills becomes increasingly valuable. Whether building customer support agents, travel assistants, HR bots, inventory systems, or financial advisors, Agent Skills offer a practical architectural pattern for creating maintainable, extensible, and production-ready Spring AI applications.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button