Nếu bạn là một lập trình viên Java/Spring Boot và muốn tích hợp AI vào ứng dụng của mình, thì Spring AI chính là thứ bạn cần. Hôm nay chúng ta sẽ cùng tìm hiểu về framework này nhé.
Spring AI là gì?
Spring AI là một application framework từ hệ sinh thái Spring, được thiết kế để đưa các nguyên tắc thiết kế quen thuộc của Spring — portability, modularity, và POJO-based development — vào thế giới AI engineering.
Nói đơn giản: nó giúp bạn kết nối dữ liệu doanh nghiệp và API với các mô hình AI mà không phải vật lộn với sự phức tạp. Nếu bạn đã từng nghe về LangChain hay LlamaIndex bên Python, thì Spring AI mang đến trải nghiệm tương tự nhưng dành riêng cho Java developers, với Spring Boot auto-configuration, dependency injection và fluent API quen thuộc.
- Repository: spring-projects/spring-ai
- License: Apache 2.0
- Stars: ~7.9k GitHub stars, 440+ contributors
Những tính năng nổi bật
1. ChatClient - Fluent API
Giống như WebClient hay RestClient, Spring AI cung cấp ChatClient với fluent API cực kỳ trực quan:
@RestController
class AiController {
private final ChatClient chatClient;
AiController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/ask")
String ask(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}
Chỉ vài dòng code, bạn đã có một REST API giao tiếp với AI. Hỗ trợ cả .call() (đồng bộ), .stream() (reactive streaming) và .entity(MyClass.class) (tự động map response sang Java object).
2. Structured Output - Map AI response sang POJO
Một trong những pain point lớn nhất khi làm việc với AI là parse response. Spring AI giải quyết bằng cách tự động map output sang Java records/POJOs:
record MovieRecommendation(String title, String genre, int year) {}
MovieRecommendation movie = chatClient.prompt()
.user("Gợi ý cho tôi một bộ phim khoa học viễn tưởng hay")
.call()
.entity(MovieRecommendation.class);
3. Tool/Function Calling - AI gọi code Java của bạn
Đây là tính năng cực kỳ mạnh mẽ. Bạn có thể cho phép AI model gọi các method Java bằng annotation @Tool:
class WeatherTools {
@Tool(description = "Lấy thông tin thời tiết hiện tại theo thành phố")
String getCurrentWeather(String city) {
// Gọi API thời tiết thực tế
return weatherService.getWeather(city);
}
}
// Sử dụng
String response = chatClient.prompt("Thời tiết Hà Nội hôm nay thế nào?")
.tools(new WeatherTools())
.call()
.content();
AI sẽ tự nhận biết cần gọi tool nào, truyền tham số gì, rồi tổng hợp kết quả trả về cho user.
4. RAG (Retrieval Augmented Generation)
Spring AI hỗ trợ đầy đủ pipeline RAG — cho phép AI trả lời dựa trên dữ liệu riêng của bạn thông qua vector store:
chatClient.prompt()
.advisors(
QuestionAnswerAdvisor.builder(vectorStore).build()
)
.user("Chính sách nghỉ phép của công ty là gì?")
.call()
.content();
5. Chat Memory - Nhớ ngữ cảnh hội thoại
chatClient.prompt()
.advisors(
MessageChatMemoryAdvisor.builder(chatMemory).build()
)
.user(userMessage)
.call()
.content();
6. Observability & ETL Framework
- Observability: Tích hợp sẵn monitoring và tracing cho mọi AI operation
- ETL Framework: Pipeline để load, transform và lưu trữ documents vào vector store
- Model Evaluation: Utilities để đánh giá chất lượng output từ AI
Hỗ trợ đa dạng AI Providers
Spring AI không lock bạn vào một provider duy nhất. Chỉ cần thay đổi dependency và config, bạn có thể switch giữa:
Chat Models:
- OpenAI (GPT-4, GPT-4o, …)
- Anthropic (Claude)
- Google GenAI / Vertex AI (Gemini)
- Azure OpenAI
- Amazon Bedrock
- Ollama (chạy local models)
- Mistral AI, Groq, DeepSeek
- Và 15+ providers khác
Vector Stores (20+):
- PGVector, Pinecone, Qdrant, Weaviate, Chroma
- Redis, Milvus, MongoDB Atlas, Elasticsearch
- Neo4j, Azure Cosmos DB, Oracle, và nhiều hơn
SearchRequest request = SearchRequest.builder()
.query("spring boot security")
.topK(5)
.similarityThreshold(0.7)
.filterExpression("category == 'tutorial' && year >= 2024")
.build();
List<Document> results = vectorStore.similaritySearch(request);
Ngoài ra còn hỗ trợ: Text-to-Image, Audio Transcription, Text-to-Speech, Content Moderation.
Có thể làm gì với Spring AI?
- Q&A trên tài liệu nội bộ: Ingest documents vào vector store, dùng RAG để trả lời câu hỏi dựa trên dữ liệu của bạn
- AI-powered REST APIs: Expose ChatClient qua Spring MVC/WebFlux endpoints
- Intelligent Agents: Cho AI gọi Java methods để query database, gọi API, gửi email, trigger workflows
- Content Generation: Tạo nội dung có cấu trúc, map thẳng sang Java records
- Semantic Search: Tìm kiếm theo ngữ nghĩa với embedding models và vector stores
- Chatbot đa lượt: Dùng Chat Memory advisors cho hội thoại nhiều lượt
- Multi-model: Kết hợp nhiều providers trong cùng một ứng dụng (ví dụ: OpenAI cho chat, Ollama cho embeddings)
Bắt đầu nhanh
Yêu cầu: Spring Boot 3.4.x+ và JDK 17+
Bước 1: Thêm BOM (Maven)
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.1.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Bước 2: Thêm starter dependency (ví dụ OpenAI)
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
Bước 3: Cấu hình API key
spring.ai.openai.api-key=${OPENAI_API_KEY}
Bước 4: Inject và sử dụng
@RestController
class ChatController {
private final ChatClient chatClient;
ChatController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/chat")
String chat(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
}
Bạn cũng có thể dùng start.spring.io để bootstrap project với AI dependencies đã được chọn sẵn.
So sánh với các framework khác
| Spring AI | LangChain (Python) | LangChain4j (Java) | |
|---|---|---|---|
| Ecosystem | Native Spring Boot, auto-config | Python-native | Java, hỗ trợ Spring hạn chế |
| Design | Spring idioms (DI, POJOs, Advisors) | Chain-based | Chain-based, builder |
| Enterprise | Được xây dựng cho enterprise Java | Community-driven | Community-driven |
| Observability | Built-in Spring observability | Third-party | Hạn chế |
| Vector Stores | 20+ databases, portable filter API | Nhiều | Tốt |
| Backing | Official Spring team (VMware/Broadcom) | Community | Community |
Điểm khác biệt lớn nhất: Spring AI là framework AI chính thức từ Spring team, được tích hợp first-class với Spring Boot, Spring Security, Spring Data và toàn bộ hệ sinh thái Spring.
Phiên bản hiện tại
- 1.1.2 (stable) — Phiên bản ổn định cho Spring Boot 3.x
- 2.0.0-M2 (preview) — Xây dựng trên Spring Boot 4.0 / Spring Framework 7.0, yêu cầu JDK 21
Kết luận
Spring AI là bước tiến lớn cho Java developers muốn bước vào thế giới AI. Với thiết kế quen thuộc của Spring, hỗ trợ đa dạng providers, và các tính năng mạnh mẽ như Tool Calling, RAG, Structured Output — bạn có thể xây dựng ứng dụng AI production-ready mà không cần phải chuyển sang Python.
Nếu bạn đã biết Spring Boot, thì Spring AI gần như không có learning curve. Hãy thử ngay!
Happy coding!