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.
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:
Agent<I, O> abstraction.GraphAgent and ModelGraphAgent. ChatClient implementations.
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.
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.
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.
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.
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.
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.
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.
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.
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:
The query builder remains independent of the database execution mechanism.
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.
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:
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 product prices
- Orders and their lifecycle statuses
- Product sales and revenue
- Customer spending
Business terminology:
- Product, item, merchandise and goods refer to products.
- Sales revenue means revenue from PAID orders.
- Order statuses are PENDING, PAID, SHIPPED,
DELIVERED and CANCELLED.
Rules:
- Use the available tools whenever actual database
information is needed.
- Never invent products, customers, orders or figures.
- Never claim that a query succeeded when it failed.
- Only report information returned by the tools.
- Do not expose customer emails or other unnecessary
personal information.
- The available database operations are read-only.
""")
.tools(productCatalogTools, orderAnalyticsTools)
.build();
}
}
Let's understand what happens here.
Unlike a traditional ChatClient-based implementation, ModelGraphAgent allows the agent itself to be represented by a graph.
The graph defines how the agent processes its input and produces its output.
In our case:
ModelGraphAgent.builder(ToolCallLoop.create(), chatModel)
We are using the built-in tool-calling graph.
We provide the ChatModel, which is the model interface auto-configured by Spring AI.
The instructions provide the business context and behavioral rules.
Notice that we are also providing terminology mappings.
For example, users might ask about:
All these terms refer to the same business concept.
We can communicate this information through the agent instructions and tool descriptions without introducing Querier's AI module.
.tools(productCatalogTools, orderAnalyticsTools)
This makes the methods annotated with @Tool available to the model.
The model can now decide whether it needs product information, order information or sales analytics.
The application remains responsible for executing the actual database operations.
The Agent<I, O> abstraction gives us a consistent way to interact with our agent.
We can create a regular Spring service:
@Service
public class CommerceAssistantService {
private final Agent<String, String> commerceAssistant;
public CommerceAssistantService(
Agent<String, String> commerceAssistant) {
this.commerceAssistant = commerceAssistant;
}
public String ask(String question) {
return commerceAssistant.result(question).output();
}
}
For example:
String answer = commerceAssistantService.ask(
"Which are our top 5 products by revenue?"
);
The model should recognize that it needs sales information and invoke:
topProductsByRevenue(5)
The tool executes the Querier-generated SQL and returns the records.
The model then uses the returned data to construct its answer.
Other possible questions:
Find products priced between 50 and 150.
Show me the latest 10 cancelled orders.
Which customers generated the highest revenue?
How many paid orders can we inspect?
The agent can select the appropriate tool based on the meaning of the request.
The actual response depends on our database contents.
This is where Spring AI Agent becomes particularly interesting.
We have so far built one agent using a model and a set of tools.
But we don't have to put all business capabilities into one agent.
We can split the application into specialized agents, each with its own tools, instructions, model configuration and permissions.
Commerce Assistant
|
-----------------------
| |
Product Agent Order Agent
| |
Product Tools Order Tools
| |
Querier Core Querier Core
| |
PostgreSQL PostgreSQL
The Product Agent only needs access to product-related queries.
The Order Agent only needs access to order-related queries.
A coordinator can decide which agent should handle a particular question.
This gives us a natural way to implement least-privilege database access.
Spring AI Agent provides AgentTools.asToolCallback(agent).
This is particularly interesting because it allows one agent to be exposed as a tool that another model can invoke.
For this case we need to wrap the subagent's input in a Java record (or POJO) instead of using String as the input type:
public record CommerceRequest(
@ToolParam(description = "The topic or question to research") String query
) {}
We map record to user prompt with:
Graph<CommerceRequest, String> toolCallLoop = ToolCallLoop.builder()
.inputType(CommerceRequest.class, CommerceRequest::query)
.outputType(String.class)
.build();
Since ToolCallLoop is simply a stateless Graph<I, O> topology definition. It defines the execution flow (model node → conditional check → tool execution node → loop back) without holding mutable execution state, agent-specific system prompts, or agent-specific tools. We can share it safely between the subagents and the coordinator agent.
For example, we can create our specialized agents:
Agent<CommerceRequest, String> productAgent =
ModelGraphAgent.builder(toolCallLoop, chatModel)
.name("product-agent")
.description("Handles product catalog and pricing questions")
.instructions("You are a product catalog specialist.")
.tools(productCatalogTools)
.build();
Agent<CommerceRequest, String> orderAgent =
ModelGraphAgent.builder(toolCallLoop, chatModel)
.name("order-agent")
.description("Handles orders, customer spending and sales analytics")
.instructions("You are an order and sales analytics specialist.")
.tools(orderAnalyticsTools)
.build();
Now expose them to a coordinator agent:
Agent<CommerceRequest, String> commerceCoordinator =
ModelGraphAgent.builder(toolCallLoop, chatModel)
.instructions("""
You coordinate commerce-related questions.
Delegate product catalog questions to the product agent.
Delegate order and sales analytics questions to the order agent.
Combine the results when the question requires both specialists.
Do not invent information.
""")
.toolCallbacks(
AgentTools.asToolCallback(productAgent),
AgentTools.asToolCallback(orderAgent)
)
.build();
The important distinction is that the coordinator's model decides when to delegate to a specialist.
Each subagent runs with its own execution context and conversation behavior.
This is different from a graph-driven subagent, where the graph determines which agent runs next.
Another interesting abstraction is GraphAgent.
Unlike ModelGraphAgent, a GraphAgent doesn't need its own model. It orchestrates other agents and deterministic Java operations through a graph.
For example, imagine that we want to generate an analytics report and then have another agent review it.
We could use:
Agent<String, String> analyst = commerceCoordinator;
ChatClient reviewerClient = ChatClient.builder(chatModel)
.defaultSystem("""
You are an analytics report reviewer.
Check the consistency and clarity of the supplied report.
""")
.build();
Agent<String, String> reviewer =
ChatClientAgent.of(reviewerClient);
Graph<CommerceRequest, String> reportingGraph =
Graph.sequence(
AgentNodes.subAgent("analysis", analyst)
)
.then(
AgentNodes.subAgent("review", reviewer)
)
.build();
Agent<CommerceRequest, String> reportingAgent =
GraphAgent.builder(reportingGraph).build();
The execution is deterministic:
The GraphAgent doesn't need another LLM to decide this sequence.
The graph itself controls the workflow.
This separation between model-driven decisions and deterministic orchestration is one of the most interesting aspects of the new architecture.
Another interesting part of Spring AI Agent is its execution model.
The Agent abstraction supports both synchronous and asynchronous execution.
For simple requests:
AgentRunResult<String> result =
commerceCoordinator.result(question);
String answer = result.output();
For asynchronous execution:
try (AgentRun<String> run = commerceCoordinator.run(question)) {
Source<AgentEvent> events = run.events();
while (events.receiveNext()) {
AgentEvent event = events.next();
// Observe run, model, node and tool events.
// ModelFrameEvent can be used to inspect streamed output.
}
}
Or run asynchronously with a CompletableFuture:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try (AgentRun<String> run = commerceCoordinator.run(question)) {
return run.output();
} catch (InterruptedException e) {
log.error("Interrupted while processing question: {}", question, e);
Thread.currentThread().interrupt();
throw new CompletionException(e);
}
}, agentTaskExecutor);
The new Source<T> abstraction provides a virtual-thread-friendly way to consume events.
On Java 21 and later, execution can use virtual threads underneath. Java 17 remains supported through platform-thread execution.
It is worth noting that this is an imperative streaming model, not simply another reactive API.
For example, an application could use the event stream to:
The AgentRunResult also exposes execution information such as the run identification, conversation messages and aggregated model usage.
This gives us useful foundations for monitoring and understanding complex agent workflows.
For production applications, simply invoking a model and executing tools isn't enough.
We need to think about conversation persistence, recoverability, observability and execution control.
Spring AI Agent introduces a feature mechanism that can extend the agent execution pipeline.
There are three important extension points.
Hooks
Hooks participate in execution lifecycle boundaries, such as run start, completion, failure and interruption.
They can be useful for initializing execution context, attaching metadata or performing cleanup.
Interceptors
Interceptors wrap operations such as model calls, tool calls and graph node execution.
They can inspect or modify arguments and results, implement retries, or skip operations.
This is interesting for implementing cross-cutting policies such as input validation, data redaction and tool-call controls.
Listeners
Listeners observe events asynchronously.
They can be used for:
The framework also provides two important durability features.
SessionFeature integrates with Spring AI Session to maintain conversations across runs.
It also supports conversation compaction.
This is useful when an assistant needs to retain context across multiple user interactions without repeatedly sending the complete conversation history.
It is provided by the optional spring-ai-agent-session module.
CheckpointFeature allows agent executions to resume after interruptions or failures.
The framework can persist checkpoints after graph nodes and tool-call rounds.
This is particularly useful for long-running workflows or human approval processes.
Generate report
|
v
Validate report
|
v
Request human approval
|
v
Save checkpoint
|
v
Wait for approval
|
v
Resume execution
|
v
Continue workflow
The spring-ai-agent-checkpoint module provides the checkpoint feature.
Both features are optional and should be introduced when the application actually needs them.
Giving AI agents access to business data requires carefully designed boundaries.
A few recommendations for our implementation:
Use least privilege.
The Product Agent should not have access to customer data or order operations unless required.
Avoid unrestricted SQL execution.
Don't expose a generic method that accepts an SQL string generated by the model. Keep SQL construction and permitted operations under application control.
Validate tool arguments.
The LLM is not a trusted source of input. Validate price ranges, result limits, identifiers and other business constraints inside Java methods.
Enforce tenant isolation.
For multi-tenant applications, derive tenant identity from the authenticated application context, not from parameters supplied by the LLM.
Protect customer information.
Return only the fields needed by the agent. Avoid exposing customer emails and other personal data unnecessarily.
Protect sensitive operations.
Keep read and write capabilities separate. Use explicit human approval for sensitive actions such as issuing refunds, changing orders or modifying customer information.
Spring AI Agent provides useful building blocks for applying these controls, but the application remains responsible for authorization and business security.
This integration demonstrates how Spring AI Agent and Querier Core can complement each other without introducing unnecessary coupling.
Spring AI Agent provides the agentic foundations:
Querier Core provides the database query construction layer:
The interesting architectural point is that Querier doesn't need to know anything about Spring AI Agent, and Spring AI Agent doesn't need to know anything about Querier.
They meet at the Java business-tool boundary.
This separation makes it possible to adopt Spring AI Agent incrementally in existing Spring applications while continuing to use familiar Java libraries and database infrastructure.
It also leaves plenty of room for more advanced use cases: specialized analytics agents, distributed business agents, database-backed subagents and long-running enterprise workflows.
References