{"slug": "building-ai-agents-with-spring-ai-agent-and-querier", "title": "Building AI Agents with Spring AI Agent and Querier", "summary": "A developer explored integrating the Spring team's newly announced Spring AI Agent project with Querier Core, a type-safe SQL construction layer, to build a commerce analytics assistant in Java. The demo uses Spring AI Agent's typed Agent<I, O> abstraction and graph-based orchestration for LLM interaction while Querier Core handles SQL generation, exposing existing Java domain models as tools agents can call. Spring AI Agent, announced December 3, 2026, is an incubating project built on Spring AI 2.1 and planned for merge into Spring AI 3.0 in May 2027.", "body_md": "On December 3, 2026, the Spring team announced [Spring AI Agent](https://spring.io/blog/2026/12/03/spring-ai-agent-announcement), a new project bringing type-safe agentic foundations to Java and Kotlin.\n\nBuilt 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.\n\nI wanted to explore how [Querier](https://github.com/AytmaTech/Querier), specifically its core module, can fit into this new ecosystem.\n\nThe 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.\n\nWe will build a small commerce analytics assistant that can answer questions about products, orders, customers, and sales using our existing Java domain models.\n\nThe 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.\n\nLet's explore the architecture and the possibilities.\n\nBefore writing code, let's understand what Spring AI Agent brings to the table.\n\nThe Spring AI team describes an agent as a model plus a harness.\n\nSpring AI already provides `ChatClient`, which can be used to build agents with model interaction, instructions, memory and tool calling.\n\nSpring AI 2.1 added important capabilities such as session memory with compaction, tool-call confirmation, and reasoning preservation across model interactions.\n\nSpring AI Agent takes these foundations further by introducing dedicated abstractions for agent composition and orchestration.\n\nSome of its main capabilities include:\n\n`Agent<I, O>` abstraction.`GraphAgent` and `ModelGraphAgent`.` ChatClient` implementations.\nAn 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.\n\n__This means we should keep an eye on API evolution when adopting it in production.__\n\nThe central abstraction introduced by Spring AI Agent is:\n\n```\nAgent<I, O>\n```\n\nHere, `I` represents the input type and `O` represents the output type.\n\nThese types can simply be strings, but they can also be Java records representing business requests and responses.\n\nThe interface provides synchronous and asynchronous execution:\n\n```\n// Synchronous execution\nAgentRunResult<O> result(I input);\n\n// Resume an interrupted execution\n<R> AgentRunResult<O> resumeResult(\n    RunIdentification runId,\n    R answer\n);\n\n// Asynchronous execution\nAgentRun<O> run(I input);\n\n// Resume an asynchronous execution\n<R> AgentRun<O> resumeRun(\n    RunIdentification runId,\n    R answer\n);\n```\n\nThis abstraction is interesting because it makes agents composable.\n\nAn 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.\n\nIt can interact with all of them through a common contract.\n\nFor example, consider the following business types:\n\n```\npublic record AnalyticsRequest(\n    String question\n) {}\n\npublic record AnalyticsResponse(\n    String summary,\n    List<String> findings\n) {}\n```\n\nWe can build an agent accepting `AnalyticsRequest` and returning `AnalyticsResponse`.\n\nThe benefit is that our application can work with strongly typed domain objects instead of passing strings between every component.\n\nThis becomes particularly useful when building workflows containing several specialized agents.\n\nOur example will use a small commerce domain.\n\nWe already have the following entities:\n\n`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.\nOur order statuses are:\n\n```\npublic enum OrderStatus {\n    PENDING,\n    PAID,\n    SHIPPED,\n    DELIVERED,\n    CANCELLED\n}\n```\n\nWe will reuse the supplied JPA entities:\n\n```\n@Entity(name = \"products\")\n@Table(name = \"products\")\npublic class Product {\n\n    @Id\n    private Long id;\n\n    private String name;\n\n    private BigDecimal price;\n\n    public Long getId() { return id; }\n\n    public String getName() { return name; }\n\n    public BigDecimal getPrice() { return price; }\n}\n@Entity(name = \"orders\")\n@Table(name = \"orders\")\npublic class Order {\n\n    @Id\n    private Long id;\n\n    private Long customerId;\n\n    private Long productId;\n\n    private BigDecimal total;\n\n    @Enumerated(EnumType.STRING)\n    private OrderStatus status;\n\n    private LocalDate createdAt;\n\n    public Long getId() { return id; }\n\n    public Long getCustomerId() { return customerId; }\n\n    public Long getProductId() { return productId; }\n\n    public BigDecimal getTotal() { return total; }\n\n    public OrderStatus getStatus() { return status; }\n\n    public LocalDate getCreatedAt() { return createdAt; }\n}\n@Entity(name = \"customers\")\n@Table(name = \"customers\")\npublic class Customer {\n\n    @Id\n    private Long id;\n\n    private String name;\n\n    private String email;\n\n    public Long getId() { return id; }\n\n    public String getName() { return name; }\n\n    public String getEmail() { return email; }\n}\n```\n\nThe snippets focus on the attributes and accessors needed for our queries. The actual entities can retain their setters, constructors and other methods.\n\nNotice 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.\n\nWe will provide business semantics through Spring AI tool descriptions and agent instructions.\n\nLet's prepare our Spring Boot application.\n\nWe will use:\n\n| Component | Version | \n|---|---|\n| Java | 17+ (17.0.19 or later) | \n| Spring Boot | 4.2.x | \n| Spring AI | 2.1.0 | \n| Spring AI Agent | 0.8.0 | \n| Querier Core | 2.0.4 | \n| Database | PostgreSQL | \n\nSpring AI 2.1 is built on Spring Boot 4.2.\n\nFirst, import the Spring AI BOM:\n\n```\n<dependencyManagement>\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.ai</groupId>\n            <artifactId>spring-ai-bom</artifactId>\n            <version>2.1.0</version>\n            <type>pom</type>\n            <scope>import</scope>\n        </dependency>\n    </dependencies>\n</dependencyManagement>\n```\n\nThen add the dependencies:\n\n``` php\n<dependencies>\n\n    <!-- Querier Core -->\n    <dependency>\n        <groupId>com.aytmatech</groupId>\n        <artifactId>querier-core</artifactId>\n        <version>2.0.4</version>\n    </dependency>\n\n    <!-- Spring AI Agent -->\n    <dependency>\n        <groupId>org.springframework.experimental.ai</groupId>\n        <artifactId>spring-ai-agent</artifactId>\n        <version>0.8.0</version>\n    </dependency>\n\n    <!-- OpenAI Chat Model -->\n    <dependency>\n        <groupId>org.springframework.ai</groupId>\n        <artifactId>spring-ai-starter-model-openai</artifactId>\n    </dependency>\n\n    <!-- Database access -->\n    <dependency>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-jdbc</artifactId>\n    </dependency>\n\n    <!-- JPA annotations used by our domain entities -->\n    <dependency>\n        <groupId>jakarta.persistence</groupId>\n        <artifactId>jakarta.persistence-api</artifactId>\n    </dependency>\n\n    <!-- PostgreSQL -->\n    <dependency>\n        <groupId>org.postgresql</groupId>\n        <artifactId>postgresql</artifactId>\n        <scope>runtime</scope>\n    </dependency>\n\n</dependencies>\n```\n\nThe application can also include `spring-boot-starter-web` if we want to expose our agent through REST endpoints.\n\nSpring AI's model integrations are separate from the agent orchestration layer.\n\nSpring 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.\n\nFor this tutorial, we will use OpenAI compatible API.\n\nSet it as an environment variable instead.\n\nLinux/macOS:\n\n```\nexport LLM_BASE_URL=\"your-base-url\"\nexport LLM_API_KEY=\"your-api-key\"\nexport LLM_MODEL=\"your-model\"\n```\n\nWindows PowerShell:\n\n```\n$env:LLM_BASE_URL=\"your-base-url\"\n$env:LLM_API_KEY=\"your-api-key\"\n$env:LLM_MODEL=\"your-model\"\n```\n\nNow configure `application.yml`:\n\n```\nspring:\n  ai:\n    openai:\n      base-url: ${LLM_BASE_URL}\n      api-key: ${LLM_API_KEY}\n      chat:\n        options:\n          model: ${LLM_MODEL}\n\n  datasource:\n    url: jdbc:postgresql://localhost:5432/commerce\n    username: ${DB_USERNAME}\n    password: ${DB_PASSWORD}\n```\n\nThe important properties are:\n\n`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.\nThe model can be changed through the environment variable without modifying application code.\n\nSpring 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.\n\nNow let's integrate Querier.\n\nThe approach is simple: we expose specific database capabilities as Java methods and let the LLM decide which capabilities to invoke.\n\nThe model doesn't generate SQL.\n\nInstead, it receives the description of available tools and determines which one is appropriate for the user's request.\n\nEach tool uses Querier Core to construct its query, and Spring JDBC executes the generated SQL.\n\nLet's start with a tool for searching products within a price range.\n\n```\n@Component\npublic class ProductCatalogTools {\n\n    private final NamedParameterJdbcTemplate jdbc;\n\n    public ProductCatalogTools(NamedParameterJdbcTemplate jdbc) {\n        this.jdbc = jdbc;\n    }\n\n    @Tool(description = \"\"\"\n        Search products in the product catalog by price range.\n        Products can also be referred to as items, merchandise or goods.\n        Returns product identifiers, names and prices.\n        \"\"\")\n    public List<Map<String, Object>> findProductsByPriceRange(\n\n            @ToolParam(description = \"Minimum product price\")\n            BigDecimal minPrice,\n\n            @ToolParam(description = \"Maximum product price\")\n            BigDecimal maxPrice,\n\n            @ToolParam(description = \"Maximum number of results, between 1 and 50\")\n            int limit) {\n\n        if (minPrice.compareTo(maxPrice) > 0) {\n            throw new IllegalArgumentException(\n                \"Minimum price cannot exceed maximum price\"\n            );\n        }\n\n        int safeLimit = Math.clamp(limit, 1, 50);\n\n        Select query = Select.builder()\n                .select(Product::getId)\n                .select(Product::getName)\n                .select(Product::getPrice)\n                .from(Product.class)\n                .where(Condition.and(\n                        Condition.gte(Product::getPrice, minPrice),\n                        Condition.lte(Product::getPrice, maxPrice)\n                ))\n                .orderBy(OrderBy.asc(Product::getPrice))\n                .limit(safeLimit)\n                .build();\n\n        Select.SqlAndParams statement = query.toSqlAndParams();\n\n        return jdbc.queryForList(\n                statement.sql(),\n                statement.params()\n        );\n    }\n}\n```\n\nThere are several interesting things here.\n\nFirst, the LLM only sees the business operation:\n\n`findProductsByPriceRange`\n\nIt doesn't need to know that the application uses Querier, PostgreSQL or Spring JDBC.\n\nSecond, Querier provides type-safe column references:\n\n```\n.select(Product::getId)\n.select(Product::getName)\n.select(Product::getPrice)\n```\n\nWe also have a composable condition:\n\n```\n.where(Condition.and(\n    Condition.gte(Product::getPrice, minPrice),\n    Condition.lte(Product::getPrice, maxPrice)\n))\n```\n\nFinally, the generated SQL and parameters are separated:\n\n```\nSelect.SqlAndParams statement = query.toSqlAndParams();\n```\n\nThis is directly compatible with Spring's `NamedParameterJdbcTemplate`.\n\nLet's introduce more interesting database operations.\n\nOur order analytics tools will allow the agent to retrieve orders by status and identify the products generating the highest revenue.\n\n```\n@Component\npublic class OrderAnalyticsTools {\n\n    private final NamedParameterJdbcTemplate jdbc;\n\n    public OrderAnalyticsTools(NamedParameterJdbcTemplate jdbc) {\n        this.jdbc = jdbc;\n    }\n\n    @Tool(description = \"\"\"\n        Retrieve recent customer orders filtered by their lifecycle status.\n        Available statuses are PENDING, PAID, SHIPPED, DELIVERED and CANCELLED.\n        Use this for questions about order tracking and order status.\n        \"\"\")\n    public List<Map<String, Object>> findOrdersByStatus(\n\n            @ToolParam(description = \"Requested order status\")\n            OrderStatus status,\n\n            @ToolParam(description = \"Maximum number of orders, between 1 and 50\")\n            int limit) {\n\n        int safeLimit = Math.clamp(limit, 1, 50);\n\n        Select query = Select.builder()\n                .select(Order::getId)\n                .select(Order::getCustomerId)\n                .select(Order::getProductId)\n                .select(Order::getTotal)\n                .select(Order::getStatus)\n                .select(Order::getCreatedAt)\n                .from(Order.class)\n                .where(Condition.eq(Order::getStatus, status))\n                .orderBy(OrderBy.desc(Order::getCreatedAt))\n                .limit(safeLimit)\n                .build();\n\n        Select.SqlAndParams statement = query.toSqlAndParams();\n\n        return jdbc.queryForList(\n                statement.sql(),\n                statement.params()\n        );\n    }\n\n    @Tool(description = \"\"\"\n        Find the best-selling products based on revenue from paid orders.\n        Returns product names and total revenue.\n        Use this for questions about product performance and sales.\n        \"\"\")\n    public List<Map<String, Object>> topProductsByRevenue(\n\n            @ToolParam(description = \"Maximum number of products, between 1 and 20\")\n            int limit) {\n\n        int safeLimit = Math.clamp(limit, 1, 20);\n\n        Select query = Select.builder()\n                .select(Product::getName)\n                .select(Aggregate.sum(Order::getTotal).as(\"revenue\"))\n                .from(Order.class)\n                .join(\n                    Product.class,\n                    Condition.eq(Order::getProductId, Product::getId)\n                )\n                .where(Condition.eq(Order::getStatus, OrderStatus.PAID.name()))\n                .groupBy(Product::getName)           \n                .orderBy(\n                    OrderBy.desc(\n                       Aggregate.sum(\n                          Order::getTotal\n                       ).toSqlWithoutAlias()\n                    )\n                 )\n                .limit(safeLimit)\n                .build();\n\n        Select.SqlAndParams statement = query.toSqlAndParams();\n\n        return jdbc.queryForList(\n                statement.sql(),\n                statement.params()\n        );\n    }\n}\n```\n\nThis example demonstrates a more interesting capability of Querier Core.\n\nWe are using:\n\nThe query builder remains independent of the database execution mechanism.\n\nWe can also expose customer spending analytics using the same approach.\n\nFor example, a tool that identifies the highest-spending customers:\n\n```\nSelect query = Select.builder()\n        .select(Customer::getName)\n        .select(Aggregate.sum(Order::getTotal).as(\"total_spend\"))\n        .from(Order.class)\n        .join(\n            Customer.class,\n            Condition.eq(Order::getCustomerId, Customer::getId)\n        )\n        .where(Condition.eq(Order::getStatus, OrderStatus.PAID))\n        .groupBy(Customer::getName)\n                .orderBy(\n                    OrderBy.desc(\n                       Aggregate.sum(\n                          Order::getTotal\n                       ).toSqlWithoutAlias()\n                    )\n                 )\n        .limit(10)\n        .build();\n```\n\nThe same pattern can be extended to customer purchase history, average order values, monthly revenue and other business analytics operations.\n\nThe important design decision is that each Java method represents a business capability, not an unrestricted SQL execution endpoint.\n\nNow that we have database tools, let's connect them to Spring AI Agent.\n\nFor our first implementation, we will use `ModelGraphAgent` and the built-in `ToolCallLoop`.\n\nWhy?\n\nBecause we want the model to:\n\nThe `ToolCallLoop` provides this repeated model/tool interaction as a reusable graph.\n\nLet's configure the agent:\n\n```\n@Configuration\npublic class CommerceAgentConfiguration {\n\n    @Bean\n    Agent<String, String> commerceAssistant(\n            ChatModel chatModel,\n            ProductCatalogTools productCatalogTools,\n            OrderAnalyticsTools orderAnalyticsTools) {\n\n        return ModelGraphAgent\n                .builder(ToolCallLoop.create(), chatModel)\n                .instructions(\"\"\"\n                    You are a commerce analytics assistant.\n\n                    Your responsibility is to answer questions about:\n                    - Products and product prices\n                    - Orders and their lifecycle statuses\n                    - Product sales and revenue\n                    - Customer spending\n\n                    Business terminology:\n                    - Product, item, merchandise and goods refer to products.\n                    - Sales revenue means revenue from PAID orders.\n                    - Order statuses are PENDING, PAID, SHIPPED,\n                      DELIVERED and CANCELLED.\n\n                    Rules:\n                    - Use the available tools whenever actual database\n                      information is needed.\n                    - Never invent products, customers, orders or figures.\n                    - Never claim that a query succeeded when it failed.\n                    - Only report information returned by the tools.\n                    - Do not expose customer emails or other unnecessary\n                      personal information.\n                    - The available database operations are read-only.\n                    \"\"\")\n                .tools(productCatalogTools, orderAnalyticsTools)\n                .build();\n    }\n}\n```\n\nLet's understand what happens here.\n\nUnlike a traditional ChatClient-based implementation, `ModelGraphAgent` allows the agent itself to be represented by a graph.\n\nThe graph defines how the agent processes its input and produces its output.\n\nIn our case:\n\n```\nModelGraphAgent.builder(ToolCallLoop.create(), chatModel)\n```\n\nWe are using the built-in tool-calling graph.\n\nWe provide the `ChatModel`, which is the model interface auto-configured by Spring AI.\n\nThe instructions provide the business context and behavioral rules.\n\nNotice that we are also providing terminology mappings.\n\nFor example, users might ask about:\n\nAll these terms refer to the same business concept.\n\nWe can communicate this information through the agent instructions and tool descriptions without introducing Querier's AI module.\n\n```\n.tools(productCatalogTools, orderAnalyticsTools)\n```\n\nThis makes the methods annotated with `@Tool` available to the model.\n\nThe model can now decide whether it needs product information, order information or sales analytics.\n\nThe application remains responsible for executing the actual database operations.\n\nThe `Agent<I, O>` abstraction gives us a consistent way to interact with our agent.\n\nWe can create a regular Spring service:\n\n```\n@Service\npublic class CommerceAssistantService {\n\n    private final Agent<String, String> commerceAssistant;\n\n    public CommerceAssistantService(\n            Agent<String, String> commerceAssistant) {\n        this.commerceAssistant = commerceAssistant;\n    }\n\n    public String ask(String question) {\n        return commerceAssistant.result(question).output();\n    }\n}\n```\n\nFor example:\n\n```\nString answer = commerceAssistantService.ask(\n    \"Which are our top 5 products by revenue?\"\n);\n```\n\nThe model should recognize that it needs sales information and invoke:\n\n```\ntopProductsByRevenue(5)\n```\n\nThe tool executes the Querier-generated SQL and returns the records.\n\nThe model then uses the returned data to construct its answer.\n\nOther possible questions:\n\n```\nFind products priced between 50 and 150.\nShow me the latest 10 cancelled orders.\nWhich customers generated the highest revenue?\nHow many paid orders can we inspect?\n```\n\nThe agent can select the appropriate tool based on the meaning of the request.\n\nThe actual response depends on our database contents.\n\nThis is where Spring AI Agent becomes particularly interesting.\n\nWe have so far built one agent using a model and a set of tools.\n\nBut we don't have to put all business capabilities into one agent.\n\nWe can split the application into specialized agents, each with its own tools, instructions, model configuration and permissions.\n\n```\n                 Commerce Assistant\n                         |\n             -----------------------\n             |                     |\n        Product Agent          Order Agent\n             |                     |\n       Product Tools          Order Tools\n             |                     |\n       Querier Core           Querier Core\n             |                     |\n       PostgreSQL             PostgreSQL\n```\n\nThe Product Agent only needs access to product-related queries.\n\nThe Order Agent only needs access to order-related queries.\n\nA coordinator can decide which agent should handle a particular question.\n\nThis gives us a natural way to implement least-privilege database access.\n\nSpring AI Agent provides `AgentTools.asToolCallback(agent)`.\n\nThis is particularly interesting because it allows one agent to be exposed as a tool that another model can invoke.\n\nFor this case we need to wrap the subagent's input in a Java `record` (or POJO) instead of using String as the input type:\n\n```\npublic record CommerceRequest(\n        @ToolParam(description = \"The topic or question to research\") String query\n) {}\n```\n\nWe map record to user prompt with:\n\n```\nGraph<CommerceRequest, String> toolCallLoop = ToolCallLoop.builder()\n                .inputType(CommerceRequest.class, CommerceRequest::query)\n                .outputType(String.class)\n                .build();\n```\n\nSince `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.\n\nFor example, we can create our specialized agents:\n\n```\nAgent<CommerceRequest, String> productAgent =\n    ModelGraphAgent.builder(toolCallLoop, chatModel)\n        .name(\"product-agent\")\n        .description(\"Handles product catalog and pricing questions\")\n        .instructions(\"You are a product catalog specialist.\")\n        .tools(productCatalogTools)\n        .build();\n\nAgent<CommerceRequest, String> orderAgent =\n    ModelGraphAgent.builder(toolCallLoop, chatModel)\n        .name(\"order-agent\")\n        .description(\"Handles orders, customer spending and sales analytics\")\n        .instructions(\"You are an order and sales analytics specialist.\")\n        .tools(orderAnalyticsTools)\n        .build();\n```\n\nNow expose them to a coordinator agent:\n\n```\nAgent<CommerceRequest, String> commerceCoordinator =\n    ModelGraphAgent.builder(toolCallLoop, chatModel)\n        .instructions(\"\"\"\n            You coordinate commerce-related questions.\n\n            Delegate product catalog questions to the product agent.\n\n            Delegate order and sales analytics questions to the order agent.\n\n            Combine the results when the question requires both specialists.\n\n            Do not invent information.\n            \"\"\")\n        .toolCallbacks(\n            AgentTools.asToolCallback(productAgent),\n            AgentTools.asToolCallback(orderAgent)\n        )\n        .build();\n```\n\nThe important distinction is that the coordinator's model decides when to delegate to a specialist.\n\nEach subagent runs with its own execution context and conversation behavior.\n\nThis is different from a graph-driven subagent, where the graph determines which agent runs next.\n\nAnother interesting abstraction is `GraphAgent`.\n\nUnlike `ModelGraphAgent`, a `GraphAgent` doesn't need its own model. It orchestrates other agents and deterministic Java operations through a graph.\n\nFor example, imagine that we want to generate an analytics report and then have another agent review it.\n\nWe could use:\n\n```\nAgent<String, String> analyst = commerceCoordinator;\n\nChatClient reviewerClient = ChatClient.builder(chatModel)\n        .defaultSystem(\"\"\"\n            You are an analytics report reviewer.\n            Check the consistency and clarity of the supplied report.\n            \"\"\")\n        .build();\n\nAgent<String, String> reviewer =\n        ChatClientAgent.of(reviewerClient);\n\nGraph<CommerceRequest, String> reportingGraph =\n        Graph.sequence(\n            AgentNodes.subAgent(\"analysis\", analyst)\n        )\n        .then(\n            AgentNodes.subAgent(\"review\", reviewer)\n        )\n        .build();\n\nAgent<CommerceRequest, String> reportingAgent =\n        GraphAgent.builder(reportingGraph).build();\n```\n\nThe execution is deterministic:\n\nThe `GraphAgent` doesn't need another LLM to decide this sequence.\n\nThe graph itself controls the workflow.\n\nThis separation between model-driven decisions and deterministic orchestration is one of the most interesting aspects of the new architecture.\n\nAnother interesting part of Spring AI Agent is its execution model.\n\nThe `Agent` abstraction supports both synchronous and asynchronous execution.\n\nFor simple requests:\n\n```\nAgentRunResult<String> result =\n    commerceCoordinator.result(question);\n\nString answer = result.output();\n```\n\nFor asynchronous execution:\n\n```\ntry (AgentRun<String> run = commerceCoordinator.run(question)) {\n\n    Source<AgentEvent> events = run.events();\n\n    while (events.receiveNext()) {\n\n        AgentEvent event = events.next();\n\n        // Observe run, model, node and tool events.\n        // ModelFrameEvent can be used to inspect streamed output.\n    }\n}\n```\n\nOr run asynchronously with a CompletableFuture:\n\n``` php\nCompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {\n    try (AgentRun<String> run = commerceCoordinator.run(question)) {\n        return run.output();\n    } catch (InterruptedException e) {\n        log.error(\"Interrupted while processing question: {}\", question, e);\n        Thread.currentThread().interrupt();\n        throw new CompletionException(e);\n    }\n}, agentTaskExecutor);\n```\n\nThe new `Source<T>` abstraction provides a virtual-thread-friendly way to consume events.\n\nOn Java 21 and later, execution can use virtual threads underneath. Java 17 remains supported through platform-thread execution.\n\nIt is worth noting that this is an imperative streaming model, not simply another reactive API.\n\nFor example, an application could use the event stream to:\n\nThe `AgentRunResult` also exposes execution information such as the run identification, conversation messages and aggregated model usage.\n\nThis gives us useful foundations for monitoring and understanding complex agent workflows.\n\nFor production applications, simply invoking a model and executing tools isn't enough.\n\nWe need to think about conversation persistence, recoverability, observability and execution control.\n\nSpring AI Agent introduces a feature mechanism that can extend the agent execution pipeline.\n\nThere are three important extension points.\n\n**Hooks**\n\nHooks participate in execution lifecycle boundaries, such as run start, completion, failure and interruption.\n\nThey can be useful for initializing execution context, attaching metadata or performing cleanup.\n\n**Interceptors**\n\nInterceptors wrap operations such as model calls, tool calls and graph node execution.\n\nThey can inspect or modify arguments and results, implement retries, or skip operations.\n\nThis is interesting for implementing cross-cutting policies such as input validation, data redaction and tool-call controls.\n\n**Listeners**\n\nListeners observe events asynchronously.\n\nThey can be used for:\n\nThe framework also provides two important durability features.\n\n`SessionFeature` integrates with Spring AI Session to maintain conversations across runs.\n\nIt also supports conversation compaction.\n\nThis is useful when an assistant needs to retain context across multiple user interactions without repeatedly sending the complete conversation history.\n\nIt is provided by the optional `spring-ai-agent-session` module.\n\n`CheckpointFeature` allows agent executions to resume after interruptions or failures.\n\nThe framework can persist checkpoints after graph nodes and tool-call rounds.\n\nThis is particularly useful for long-running workflows or human approval processes.\n\n```\nGenerate report\n      |\n      v\nValidate report\n      |\n      v\nRequest human approval\n      |\n      v\nSave checkpoint\n      |\n      v\nWait for approval\n      |\n      v\nResume execution\n      |\n      v\nContinue workflow\n```\n\nThe `spring-ai-agent-checkpoint` module provides the checkpoint feature.\n\nBoth features are optional and should be introduced when the application actually needs them.\n\nGiving AI agents access to business data requires carefully designed boundaries.\n\nA few recommendations for our implementation:\n\n**Use least privilege.**\n\nThe Product Agent should not have access to customer data or order operations unless required.\n\n**Avoid unrestricted SQL execution.**\n\nDon't expose a generic method that accepts an SQL string generated by the model. Keep SQL construction and permitted operations under application control.\n\n**Validate tool arguments.**\n\nThe LLM is not a trusted source of input. Validate price ranges, result limits, identifiers and other business constraints inside Java methods.\n\n**Enforce tenant isolation.**\n\nFor multi-tenant applications, derive tenant identity from the authenticated application context, not from parameters supplied by the LLM.\n\n**Protect customer information.**\n\nReturn only the fields needed by the agent. Avoid exposing customer emails and other personal data unnecessarily.\n\n**Protect sensitive operations.**\n\nKeep read and write capabilities separate. Use explicit human approval for sensitive actions such as issuing refunds, changing orders or modifying customer information.\n\nSpring AI Agent provides useful building blocks for applying these controls, but the application remains responsible for authorization and business security.\n\nThis integration demonstrates how Spring AI Agent and Querier Core can complement each other without introducing unnecessary coupling.\n\nSpring AI Agent provides the agentic foundations:\n\nQuerier Core provides the database query construction layer:\n\nThe 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.**\n\nThey meet at the Java business-tool boundary.\n\nThis separation makes it possible to adopt Spring AI Agent incrementally in existing Spring applications while continuing to use familiar Java libraries and database infrastructure.\n\nIt also leaves plenty of room for more advanced use cases: specialized analytics agents, distributed business agents, database-backed subagents and long-running enterprise workflows.\n\n**References**", "url": "https://wpnews.pro/news/building-ai-agents-with-spring-ai-agent-and-querier", "canonical_source": "https://dev.to/aissam_assouik/building-ai-agents-with-spring-ai-agent-and-querier-451h", "published_at": "2026-12-06 15:34:33+00:00", "updated_at": "2026-12-06 15:44:23.345115+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "artificial-intelligence"], "entities": ["Spring", "Spring AI Agent", "Querier", "Querier Core", "AytmaTech", "Spring AI 2.1", "Spring AI 3.0"], "also_reported_by": [], "takeaway": "Spring AI Agent's typed Agent<I, O> contract lets Java applications expose existing domain models and SQL-building code as agent tools, keeping orchestration and LLM calls separate from deterministic query construction.", "recommendation": {"advice": "Wrap existing typed Java domain capabilities as agent tools and keep LLM orchestration in Spring AI Agent while deterministic layers like Querier Core build the SQL, so agents compose through a common Agent<I, O> contract.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-ai-agents-with-spring-ai-agent-and-querier", "markdown": "https://wpnews.pro/news/building-ai-agents-with-spring-ai-agent-and-querier.md", "text": "https://wpnews.pro/news/building-ai-agents-with-spring-ai-agent-and-querier.txt", "jsonld": "https://wpnews.pro/news/building-ai-agents-with-spring-ai-agent-and-querier.jsonld"}}