This content originally appeared on DEV Community and was authored by lucasnscr
Quarkus Book Recommendation System
An intelligent book recommendation system built with Quarkus and LangChain4j, demonstrating the power of AI to personalize reading experiences. The system uses multiple AI providers (OpenAI, Mistral AI, and Ollama) to deliver personalized recommendations based on user profiles and reading history.
Features
Multi-AI Support: Switch between OpenAI, Mistral AI, and Ollama
Personalized Recommendations: AI analyzes preferences and history to suggest books
Conversational Memory: Maintains context for personalized interactions
Intelligent Search: AI tools to search for books by multiple criteria
Pattern Analysis: AI analyzes reading habits and suggests diversification
Similar Recommendations: Finds similar books based on specific titles
Quarkus Performance: Fast startup and low memory footprint
Simple Configuration: Environment variable-based configuration
Architecture
Architecture and Tool Calling with LangChain4j
This system demonstrates advanced usage of the Tool Calling pattern with Quarkus and LangChain4j, integrating AI with external tools and databases. This approach allows language models to access APIs and local repositories to deliver personalized responses based on real-time and accurate data.
Integration with @Tool
We use the @Tool
annotation to expose Java methods as tools that can be accessed by the AI model. This enables the AI to:
- Query books stored in the database via JPA (Panache).
- Access user preferences and reading history.
- Perform filtering and smart analysis using real business logic.
Example of a Service with AI Tools
@RegisterAiService(tools = {BookSearchTools.class, UserProfileTools.class})
public interface BookRecommendationService {
@UserMessage("""
Based on my preferences, which books do you recommend?
""")
String recommendBooksForUser(Long userId);
}
Output Validation Guardrails
You can apply custom validations to the model’s responses using @OutputGuardrails
, ensuring result format, safety, and consistency.
Logging and Observability
Quarkus allows detailed logging of model interactions and external API calls:
quarkus.langchain4j.log-requests=true
quarkus.langchain4j.log-responses=true
Automated Testing with Quarkus
To ensure reliability, endpoints are tested using quarkus-junit5
along with mocked dependencies via quarkus-junit5-mockito
.
This addition highlights how your system uses Tool Calling robustly and aligns with modern intelligent agent development practices.
The system uses the AI Tools pattern from LangChain4j, allowing the AI to access database data and perform complex operations:
┌─────────────────┐ ┌──────────────────────┐ ┌─────────────────────┐
│ REST Client │───▶│ RecommendationController │───▶│BookRecommendationService│
└─────────────────┘ └──────────────────────┘ └─────────────────────┘
┌──────────────────────┐ ┌─────────────────────┐
│ BookController │───▶│ BookDataService │
└──────────────────────┘ └─────────────────────┘
│
┌────────────┼────────────┐
│ │ │
┌────▼────┐ ┌────▼────┐ ┌─────▼──────┐
│ Book │ │ User │ │ Config │
│ Search │ │ Profile │ │ Class │
│ Tools │ │ Tools │ └─────┬──────┘
└────┬────┘ └────┬────┘ │
│ │ │
┌─────────▼───┐ ┌───▼────────┐ │
│ Book │ │ User │ │
│ Repository │ │Repositories│ │
└─────────────┘ └────────────┘ │
│ │
┌────▼────┐ │
│ H2 │ │
│Database │ │
└─────────┘ │
│
┌────────────────────────▼────┐
│ LangChain4j │
│ AI Providers │
└────────────────────────────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌───────▼────────┐ ┌───────▼────────┐ ┌──────▼───────┐
│ OpenAI │ │ Mistral AI │ │ Ollama │
│ (gpt-4o-mini)│ │ (mistral-small)│ │ (llama3.2) │
└────────────────┘ └────────────────┘ └──────────────┘
Prerequisites
- Java 21 or higher
- Maven 3.8+ or Gradle
- Choose at least one AI provider:
OpenAI Configuration
- Create an account at OpenAI
- Generate an API key in the API keys section
- Set the environment variable
OPEN_AI_TOKEN
Mistral AI Configuration
- Create an account at Mistral AI
- Generate an API key in your dashboard
- Set the environment variable
MISTRAL_AI_TOKEN
Ollama Configuration
- Install Ollama from ollama.ai
- Start the Ollama service:
ollama serve
- Download a model:
ollama pull llama3.2
- Ensure Ollama is running at
http://localhost:11434
Configuration
Selecting the AI Provider
Set the AI provider using the AI_MODEL_PROVIDER
environment variable:
# For OpenAI (default)
export AI_MODEL_PROVIDER=openai
export OPEN_AI_TOKEN=your-openai-key
# For Mistral AI
export AI_MODEL_PROVIDER=mistral
export MISTRAL_AI_TOKEN=your-mistral-key
# For Ollama
export AI_MODEL_PROVIDER=ollama
Quick Start
1. Clone the Repository
git clone <repository-url>
cd quarkus-book-recommendation
2. Set Up Your AI Provider
Option A: Using OpenAI
export AI_MODEL_PROVIDER=openai
export OPEN_AI_TOKEN=your-real-key
Option B: Using Mistral AI
export AI_MODEL_PROVIDER=mistral
export MISTRAL_AI_TOKEN=your-real-key
Option C: Using Ollama
# Start Ollama first
ollama serve
# In another terminal, download a model
ollama pull llama3.2
# Set up the environment
export AI_MODEL_PROVIDER=ollama
3. Run the Application
Development Mode (with hot reload):
./mvnw quarkus:dev
Production Mode:
./mvnw clean package
java -jar target/quarkus-app/quarkus-run.jar
The application will start at http://localhost:8080
API Endpoints
Book Generation Endpoints
Generate Book List by Genre
Endpoint: GET /api/books/generate/{genre}
Generates a list of 10 books using AI for the specified genre.
Request Example:
curl -X GET "http://localhost:8080/api/books/generate/fantasy?sessionId=user123"
Get Book by ID
Endpoint: GET /api/books/{sessionId}/{id}
Retrieves a specific book by ID using AI with chat memory capabilities.
Request Example:
curl -X GET http://localhost:8080/api/books/user123/1
Recommendation Endpoints
Personalized User Recommendations
Endpoint: GET /api/recommendations/user/{userId}
Uses AI with LangChain4j tools to analyze the user profile and recommend personalized books.
Request Example:
curl -X GET http://localhost:8080/api/recommendations/user/1
Response Example:
Based on your profile and reading history, here are 5 perfect recommendations for you:
1. **Foundation** by Isaac Asimov
- Perfectly matches your love of epic science fiction like Dune
- Classic series with complex worldbuilding and deep political themes
2. **The Name of the Wind** by Patrick Rothfuss
- Epic fantasy with immersive storytelling, similar to Madeline Miller's style
- Poetic prose and exceptional character development
[...]
Find Similar Books
Endpoint: GET /api/recommendations/similar
Finds similar books based on a specific title and author.
Request Example:
curl -X GET "http://localhost:8080/api/recommendations/similar?title=Dune&author=Frank Herbert"
Recommendations by Genre and Criteria
Endpoint: GET /api/recommendations/genre/{genre}
Recommends books based on genre and specific criteria.
Request Example:
curl -X GET "http://localhost:8080/api/recommendations/genre/science-fiction?minRating=4.0&language=English&yearAfter=2010"
Reading Pattern Analysis
Endpoint: GET /api/recommendations/analysis/{userId}
Analyzes the user’s reading patterns and suggests diversification.
Request Example:
curl -X GET http://localhost:8080/api/recommendations/analysis/1
AI Tools
The system demonstrates advanced AI capabilities using LangChain4j tools:
Book Search Tools
- Search by Genre: Retrieve books by category
- Search by Author: Find books by specific authors
- Search by Rating: Filter books by minimum rating
- Search by Language: Filter books by language
- Search by Year: Find books by publication period
User Profile Tools
- User Preferences: Access stored reading preferences
- Reading History: Retrieve books read by the user
- Pattern Analysis: Identify trends in reading habits
AI Service Integration
The BookRecommendationService
combines both sets of tools to provide intelligent analysis:
@RegisterAiService(tools = {BookSearchTools.class, UserProfileTools.class})
public interface BookRecommendationService {
// AI can automatically call tools to analyze preferences
String recommendBooksForUser(Long userId);
// AI can find similar books using multiple criteria
String findSimilarBooks(String bookTitle, String author);
}
Technology Stack
- Quarkus 3.24.3 – Supersonic Subatomic Java Framework
-
LangChain4j – Java library for building AI applications
- OpenAI Integration (v1.0.2)
- Mistral AI Integration (v1.0.2)
- Ollama Integration (v1.0.2)
- Support for AI Tools and Agents
- JAX-RS (Quarkus REST) – RESTful web services
- Hibernate ORM with Panache – Database operations
- H2 Database – In-memory database for development
- Jackson – JSON processing
- CDI – Dependency injection
Development
Project Structure
src/main/java/com/example/books/
├── resources/
│ ├── BookController.java # REST endpoints for books
│ └── RecommendationController.java # Recommendation endpoints
├── service/
│ ├── BookDataService.java # AI service interface
│ └── BookRecommendationService.java # AI service with tools
├── model/
│ ├── Book.java # Book data model
│ ├── UserPreference.java # User preferences
│ └── ReadingHistory.java # Reading history
├── repository/
│ ├── BookRepository.java # Database operations for books
│ ├── UserPreferenceRepository.java # Preference operations
│ └── ReadingHistoryRepository.java # History operations
├── tools/
│ ├── BookSearchTools.java # Book search tools
│ └── UserProfileTools.java # User profile tools
└── api/
└── BookListResponse.java # API response models
Running Tests
./mvnw test
Development with Hot Reload
./mvnw quarkus:dev
This enables hot reload—changes to your code will be automatically reflected without restarting the application.
Demonstrated Use Cases
- Personalized Recommendations: AI analyzes the user’s complete profile
- Intelligent Search: AI tools for complex database queries
- Pattern Analysis: AI identifies trends and suggests diversification
- Conversational Memory: Context maintained between interactions
- Data Generation: AI creates realistic book data by genre
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
License
This project is open source and available under the MIT License.
Happy reading with AI!
This content originally appeared on DEV Community and was authored by lucasnscr