Building Smart Agents with Spring AI Alibaba: A Hands‑On Guide

This article walks through the Spring AI Alibaba Agent Framework (v1.1.2.0), explaining the ReAct reasoning‑acting loop, core APIs, configuration, code examples, testing commands, and common troubleshooting steps so developers can quickly create LLM‑driven agents with tool‑calling and memory support.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
Building Smart Agents with Spring AI Alibaba: A Hands‑On Guide

What Is the Agent Framework?

Spring AI Alibaba Agent Framework is a high‑level abstraction built on the Graph engine that encapsulates the ReAct (Reasoning + Acting) loop, enabling developers to create agents capable of reasoning and invoking tools.

1.1 ReAct Mode

The ReAct cycle consists of four stages:

Reasoning : the agent analyses the current situation and decides the next step.

Acting : the agent performs a tool call or generates the final answer.

Observation : the result of the tool execution is received.

Iteration : based on the observation the agent repeats reasoning and acting until the task is completed.

This loop lets an agent break complex problems into steps, adjust strategies dynamically, handle multi‑tool tasks, and make decisions in uncertain environments.

1.2 ReactAgent Architecture

ReactAgent runs on the Graph runtime and moves between three node types:

Model Node : calls the LLM for reasoning and decision making.

Tool Node : executes external tool calls.

Hook Nodes : inject custom logic at key points.

Core API Details

2.1 Model (Model Configuration)

The model is the inference engine of the agent. The example uses ChatModel backed by DashScope:

<span>DashScopeApi dashScopeApi = DashScopeApi.builder()
    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
    .build();

ChatModel chatModel = DashScopeChatModel.builder()
    .dashScopeApi(dashScopeApi)
    .defaultOptions(DashScopeChatOptions.builder()
        .withModel("deepseek-v4-flash")
        .withTemperature(0.7)
        .withMaxToken(2000)
        .build())
    .build();

2.2 Tools (Tool Definition)

Tools give the agent the ability to perform actions. They are declared with the @Tool annotation:

@Component
public class AgentTools {
    @Tool(description = "获取指定城市的当前天气信息")
    public String getWeather(@ToolParam(description = "城市名称") String city) {
        // 实现逻辑
        return "北京:晴,25°C";
    }
}

2.3 Registering Tools

Tools must be converted to ToolCallback objects and registered via .tools(...):

ToolCallback[] toolCallbacks = MethodToolCallbackProvider.builder()
    .toolObjects(agentTools)
    .build()
    .getToolCallbacks();

ReactAgent agent = ReactAgent.builder()
    .name("assistant_agent")
    .model(chatModel)
    .tools(toolCallbacks) // pass the array
    .build();

2.4 System Prompt

The system prompt shapes the agent’s behavior:

ReactAgent agent = ReactAgent.builder()
    .name("my_agent")
    .model(chatModel)
    .systemPrompt("""
        你是一个智能助手,可以帮助用户完成各种任务。
        你有以下能力:
        1. 查询城市天气
        2. 获取当前时间
        3. 进行数学计算
        请根据用户的问题,选择合适的工具来解决问题。
    """)
    .build();

2.5 Invoking the Agent

AssistantMessage response = agent.call("北京今天天气怎么样?");
System.out.println(response.getText());

2.6 Memory (Conversation Context)

Use MemorySaver together with a threadId to keep context across turns:

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

RunnableConfig config = RunnableConfig.builder()
    .threadId("user_123")
    .build();

agent.call("我叫张三", config);
agent.call("我叫什么名字?", config); // returns "你叫张三"

2.7 Iteration Control

Prevent infinite loops with ModelCallLimitHook:

ReactAgent agent = ReactAgent.builder()
    .name("my_agent")
    .model(chatModel)
    .hooks(ModelCallLimitHook.builder().runLimit(5).build())
    .build();

Environment Setup

3.1 Maven Dependencies (pom.xml)

<properties>
    <java.version>17</java.version>
    <spring-ai-alibaba.version>1.1.2.0</spring-ai-alibaba.version>
    <jackson.version>2.16.2</jackson.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Agent Framework core -->
    <dependency>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-agent-framework</artifactId>
        <version>${spring-ai-alibaba.version}</version>
    </dependency>
</dependencies>

3.2 Application Configuration (application.yml)

server:
  port: 885

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

Bean definitions create the ChatModel and the ReactAgent with the tool callbacks, system prompt, memory saver, and iteration hook.

Testing and Verification

5.1 Test Commands

# Basic conversation
curl -X POST http://localhost:885/api/agent/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "北京今天天气怎么样?"}'

# Conversation with session memory
curl -X POST http://localhost:885/api/agent/chat/session \
  -H "Content-Type: application/json" \
  -d '{"message": "我叫张三", "sessionId": "test-001"}'

curl -X POST http://localhost:885/api/agent/chat/session \
  -H "Content-Type: application/json" \
  -d '{"message": "我叫什么名字?", "sessionId": "test-001"}'

5.2 Expected Output

{
  "success": true,
  "response": "北京今天的天气是晴,25°C,湿度45%。"
}

Images illustrate the test results (omitted here for brevity).

Common Issues and Solutions

6.1 Unhandled GraphRunnerException

Error:

Unhandled exception: com.alibaba.cloud.ai.graph.exception.GraphRunnerException

Cause: agent.call() throws a checked exception that must be declared or caught.

Solution: Declare throws GraphRunnerException in the service method and let the controller handle it, or wrap it in a runtime exception.

6.2 Incorrect Tool Registration

Error: Cannot resolve method 'tools(AgentTools)' Cause: The builder expects .tools(ToolCallback...).

Solution: Convert the @Tool bean to ToolCallback[] via MethodToolCallbackProvider and register with .tools(toolCallbacks).

6.3 Infinite Loop

Problem: The agent repeatedly calls tools without producing a final answer, consuming tokens.

Solution: Add ModelCallLimitHook with a run limit (e.g., 5).

6.4 Tool Execution Failure

Problem: Exceptions in tool methods abort the agent.

Solution: Wrap tool logic in try‑catch and return a friendly error message.

6.5 Lost Conversation Context

Problem: Subsequent requests forget previous dialogue.

Solution: Configure the agent with MemorySaver and pass a consistent threadId via RunnableConfig.

6.6 Import Path Errors

A table of correct fully‑qualified class names is provided (e.g., com.alibaba.cloud.ai.graph.agent.ReactAgent, com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver, etc.). Use these imports to avoid compilation errors.

Summary of Knowledge Points

ReAct Mode : Reasoning + Acting loop.

ReactAgent : Graph‑based implementation of an agent.

Model Configuration : ChatModel + ChatOptions (model, temperature, max token).

Tool Definition : Declare tools with @Tool annotation.

Tool Registration : Convert to ToolCallback[] via MethodToolCallbackProvider and register with .tools(...).

System Prompt : Shapes agent behavior and capabilities.

Memory : MemorySaver + threadId for multi‑turn context.

Iteration Control : ModelCallLimitHook prevents endless loops.

Exception Handling : Unified handling of GraphRunnerException.

With this complete example you can extend the agent further—add more tools, enable multi‑agent collaboration, or integrate Retrieval‑Augmented Generation (RAG) for advanced use cases.

Reference resources: Spring AI Alibaba GitHub | Official Documentation
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.

AlibabaJavaLLMReActTool IntegrationSpring AIAgent Framework
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

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.