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

  1. Index: split the documents into passages, compute a vector (embedding) that represents the meaning of each, and store them in a vector database.
  2. Retrieve: for each question, find the closest passages.
  3. 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:

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

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.

The Lab All tutorials

Worth a look