Java tutorial · Intermediate · 14 min
A RAG over your procedures in Java with LangChain4j
"Which documents do we need to open an account for a property holding company?" The answer is in the KYC procedure, page 34. A RAG (retrieval-augmented generation) assistant finds the relevant passages in your documents, then asks a language model to answer from them alone, citing the source. Here is how to build one in Java with LangChain4j.
Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)
The principle in three steps
- Index: split the documents into passages, compute a vector (embedding) that represents the meaning of each, and store them in a vector database.
- Retrieve: for each question, find the closest passages.
- Generate: send the question and those passages to the model, with the instruction to answer from them only.
1. Dependencies
build.gradle
dependencies {
implementation platform('dev.langchain4j:langchain4j-bom:X.Y.Z') // latest version on Maven Central
implementation 'dev.langchain4j:langchain4j'
implementation 'dev.langchain4j:langchain4j-easy-rag' // loading, splitting, default embeddings
implementation 'dev.langchain4j:langchain4j-ollama' // model running on your own servers
}
The BOM keeps module versions aligned. For a first try, Ollama runs an open model on a workstation or internal server: no data leaves the company. LangChain4j also has modules for hosted providers (Mistral AI, Anthropic, Azure OpenAI and others), to choose according to your hosting constraints.
2. The assistant
interface ProceduresAssistant {
@SystemMessage("""
You help compliance teams. Answer only from the procedure excerpts provided.
State the document and section used. If the answer is not there, say you do not know.
""")
String answer(String question);
}
// Indexing: reads the folder, splits and computes the embeddings
List<Document> documents = FileSystemDocumentLoader.loadDocuments(Path.of("procedures"));
InMemoryEmbeddingStore<TextSegment> store = new InMemoryEmbeddingStore<>();
EmbeddingStoreIngestor.ingest(documents, store);
// Local language model
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("mistral")
.temperature(0.0)
.build();
ProceduresAssistant assistant = AiServices.builder(ProceduresAssistant.class)
.chatModel(model)
.contentRetriever(EmbeddingStoreContentRetriever.from(store))
.build();
System.out.println(assistant.answer("Which documents are needed to open an account for a property company?"));
LangChain4j generates the implementation of the interface: on each call it finds the relevant passages, adds them to the question and queries the model. A temperature of zero limits creativity, which is what you want here.
3. From prototype to production
The prototype fits in twenty lines. Making it reliable is where the work lies:
- An embedding model suited to your language: the default model that comes with easy-rag is trained mostly on English. For documents in French or other languages, pick a multilingual model, and use the same one for indexing and search.
- Splitting that respects the documents: by section rather than by character count, with metadata (procedure name, version, date, section) for precise citations.
DocumentSplitters.recursive(...)is a good starting point. - A persistent vector store: PostgreSQL with pgvector (
langchain4j-pgvectormodule) is often enough, and your team already knows how to run it. - Access rights: users must only retrieve documents they are allowed to read. Filter the search on metadata.
- An evaluation set: thirty to fifty real questions with the expected answer, replayed on every change of model, splitting or instructions.
- Up-to-date content: re-index when a procedure changes, and remove outdated versions.
4. The Quarkus version
With the Quarkus LangChain4j extension, the assistant becomes an injectable bean, configured in application.properties:
@RegisterAiService(retrievalAugmentor = ProceduresRetrieval.class)
public interface ProceduresAssistant {
@SystemMessage("Answer only from the procedures provided and cite the source.")
String answer(@UserMessage String question);
}
5. The sector's rules
- AI Act: an internal assistant on procedures is usually minimal risk, but your staff must be trained to use it. Our AI Act guide and the self-assessment help you check.
- DORA: a hosted model provider is an ICT third-party provider, to be recorded in the register.
- GDPR: questions may contain personal data. Set how long conversations are kept and who can access them.
- The decision stays human: the assistant prepares, cites and speeds things up; the analyst decides.
An assistant on your procedures, tested on your documents
At the Lab, we build this prototype on your own procedures within hours: you see what it is worth before investing. First hour free.