在经历了八个里程碑式的版本之后(M1~M8),Spring AI 1.0 正式版本,终于在 2025 年 5 月 20 日正式发布了,这是另一个新高度的里程碑式的版本,标志着 Spring 生态系统正式全面拥抱人工智能技术,并且意味着 Spring AI 将会给企业带来稳定 API 支持。
Spring AI 1.0 的核心是 ChatClient 接口,这是一个可移植且易于使用的 API,是与 AI 模型交互的主要接口。
它支持调用 20 多种 AI 模型,从 Anthropic 到 ZhiPu AI,并支持多模态输入和输出(当底层模型支持时)以及结构化响应(通常以 JSON 格式,便于应用程序处理输出)。
在项目中只有一个模型时,创建全局的 ChatClient:
@RestController
class MyController {
private final ChatClient chatClient;
public MyController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/ai")
String generation(String userInput) {
return this.chatClient.prompt()
.user(userInput)
.call()
.content();
}
}
在项目中有多个模型时,为这一个模型创建全局的 ChatClient:
// Create ChatClient instances programmatically
ChatModel myChatModel = ... // already autoconfigured by Spring Boot
ChatClient chatClient = ChatClient.create(myChatModel);
// Or use the builder for more control
ChatClient.Builder builder = ChatClient.builder(myChatModel);
ChatClient customChatClient = builder
.defaultSystemPrompt("You are a helpful assistant.")
.build();
当项目中有多个模型时,为每个模型定义单独的 ChatClient:
import org.springframework.ai.chat.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ChatClientConfig {
@Bean
public ChatClient openAiChatClient(OpenAiChatModel chatModel) {
return ChatClient.create(chatModel);
}
@Bean
public ChatClient anthropicChatClient(AnthropicChatModel chatModel) {
return ChatClient.create(chatModel);
}
}
然后,您可以使用 @Qualifier 指定大模型对应的 ChatClient:
@Configuration
public class ChatClientExample {
@Bean
CommandLineRunner cli(
@Qualifier("openAiChatClient") ChatClient openAiChatClient,
@Qualifier("anthropicChatClient") ChatClient anthropicChatClient) {
return args -> {
var scanner = new Scanner(System.in);
ChatClient chat;
// Model selection
System.out.println("\nSelect your AI model:");
System.out.println("1. OpenAI");
System.out.println("2. Anthropic");
System.out.print("Enter your choice (1 or 2): ");
String choice = scanner.nextLine().trim();
if (choice.equals("1")) {
chat = openAiChatClient;
System.out.println("Using OpenAI model");
} else {
chat = anthropicChatClient;
System.out.println("Using Anthropic model");
}
// Use the selected chat client
System.out.print("\nEnter your question: ");
String input = scanner.nextLine();
String response = chat.prompt(input).call().content();
System.out.println("ASSISTANT: " + response);
scanner.close();
};
}
}
Spring AI 1.0 全面支持 Model Context Protocol (MCP),这是一个标准化协议,使 AI 模型能够与外部工具、提示和资源进行交互。Spring AI 提供了客户端和服务器端的 MCP支持,简化了 MCP 工具的使用和创建。
最简单的 MCP 自定义服务器端实现:
@Service
public class WeatherService {
@Tool(description = "Get weather information by city name")
public String getWeather(String cityName) {
// 伪代码
return "The weather in " + cityName + " is 21°C and sunny.";
}
}
@SpringBootApplication
public class McpServerApplication {
private static final Logger logger = LoggerFactory.getLogger(McpServerApplication.class);
public static void main(String[] args) {
SpringApplication.run(McpServerApplication.class, args);
}
@Bean
public ToolCallbackProvider weatherTools(WeatherService weatherService) {
return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
}
}
最简单的 MCP 客户端核心代码实现:
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClientController {
@Autowired
private ChatClient chatClient;
@RequestMapping("/chat")
public String chat(@RequestParam(value = "msg",defaultValue = "今天天气如何?") String msg) {
String response = chatClient.prompt()
.user(msg)
.call()
.content();
System.out.println("响应结果: " + response);
return response;
}
}
AI Agent 的核心是“利用 AI 模型与其环境交互,以解决用户定义的任务”。有效的 AI Agent 将规划、记忆和作相结合,以完成用户分配的任务。
Spring AI 1.0 支持两种主要类型的 Agent:
虽然完全自主代理的灵活性很有吸引力,但工作流为定义明确的任务提供了更好的可预测性和一致性。具体使用哪种类型,取决于您的具体要求和风险承受能力。
让我们看看 Spring AI 如何通过五种基本模式来实现这些概念,每种模式都服务于特定的用例:
该模式将复杂任务分解为一系列步骤,其中每个 LLM 调用都会处理前一个 LLM 调用的输出。
Chain Workflow 模式体现了将复杂任务分解为更简单、更易于管理的步骤的原则。
以下是 Spring AI 实现中的一个实际示例:
public class ChainWorkflow {
private final ChatClient chatClient;
private final String[] systemPrompts;
public String chain(String userInput) {
String response = userInput;
for (String prompt : systemPrompts) {
String input = String.format("{%s}\n {%s}", prompt, response);
response = chatClient.prompt(input).call().content();
}
return response;
}
}
此实现演示了几个关键原则:
LLM 可以同时处理任务,并以编程方式聚合其输出。
简单代码实现:
List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
.parallel(
"Analyze how market changes will impact this stakeholder group.",
List.of(
"Customers: ...",
"Employees: ...",
"Investors: ...",
"Suppliers: ..."
),
4
);
路由模式实现了智能任务分配,从而支持对不同类型的输入进行专门处理。
简单代码实现:
@Autowired
private ChatClient chatClient;
RoutingWorkflow workflow = new RoutingWorkflow(chatClient);
Map<String, String> routes = Map.of(
"billing", "You are a billing specialist. Help resolve billing issues...",
"technical", "You are a technical support engineer. Help solve technical problems...",
"general", "You are a customer service representative. Help with general inquiries..."
);
String input = "My account was charged twice last week";
String response = workflow.route(input, routes);
简单实现代码:
public class OrchestratorWorkersWorkflow {
public WorkerResponse process(String taskDescription) {
// 1. Orchestrator analyzes task and determines subtasks
OrchestratorResponse orchestratorResponse = // ...
// 2. Workers process subtasks in parallel
List<String> workerResponses = // ...
// 3. Results are combined into final response
return new WorkerResponse(/*...*/);
}
}
使用示例:
ChatClient chatClient = // ... initialize chat client
OrchestratorWorkersWorkflow workflow = new OrchestratorWorkersWorkflow(chatClient);
WorkerResponse response = workflow.process(
"Generate both technical and user-friendly documentation for a REST API endpoint"
);
System.out.println("Analysis: " + response.analysis());
System.out.println("Worker Outputs: " + response.workerResponses());
public class EvaluatorOptimizerWorkflow {
public RefinedResponse loop(String task) {
Generation generation = generate(task, context);
EvaluationResponse evaluation = evaluate(generation.response(), task);
return new RefinedResponse(finalSolution, chainOfThought);
}
}
使用示例:
ChatClient chatClient = // ... initialize chat client
EvaluatorOptimizerWorkflow workflow = new EvaluatorOptimizerWorkflow(chatClient);
RefinedResponse response = workflow.loop(
"Create a Java class implementing a thread-safe counter"
);
System.out.println("Final Solution: " + response.solution());
System.out.println("Evolution: " + response.chainOfThought());
开发者可以通过 Maven 中央仓库获取 Spring AI 1.0 的所有组件。使用提供的 bom 导入依赖:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
也可以在 Spring Initializr 网站上创建 1.0 GA 应用程序,并参考参考文档中的"Getting Started"部分。
Spring AI 1.0 的发布标志着企业级 Java 应用程序开发进入了一个新时代,使开发者能够轻松地将最先进的 AI 能力集成到他们的 Spring 应用程序中。
本文已收录到我的技术小站 www.javacn.site,其中包含的内容有:Spring AI、LangChain4j、Dify、AI Agent、MCP、Function Call、RAG、向量数据库、Prompt、多模态、向量数据库、嵌入模型等内容。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有