Building AI Agents with Spring AI Agent and Querier
On December 3, 2026, the Spring team announced Spring AI Agent, a new project bringing type-safe agentic foundations to Java and Kotlin.
Built on top of Spring AI 2.1, the project introduces a different approach to building AI agents in the Spring ecosystem. Rather than focusing exclusively on model interaction and tool calling, it provides abstractions for composing agents, orchestrating workflows using strongly typed graphs, managing execution contexts, handling interruptions, and building more durable agentic applications.
I wanted to explore how Querier, specifically its core module, can fit into this new ecosystem.
The idea is to use Spring AI Agent for everything related to agent orchestration and LLM interaction, while using Querier Core as our type-safe SQL construction layer.
We will build a small commerce analytics assistant that can answer questions about products, orders, customers, and sales using our existing Java domain models.
The goal isn't to build another natural-language-to-SQL solution. Instead, we want to demonstrate how existing Java applications can expose their business capabilities as tools that AI agents can intelligently use.
Let's explore the architecture and the possibilities.
1. Understanding Spring AI Agent
Before writing code, let's understand what Spring AI Agent brings to the table.
The Spring AI team describes an agent as a model plus a harness.
Spring AI already provides ChatClient, which can be used to build agents with model interaction, instructions, memory and tool calling.
Spring AI 2.1 added important capabilities such as session memory with compaction, tool-call confirmation, and reasoning preservation across model interactions.
Spring AI Agent takes these foundations further by introducing dedicated abstractions for agent composition and orchestration.
Some of its main capabilities include:
- A common, strongly typed
Agent<I, O>abstraction. - Graph-based agent orchestration using
GraphAgentandModelGraphAgent. - Integration with existing
ChatClientimplementations. - Agent composition and reusable subagents.
- Parallel execution and selection policies.
- Execution contexts and event-based observability.
- Hooks, interceptors and listeners.
- Session management and checkpoint-based durability.
- Human-in-the-loop workflows.
- Agent-to-Agent (A2A) protocol interoperability.
An important distinction is that Spring AI Agent is currently an incubating project under Spring Projects Experimental. The announced plan is to merge it into Spring AI 3.0, expected in May 2027.
This means we should keep an eye on API evolution when adopting it in production.
2. Understanding the Agent abstraction
The central abstraction introduced by Spring AI Agent is:
Agent<I, O> Here, I represents the input type and O represents the output type.
These types can simply be strings, but they can also be Java records representing business requests and responses.
The interface provides synchronous and asynchronous execution:
// Synchronous execution AgentRunResult<O> result(I input); // Resume an interrupted execution <R> AgentRunResult<O> resumeResult( RunIdentification runId, R answer ); // Asynchronous execution AgentRun<O> run(I input); // Resume an asynchronous execution <R> AgentRun<O> resumeRun( RunIdentification runId, R answer ); This abstraction is interesting because it makes agents composable.
An application doesn't need to know whether an agent internally uses a ChatClient, a graph containing multiple model calls, a collection of deterministic Java functions, or even a remote agent.
It can interact with all of them through a common contract.
For example, consider the following business types:
public record AnalyticsRequest( String question ) {} public record AnalyticsResponse( String summary, List<String> findings ) {} We can build an agent accepting AnalyticsRequest and returning AnalyticsResponse.
The benefit is that our application can work with strongly typed domain objects instead of passing strings between every component.
This becomes particularly useful when building workflows containing several specialized agents.
3. The application we are building
Our example will use a small commerce domain.
We already have the following entities:
-
Product: represents products available in our stock, with an identifier, name and price. -
Order: represents customer orders, including their associated product, total, status and creation date. -
Customer: contains customer information. -
OrderStatus: represents the possible lifecycle states of an order.
Our order statuses are:
public enum OrderStatus { PENDING, PAID, SHIPPED, DELIVERED, CANCELLED } We will reuse the supplied JPA entities:
@Entity(name = "products") @Table(name = "products") public class Product { @Id private Long id; private String name; private BigDecimal price; public Long getId() { return id; } public String getName() { return name; } public BigDecimal getPrice() { return price; } } @Entity(name = "orders") @Table(name = "orders") public class Order { @Id private Long id; private Long customerId; private Long productId; private BigDecimal total; @Enumerated(EnumType.STRING) private OrderStatus status; private LocalDate createdAt; public Long getId() { return id; } public Long getCustomerId() { return customerId; } public Long getProductId() { return productId; } public BigDecimal getTotal() { return total; } public OrderStatus getStatus() { return status; } public LocalDate getCreatedAt() { return createdAt; } } @Entity(name = "customers") @Table(name = "customers") public class Customer { @Id private Long id; private String name; private String email; public Long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } } The snippets focus on the attributes and accessors needed for our queries. The actual entities can retain their setters, constructors and other methods.
Notice that we are using JPA annotations for table and column mappings. Querier Core supports Jakarta Persistence annotations and can also infer snake_case column names from Java property names.
We will provide business semantics through Spring AI tool descriptions and agent instructions.
4. Dependencies and LLM configuration
Let's prepare our Spring Boot application.
We will use:
| Component | Version |
|---|---|
| Java | 17+ (17.0.19 or later) |
| Spring Boot | 4.2.x |
| Spring AI | 2.1.0 |
| Spring AI Agent | 0.8.0 |
| Querier Core | 2.0.4 |
| Database | PostgreSQL |
Spring AI 2.1 is built on Spring Boot 4.2.
Maven dependencies
First, import the Spring AI BOM:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>2.1.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> Then add the dependencies:
<dependencies> <!-- Querier Core --> <dependency> <groupId>com.aytmatech</groupId> <artifactId>querier-core</artifactId> <version>2.0.4</version> </dependency> <!-- Spring AI Agent --> <dependency> <groupId>org.springframework.experimental.ai</groupId> <artifactId>spring-ai-agent</artifactId> <version>0.8.0</version> </dependency> <!-- OpenAI Chat Model --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId> </dependency> <!-- Database access --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- JPA annotations used by our domain entities --> <dependency> <groupId>jakarta.persistence</groupId> <artifactId>jakarta.persistence-api</artifactId> </dependency> <!-- PostgreSQL --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> </dependencies> The application can also include spring-boot-starter-web if we want to expose our agent through REST endpoints.
Configure the LLM API credentials
Spring AI's model integrations are separate from the agent orchestration layer.
Spring AI Agent doesn't require us to hardcode or manually manage an OpenAI client. We can use Spring Boot auto-configuration to create the ChatModel bean.
For this tutorial, we will use OpenAI compatible API.
Set it as an environment variable instead.
Linux/macOS:
export LLM_BASE_URL="your-base-url" export LLM_API_KEY="your-api-key" export LLM_MODEL="your-model" Windows PowerShell:
$env:LLM_BASE_URL="your-base-url" $env:LLM_API_KEY="your-api-key" $env:LLM_MODEL="your-model" Now configure application.yml:
spring: ai: openai: base-url: ${LLM_BASE_URL} api-key: ${LLM_API_KEY} chat: options: model: ${LLM_MODEL} datasource: url: jdbc:postgresql://localhost:5432/commerce username: ${DB_USERNAME} password: ${DB_PASSWORD} The important properties are:
-
spring.ai.openai.base-url: base URL endpoint of the OpenAI compatible API. -
spring.ai.openai.api-key: credentials used to authenticate against the OpenAI compatible API. -
spring.ai.openai.chat.options.model: the model used for chat and tool-calling interactions.
The model can be changed through the environment variable without modifying application code.
Spring AI supports other model providers and OpenAI-compatible endpoints as well. You can replace the OpenAI starter and provider configuration while keeping the main agent architecture.
5. Querier Core: Building business-oriented database tools
Now let's integrate Querier.
The approach is simple: we expose specific database capabilities as Java methods and let the LLM decide which capabilities to invoke.
The model doesn't generate SQL.
Instead, it receives the description of available tools and determines which one is appropriate for the user's request.
Each tool uses Querier Core to construct its query, and Spring JDBC executes the generated SQL.
Product catalog tool
Let's start with a tool for searching products within a price range.
@Component public class ProductCatalogTools { private final NamedParameterJdbcTemplate jdbc; public ProductCatalogTools(NamedParameterJdbcTemplate jdbc) { this.jdbc = jdbc; } @Tool(description = """ Search products in the product catalog by price range. Products can also be referred to as items, merchandise or goods. Returns product identifiers, names and prices. """) public List<Map<String, Object>> findProductsByPriceRange( @ToolParam(description = "Minimum product price") BigDecimal minPrice, @ToolParam(description = "Maximum product price") BigDecimal maxPrice, @ToolParam(description = "Maximum number of results, between 1 and 50") int limit) { if (minPrice.compareTo(maxPrice) > 0) { throw new IllegalArgumentException( "Minimum price cannot exceed maximum price" ); } int safeLimit = Math.clamp(limit, 1, 50); Select query = Select.builder() .select(Product::getId) .select(Product::getName) .select(Product::getPrice) .from(Product.class) .where(Condition.and( Condition.gte(Product::getPrice, minPrice), Condition.lte(Product::getPrice, maxPrice) )) .orderBy(OrderBy.asc(Product::getPrice)) .limit(safeLimit) .build(); Select.SqlAndParams statement = query.toSqlAndParams(); return jdbc.queryForList( statement.sql(), statement.params() ); } } There are several interesting things here.
First, the LLM only sees the business operation:
findProductsByPriceRange
It doesn't need to know that the application uses Querier, PostgreSQL or Spring JDBC.
Second, Querier provides type-safe column references:
.select(Product::getId) .select(Product::getName) .select(Product::getPrice) We also have a composable condition:
.where(Condition.and( Condition.gte(Product::getPrice, minPrice), Condition.lte(Product::getPrice, maxPrice) )) Finally, the generated SQL and parameters are separated:
Select.SqlAndParams statement = query.toSqlAndParams(); This is directly compatible with Spring's NamedParameterJdbcTemplate.
Order analytics tools
Let's introduce more interesting database operations.
Our order analytics tools will allow the agent to retrieve orders by status and identify the products generating the highest revenue.
@Component public class OrderAnalyticsTools { private final NamedParameterJdbcTemplate jdbc; public OrderAnalyticsTools(NamedParameterJdbcTemplate jdbc) { this.jdbc = jdbc; } @Tool(description = """ Retrieve recent customer orders filtered by their lifecycle status. Available statuses are PENDING, PAID, SHIPPED, DELIVERED and CANCELLED. Use this for questions about order tracking and order status. """) public List<Map<String, Object>> findOrdersByStatus( @ToolParam(description = "Requested order status") OrderStatus status, @ToolParam(description = "Maximum number of orders, between 1 and 50") int limit) { int safeLimit = Math.clamp(limit, 1, 50); Select query = Select.builder() .select(Order::getId) .select(Order::getCustomerId) .select(Order::getProductId) .select(Order::getTotal) .select(Order::getStatus) .select(Order::getCreatedAt) .from(Order.class) .where(Condition.eq(Order::getStatus, status)) .orderBy(OrderBy.desc(Order::getCreatedAt)) .limit(safeLimit) .build(); Select.SqlAndParams statement = query.toSqlAndParams(); return jdbc.queryForList( statement.sql(), statement.params() ); } @Tool(description = """ Find the best-selling products based on revenue from paid orders. Returns product names and total revenue. Use this for questions about product performance and sales. """) public List<Map<String, Object>> topProductsByRevenue( @ToolParam(description = "Maximum number of products, between 1 and 20") int limit) { int safeLimit = Math.clamp(limit, 1, 20); Select query = Select.builder() .select(Product::getName) .select(Aggregate.sum(Order::getTotal).as("revenue")) .from(Order.class) .join( Product.class, Condition.eq(Order::getProductId, Product::getId) ) .where(Condition.eq(Order::getStatus, OrderStatus.PAID.name())) .groupBy(Product::getName) .orderBy( OrderBy.desc( Aggregate.sum( Order::getTotal ).toSqlWithoutAlias() ) ) .limit(safeLimit) .build(); Select.SqlAndParams statement = query.toSqlAndParams(); return jdbc.queryForList( statement.sql(), statement.params() ); } } This example demonstrates a more interesting capability of Querier Core.
We are using:
- Type-safe JOIN conditions.
- Aggregate functions.
- GROUP BY.
- ORDER BY.
- Named parameter generation.
The query builder remains independent of the database execution mechanism.
Customer analytics
We can also expose customer spending analytics using the same approach.
For example, a tool that identifies the highest-spending customers:
Select query = Select.builder() .select(Customer::getName) .select(Aggregate.sum(Order::getTotal).as("total_spend")) .from(Order.class) .join( Customer.class, Condition.eq(Order::getCustomerId, Customer::getId) ) .where(Condition.eq(Order::getStatus, OrderStatus.PAID)) .groupBy(Customer::getName) .orderBy( OrderBy.desc( Aggregate.sum( Order::getTotal ).toSqlWithoutAlias() ) ) .limit(10) .build(); The same pattern can be extended to customer purchase history, average order values, monthly revenue and other business analytics operations.
The important design decision is that each Java method represents a business capability, not an unrestricted SQL execution endpoint.
6. Building our first ModelGraphAgent
Now that we have database tools, let's connect them to Spring AI Agent.
For our first implementation, we will use ModelGraphAgent and the built-in ToolCallLoop.
Why?
Because we want the model to:
- Understand the user's question.
- Select the appropriate database tool.
- Execute the requested operation.
- Inspect the returned data.
- Produce a final natural-language answer.
The ToolCallLoop provides this repeated model/tool interaction as a reusable graph.
Let's configure the agent:
@Configuration public class CommerceAgentConfiguration { @Bean Agent<String, String> commerceAssistant( ChatModel chatModel, ProductCatalogTools productCatalogTools, OrderAnalyticsTools orderAnalyticsTools) { return ModelGraphAgent .builder(ToolCallLoop.create(), chatModel) .instructions(""" You are a commerce analytics assistant. Your responsibility is to answer questions about: - Products and p...