在人工智能与企业应用加速融合的今天,智能体(Agent)正从概念走向落地,成为连接大模型能力与业务场景的关键桥梁。然而一提起人工智能都是Python的天下,如何在 Java 技术栈中高效、规范地构建具备推理、记忆、工具调用能力的智能体,依然是许多开发者面临的挑战。
Spring AI Alibaba 不仅延续了 Spring 生态一贯的简洁与可扩展性,更深度集成了阿里云大模型能力,为 Java 开发者提供了一条低门槛、高效率的 Agent 开发路径。无论你是希望快速构建企业级智能客服、自动化业务流程助手,还是探索多智能体协作的新范式,Spring AI Alibaba 都能为你提供坚实的基础设施与丰富的实践范式。
本文将以一个天气预报Agent为例,带领初学者快速入门这个框架。
什么是Agent框架?
Agent框架是一种可以让应用程序具备智能决策能力的架构模式。在AI领域,Agent可以理解用户的请求,根据需要调用各种工具(Tools),并通过推理过程得出最终答案。Spring AI Alibaba Agent框架基于这一理念,提供了构建智能代理应用的能力。
项目概述
我们将通过一个天气预报的例子来展示Agent框架的使用。在这个例子中,我们会创建一个能够以幽默风格回答天气询问的Agent,它可以根据用户的位置提供当地天气信息。
环境准备
1. Maven依赖配置
首先,在pom.xml中添加必要的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.guo</groupId>
<artifactId>spring-ai-alibaba</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-agent-framework</artifactId>
<version>1.1.0.0-M5</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
<version>1.1.0.0-M5</version>
</dependency>
</dependencies>
</project>
2. API密钥配置
在使用DashScope服务前,需要配置API密钥。可以通过环境变量或配置文件方式设置:
AI_DASHSCOPE_API_KEY=your_api_key_here
核心组件介绍
1. 工具(Tools)
工具是Agent执行特定任务的函数。在我们的例子中,有两个工具:
-
UserLocationTool: 根据用户ID获取用户位置 -
WeatherForLocationTool: 根据城市名称获取天气信息
工具实现示例:
package org.guo;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.ToolParam;
import java.util.function.BiFunction;
// 用户位置工具
public class UserLocationTool implements BiFunction<String, ToolContext, String> {
@Override
public String apply(String query, ToolContext toolContext) {
String userId = (String) toolContext.getContext().get("user_id");
return "1".equals(userId) ? "北京" : "上海";
}
}
// 天气查询工具
public class WeatherForLocationTool implements BiFunction<String, ToolContext, String> {
@Override
public String apply(String city, ToolContext toolContext) {
return "万里无云: " + city + "!";
}
}
2. Agent构建
Agent是整个框架的核心,负责协调模型、工具和业务逻辑:
// 创建工具回调
ToolCallback getWeatherTool = FunctionToolCallback
.builder("getWeatherForLocation", new WeatherForLocationTool())
.description("Get weather for a given city")
.inputType(String.class)
.build();
ToolCallback getUserLocationTool = FunctionToolCallback
.builder("getUserLocation", new UserLocationTool())
.description("Retrieve user location based on user ID")
.inputType(String.class)
.build();
// 创建模型实例
DashScopeApi dashScopeApi = DashScopeApi.builder()
.apiKey(apiKey)
.build();
ChatModel chatModel = DashScopeChatModel.builder()
.dashScopeApi(dashScopeApi)
.defaultOptions(DashScopeChatOptions.builder()
.withModel("qwen3-0.6b")
.withTemperature(0.5)
.withMaxToken(1000)
.build())
.build();
// 创建 agent
ReactAgent agent = ReactAgent.builder()
.name("weather_pun_agent")
.model(chatModel)
.systemPrompt(SYSTEM_PROMPT)
.tools(getUserLocationTool, getWeatherTool)
.outputType(ResponseFormat.class)
.saver(new MemorySaver())
.build();
3. 系统提示词(System Prompt)
系统提示词定义了Agent的行为准则和角色设定:
String SYSTEM_PROMPT = """
You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location.
If you can tell from the question that they mean wherever they are,
use the get_user_location tool to find their location.
""";
4. 使用 Java 类定义响应格式
package org.guo;
// 使用 Java 类定义响应格式
public class ResponseFormat {
// 一个双关语响应(始终必需)
private String punnyResponse;
// 如果可用的话,关于天气的任何有趣信息
private String weatherConditions;
// Getters and Setters
public String getPunnyResponse() {
return punnyResponse;
}
public void setPunnyResponse(String punnyResponse) {
this.punnyResponse = punnyResponse;
}
public String getWeatherConditions() {
return weatherConditions;
}
public void setWeatherConditions(String weatherConditions) {
this.weatherConditions = weatherConditions;
}
}
5. 运行Agent
构建好Agent后,就可以调用它来处理用户请求了:
// threadId 是给定对话的唯一标识符
String threadId = "123456";
RunnableConfig runnableConfig = RunnableConfig.builder()
.threadId(threadId)
.addMetadata("user_id", "1")
.build();
// 第一次调用
AssistantMessage response = agent.call("外面的天气怎么样?", runnableConfig);
System.out.println(response.getText());
// 注意我们可以使用相同的 threadId 继续对话
response = agent.call("非常感谢!", runnableConfig);
System.out.println(response.getText());
5.1主类的完整代码
package org.guo;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.function.FunctionToolCallback;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class AgentGuo {
public static void main(String[] args) throws Exception {
String SYSTEM_PROMPT = """
You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location.
If you can tell from the question that they mean wherever they are,
use the get_user_location tool to find their location.
""";
// 获取API Key
String apiKey = System.getenv("AI_DASHSCOPE_API_KEY");
// 如果环境变量中没有找到,则尝试从application.properties文件中读取
if (apiKey == null || apiKey.isEmpty()) {
try {
Properties props = new Properties();
props.load(Files.newInputStream(Paths.get("src/main/resources/application.properties")));
apiKey = props.getProperty("AI_DASHSCOPE_API_KEY");
} catch (IOException e) {
System.err.println("Failed to load API key from application.properties: " + e.getMessage());
}
}
// 创建工具回调
ToolCallback getWeatherTool = FunctionToolCallback
.builder("getWeatherForLocation", new WeatherForLocationTool())
.description("Get weather for a given city")
.inputType(String.class)
.build();
ToolCallback getUserLocationTool = FunctionToolCallback
.builder("getUserLocation", new UserLocationTool())
.description("Retrieve user location based on user ID")
.inputType(String.class)
.build();
// 创建模型实例
DashScopeApi dashScopeApi = DashScopeApi.builder()
.apiKey(apiKey)
.build();
ChatModel chatModel = DashScopeChatModel.builder()
.dashScopeApi(dashScopeApi)
.defaultOptions(DashScopeChatOptions.builder()
.withModel("qwen3-0.6b") // 添加模型参数
.withTemperature(0.5)
.withMaxToken(1000)
.build())
.build();
// 创建 agent
ReactAgent agent = ReactAgent.builder()
.name("weather_pun_agent")
.model(chatModel)
.systemPrompt(SYSTEM_PROMPT)
.tools(getUserLocationTool, getWeatherTool)
.outputType(ResponseFormat.class)
.saver(new MemorySaver())
.build();
// threadId 是给定对话的唯一标识符
String threadId = "123456";
RunnableConfig runnableConfig = RunnableConfig.builder().threadId(threadId).addMetadata("user_id", "1").build();
// 第一次调用
AssistantMessage response = agent.call("外面的天气怎么样?", runnableConfig);
System.out.println(response.getText());
// 注意我们可以使用相同的 threadId 继续对话
response = agent.call("非常感谢!", runnableConfig);
System.out.println(response.getText());
}
}

关键概念解析
1. 工具调用机制
Agent框架的强大之处在于其工具调用机制。当用户提出问题时,Agent会判断是否需要调用工具来获取更多信息,然后综合所有信息给出最终回答。
2. 对话状态管理
通过threadIdAgent可以维护对话历史,实现多轮对话。
3. 响应格式化
通过设置outputType,可以控制Agent的输出格式,使其符合特定的数据结构。
总结
Spring AI Alibaba Agent框架为我们提供了一种简洁而强大的方式来构建AI代理应用。通过合理设计工具和系统提示词,我们可以创建出能够理解和满足复杂用户需求的智能应用。
本文通过一个天气预报的例子,展示了Agent框架的基本使用方法。在实际应用中,您可以根据业务需求创建更多复杂的工具,构建更强大的AI代理应用。
希望这篇入门指南能帮助您快速上手Spring AI Alibaba Agent框架!