核心概念
大约 5 分钟
第二章:Spring AI核心概念与架构
2.1 Spring AI核心组件
Spring AI的设计遵循Spring框架的哲学,提供了清晰、模块化的组件结构。理解这些核心组件是掌握Spring AI的关键。
2.1.1 AI客户端(ChatClient)
ChatClient是Spring AI的核心接口,提供了与AI模型交互的主要方式。它抽象了不同AI服务的差异,提供了统一的API。
public interface ChatClient {
ChatResponse call(Prompt prompt);
Stream<ChatResponse> stream(Prompt prompt);
ChatResponse call(ChatPrompt chatPrompt);
Stream<ChatResponse> stream(ChatPrompt chatPrompt);
}主要特性:
- 统一的API接口
- 支持同步和异步调用
- 支持流式响应
- 自动错误处理
2.1.2 Prompt系统
Prompt是向AI模型发送的输入,Spring AI提供了丰富的Prompt系统:
// 基本Prompt
Prompt prompt = new Prompt("Tell me about Spring AI");
// 带有系统提示的Prompt
Prompt systemPrompt = new Prompt(
new SystemMessage("You are a helpful assistant"),
new UserMessage("Tell me about Spring AI")
);
// 带有多个消息的ChatPrompt
ChatPrompt chatPrompt = new ChatPrompt(
new SystemMessage("You are a helpful assistant"),
new UserMessage("Tell me about Spring AI"),
new AssistantMessage("Spring AI is a framework..."),
new UserMessage("Can you explain more?")
);2.1.3 Output解析
Spring AI提供了多种方式解析AI模型的输出:
// 基本字符串输出
String content = chatClient.prompt()
.user("Tell me about Spring AI")
.call()
.content();
// 结构化输出
ChatResponse response = chatClient.prompt()
.user("Tell me about Spring AI")
.call();
// 获取特定类型的输出
ChatResponseMetadata metadata = response.getMetadata();
List<Generation> generations = response.getResults();2.2 AI客户端与模板
Spring AI提供了两种主要的客户端实现:ChatClient和ChatClientBuilder。
2.2.1 ChatClient的使用
@RestController
public class AiController {
private final ChatClient chatClient;
public AiController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/ai")
public String generate(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
}2.2.2 ChatClientBuilder的配置
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("You are a helpful assistant")
.defaultOptions(OpenAiChatOptions.builder()
.withModel("gpt-3.5-turbo")
.withTemperature(0.7f)
.build())
.build();
}2.2.3 自定义配置
@Configuration
public class AiConfig {
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("You are a technical assistant specialized in Spring framework")
.defaultUser("User")
.defaultOptions(OpenAiChatOptions.builder()
.withModel("gpt-4")
.withMaxTokens(1000)
.build())
.build();
}
}2.3 Prompt模板系统
Spring AI的Prompt模板系统允许您创建可重用的Prompt模板。
2.3.1 基本模板
@RestController
public class TemplateController {
private final ChatClient chatClient;
public TemplateController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/template")
public String useTemplate(@RequestParam String topic) {
PromptTemplate promptTemplate = new PromptTemplate(
"Tell me about {topic} in 100 words"
);
Prompt prompt = promptTemplate.create(Map.of("topic", topic));
return chatClient.prompt(prompt).call().content();
}
}2.3.2 复杂模板
@RestController
public class ComplexTemplateController {
private final ChatClient chatClient;
public ComplexTemplateController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/complex-template")
public String useComplexTemplate(
@RequestParam String name,
@RequestParam String role,
@RequestParam String question) {
PromptTemplate promptTemplate = new PromptTemplate(
"""
You are {role}.
User: {name} asks: {question}
Please provide a detailed answer.
"""
);
Prompt prompt = promptTemplate.create(
Map.of("role", role, "name", name, "question", question)
);
return chatClient.prompt(prompt).call().content();
}
}2.3.3 条件模板
@RestController
public class ConditionalTemplateController {
private final ChatClient chatClient;
public ConditionalTemplateController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/conditional-template")
public String useConditionalTemplate(
@RequestParam String language,
@RequestParam String code) {
PromptTemplate promptTemplate = new PromptTemplate(
"""
Convert the following {language} code to Java:
{code}
"""
);
Prompt prompt = promptTemplate.create(
Map.of("language", language, "code", code)
);
return chatClient.prompt(prompt).call().content();
}
}2.4 Output解析机制
Spring AI提供了多种方式解析AI模型的输出。
2.4.1 基本字符串输出
String response = chatClient.prompt()
.user("Tell me about Spring AI")
.call()
.content();2.4.2 结构化输出
ChatResponse response = chatClient.prompt()
.user("Tell me about Spring AI")
.call();
// 获取元数据
ChatResponseMetadata metadata = response.getMetadata();
// 获取生成内容
List<Generation> generations = response.getResults();
for (Generation generation : generations) {
System.out.println("Content: " + generation.getContent());
System.out.println("Finish Reason: " + generation.getGenerationMetadata().getFinishReason());
}2.4.3 自定义输出解析
@RestController
public class CustomOutputController {
private final ChatClient chatClient;
public CustomOutputController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/custom-output")
public AiResponse customOutput(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.entity(AiResponse.class);
}
}
// 自定义响应类
public class AiResponse {
private String answer;
private String source;
private LocalDateTime timestamp;
// getters and setters
}2.5 Spring AI架构概览
Spring AI的架构设计遵循Spring框架的原则,提供了清晰的分层结构:
2.5.1 核心层
- API层:提供统一的接口,如
ChatClient、ImageClient等 - 模板层:Prompt模板系统,支持动态Prompt生成
- 输出层:多种输出解析方式
2.5.2 适配器层
- OpenAI适配器:集成OpenAI服务
- 千问适配器:集成千问服务
- DeepSeek适配器:集成DeepSeek服务
- 其他适配器:支持更多AI服务
2.5.3 配置层
- 自动配置:Spring Boot自动配置
- 属性配置:通过application.properties/yaml配置
- 编程配置:通过Java配置类
2.5.4 工具层
- Prompt工具:Prompt模板、系统提示等
- 输出工具:各种输出解析器
- 错误处理:统一的错误处理机制
2.6 最佳实践
2.6.1 配置管理
@Configuration
@Profile("production")
public class ProductionConfig {
@Bean
public ChatClient productionChatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("You are a production assistant")
.defaultOptions(OpenAiChatOptions.builder()
.withModel("gpt-4")
.withMaxTokens(2000)
.build())
.build();
}
}2.6.2 错误处理
@RestControllerAdvice
public class AiExceptionHandler {
@ExceptionHandler(AiResponseException.class)
public ResponseEntity<ErrorResponse> handleAiError(AiResponseException ex) {
ErrorResponse error = new ErrorResponse(
"AI_SERVICE_ERROR",
"Failed to get response from AI service: " + ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.SERVICE_UNAVAILABLE);
}
}2.6.3 监控与日志
@Configuration
public class AiMonitoring {
@Bean
public ChatClient monitoredChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
long startTime = System.currentTimeMillis();
try {
ChatResponse response = chatClient.call(prompt);
long duration = System.currentTimeMillis() - startTime;
log.info("AI call completed in {}ms", duration);
return response;
} catch (Exception ex) {
log.error("AI call failed", ex);
throw ex;
}
}
// 实现其他方法...
};
}
}2.7 小结
本章深入探讨了Spring AI的核心概念和架构:
- 核心组件:理解ChatClient、Prompt、Output等核心概念
- 客户端使用:掌握ChatClient的基本用法和配置
- Prompt模板:学习如何创建和使用可重用的Prompt模板
- 输出解析:了解不同的输出解析方式
- 架构设计:理解Spring AI的分层架构
在下一章中,我们将学习如何集成具体的AI模型,包括千问、DeepSeek和OpenAI。 点击这里👇🏻获取:100万QPS短链系统、复杂的商城微服务系统、智能翻译助手AI Agent、SaaS点餐系统、刷题吧小程序、商城系统、秒杀系统、AI项目、代码生成神器、苏三demo项目、智能天气播报AI Agent、智能代码审查AI Agent等 10 个项目的:项目源代码、开发教程和技术答疑
