Master Spring AI Alibaba: Build AI Agents, Workflows, and Multi‑Agent Apps with Minimal Java Code

Spring AI Alibaba extends Spring AI with a native agent and workflow framework, integrating Alibaba's DashScope models, ReactAgent, multi‑agent orchestration, Graph workflows, tool calling, memory handling, and production‑grade features, enabling Java developers to create sophisticated AI applications with just a few lines of code.

java1234
java1234
java1234
Master Spring AI Alibaba: Build AI Agents, Workflows, and Multi‑Agent Apps with Minimal Java Code

What is Spring AI Alibaba?

Spring AI Alibaba is an open‑source extension of Spring AI that adds a full‑stack Agent + Workflow framework. It enables Java developers to build AI applications that can reason, invoke tools, orchestrate multiple agents, and execute complex workflows with minimal code.

Three‑Layer Architecture

Agent Framework – Provides agents such as ReactAgent (ReAct reasoning + acting), SequentialAgent, ParallelAgent, RoutingAgent, LoopAgent and extensible Hook s for custom logic.

Graph Runtime – Implements StateGraph, Node, Edge, OverAllState and Checkpoint for durable workflow execution.

Augmented LLM – Builds on Spring AI’s ChatModel, Tool, MCP, VectorStore and Message abstractions, with deep integration of Alibaba DashScope models.

Choosing Between Spring AI, Spring AI Alibaba, and LangChain4j

Spring AI – Abstracts model calls, vector stores and tool chains; suitable for simple chat, RAG or single‑tool scenarios.

Spring AI Alibaba – Adds native agents, multi‑agent orchestration, graph workflows and first‑class DashScope support; suited for complex, domestic‑model use cases.

LangChain4j – Framework‑agnostic Java library; requires more manual wiring and is better for non‑Spring stacks.

Quick‑Start (5 minutes)

Environment Requirements

JDK 17+

Maven 3.8+

Alibaba DashScope API key (or any Spring AI‑supported model)

Maven Dependencies

<dependencies>
  <!-- Agent framework -->
  <dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-agent-framework</artifactId>
    <version>1.1.2.2</version>
  </dependency>
  <!-- DashScope starter -->
  <dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
    <version>1.1.2.2</version>
  </dependency>
</dependencies>

API‑Key Configuration

Set the key via environment variable or application.yml:

spring:
  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY}

Minimal ReactAgent Example

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import org.springframework.ai.chat.model.ChatModel;

public class QuickStart {
    public static void main(String[] args) throws Exception {
        DashScopeApi api = DashScopeApi.builder()
            .apiKey(System.getenv("AI_DASHSCOPE_API_KEY"))
            .build();
        ChatModel chatModel = DashScopeChatModel.builder()
            .dashScopeApi(api)
            .build();
        ReactAgent agent = ReactAgent.builder()
            .name("hello_agent")
            .model(chatModel)
            .systemPrompt("你是一个友好的 Java AI 助手,回答简洁。")
            .build();
        var reply = agent.call("用一句话介绍 Spring AI Alibaba");
        System.out.println(reply.getText());
    }
}

Core Concepts

ChatModel – Entry point for LLM calls, analogous to JdbcTemplate.

Tool / ToolCallback – Java methods that the model can invoke.

ReactAgent – Implements the ReAct paradigm (reason → act → re‑reason).

MemorySaver / Checkpointer – In‑memory or persistent conversation state.

StateGraph – Workflow graph composed of nodes, edges and shared state.

Hook – Lifecycle extensions such as rate limiting, human‑in‑the‑loop approval, etc.

MCP (Model Context Protocol) – Standardized protocol for external tool and data integration.

Tool Integration Example

Define a Weather Tool

public class WeatherForLocationTool implements BiFunction<String, ToolContext, String> {
    @Override
    public String apply(@ToolParam(description = "城市名称,如:杭州") String city, ToolContext ctx) {
        // In production call a real weather API
        return city + " 今天晴,25°C,适合出门。";
    }
}

ToolCallback weatherTool = FunctionToolCallback.builder(
        "get_weather_for_location", new WeatherForLocationTool())
    .description("查询指定城市的天气")
    .inputType(String.class)
    .build();

Limit Model Calls (prevent loops)

ModelCallLimitHook limitHook = ModelCallLimitHook.builder()
    .runLimit(5)
    .exitBehavior(ModelCallLimitHook.ExitBehavior.ERROR)
    .build();

ReactAgent safeAgent = ReactAgent.builder()
    .name("safe_agent")
    .model(chatModel)
    .tools(weatherTool)
    .hooks(limitHook)
    .saver(new MemorySaver())
    .build();

Conversation Memory & Structured Output

Multi‑turn Memory with Thread ID

ReactAgent chatAgent = ReactAgent.builder()
    .name("chat_agent")
    .model(chatModel)
    .saver(new MemorySaver())
    .build();

String threadId = "user-10001-thread";
RunnableConfig cfg = RunnableConfig.builder().threadId(threadId).build();
chatAgent.call("杭州天气如何?", cfg);
chatAgent.call("那明天呢?", cfg); // remembers previous turn

In production replace MemorySaver with a persistent Checkpointer (e.g., database or Redis).

Structured JSON Output

Option 1 – Java class:

public class WeatherResponse {
    private String punnyResponse;
    private String weatherConditions;
    // getters / setters
}

ReactAgent structuredAgent = ReactAgent.builder()
    .name("structured_agent")
    .model(chatModel)
    .outputType(WeatherResponse.class)
    .saver(new MemorySaver())
    .build();

Option 2 – JSON schema string:

String schema = """
    {
      \"title\": \"标题\",
      \"content\": \"正文\",
      \"style\": \"风格\"
    }
    """;

ReactAgent schemaAgent = ReactAgent.builder()
    .name("schema_agent")
    .model(chatModel)
    .outputSchema(schema)
    .build();

Hooks & Human‑In‑The‑Loop (HITL)

Hook hitlHook = HumanInTheLoopHook.builder()
    .approvalOn("get_weather_for_location",
        ToolConfig.builder().description("请确认是否查询天气").build())
    .build();

ReactAgent hitlAgent = ReactAgent.builder()
    .name("hitl_agent")
    .model(chatModel)
    .tools(weatherTool)
    .hooks(hitlHook)
    .saver(new MemorySaver())
    .build();

Multi‑Agent Orchestration Patterns

SequentialAgent – Execute agents one after another (e.g., translate → polish → format).

ParallelAgent – Run agents concurrently and aggregate results (e.g., three analysts drafting a report).

RoutingAgent / LlmRoutingAgent – Classify input and dispatch to the appropriate specialist (e.g., tech / billing / complaint routing).

LoopAgent – Repeat until a condition is satisfied (e.g., keep revising a draft until it passes review).

Graph Workflow Orchestration

Example: customer‑service email process.

StateGraph graph = new StateGraph(createKeyStrategyFactory())
    .addNode("read_email", node_async(new ReadEmailNode()))
    .addNode("classify", node_async(new ClassifyIntentNode(chatModel)))
    .addNode("search_docs", node_async(new SearchDocumentationNode()))
    .addNode("draft_reply", node_async(new DraftReplyNode(chatModel)))
    .addNode("human_review", node_async(new HumanReviewNode()))
    .addNode("send_reply", node_async(new SendReplyNode()))
    .addEdge(StateGraph.START, "read_email")
    .addEdge("read_email", "classify")
    .addConditionalEdges("classify",
        edge_async(new IntentDispatcher()),
        Map.of(
            "question", "search_docs",
            "bug", "bug_track",
            "complex", "human_review",
            StateGraph.END, StateGraph.END))
    .addEdge("search_docs", "draft_reply")
    .addEdge("draft_reply", "human_review")
    .addEdge("human_review", "send_reply")
    .addEdge("send_reply", StateGraph.END);

Pre‑built nodes such as LLMNode, ToolNode and QuestionClassifierNode accelerate development.

MCP, RAG & Vector Stores

MCP standardizes calls to external services (databases, internal APIs, SaaS). Spring AI’s VectorStore, DocumentReader and Advisor implement Retrieval‑Augmented Generation (RAG). Choose a vector store based on scale:

PostgreSQL + pgvector for existing databases.

SimpleVectorStore for in‑memory demos.

Milvus, Elasticsearch, Redis Stack for large‑scale production.

A2A Distributed Agents

Agents can register with Nacos for service discovery and invoke each other across micro‑services, enabling scenarios like order → inventory → logistics coordination.

Ecosystem Tools: Admin & Studio

Spring AI Alibaba Admin – Visual UI for building agents, monitoring, evaluation and MCP management.

Spring AI Alibaba Studio – Embedded UI that shows reasoning steps and tool‑call details.

Example repositories (chatbot, graph, multi‑agent, voice‑agent) demonstrate real‑world usage.

Production‑Ready Considerations

Store API keys securely (environment variables or secret manager).

Replace MemorySaver with a persistent Checkpointer (DB, Redis, etc.).

Use ModelCallLimitHook and gateway rate‑limiting to prevent token‑burn loops.

Apply HITL hooks for sensitive operations (payments, data deletion).

Integrate Micrometer/Actuator for observability of model and tool calls.

Align versions of spring-ai-alibaba-agent-framework and spring-ai-alibaba-starter-dashscope (e.g., 1.1.2.x).

Run on JDK 17+ LTS for stability.

Learning Path & Resources

Official documentation: https://java2ai.com

GitHub repository: https://github.com/alibaba/spring-ai-alibaba

Example projects: https://github.com/alibaba/spring-ai-alibaba/tree/main/examples

Architecture diagram
Architecture diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaworkflowSpring AIAI integrationAgent FrameworkDashScope
java1234
Written by

java1234

Former senior programmer at a Fortune Global 500 company, dedicated to sharing Java expertise. Visit Feng's site: Java Knowledge Sharing, www.java1234.com

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.