RAG from Java

Ingest documents and ask questions about them from Java with llm4s-java-rag: answers come with the chunks they were drawn from.

Table of contents

  1. What llm4s-java-rag is
  2. Add the dependency
  3. Build a pipeline
  4. Ingest documents
  5. Ask a question
  6. Hold a conversation
  7. Stream an answer
  8. Search without a model
  9. Filter and threshold a search
  10. Choose a store
  11. Close it
  12. Handling a failure
  13. Where next

What llm4s-java-rag is

Retrieval-augmented generation (RAG) answers a question from your own documents: the documents are split into chunks, each chunk is embedded as a vector, and a question is answered by a model that is given the chunks that match it best. llm4s-java-rag puts the RAG pipeline of llm4s-rag behind one Java class, JRag: you hand it the embedding and chat clients of the Java facade, ingest files or text, and ask. Every call returns an LlmResult, as JLlmClient’s do, so a failure is a value you check, not an exception.

It is a module of its own, not part of llm4s-java-api, because llm4s-rag brings document parsing (Tika, POI, PDFBox), the AWS S3 SDK and the SQLite and Postgres drivers: a Java application that only calls a model does not receive them. It is Experimental: its API may change in any release (1.0 Scope).

llm4s-java-rag is new: it is published from 0.6.0.

Add the dependency

The artifact is org.llm4s:llm4s-java-rag_3; it brings llm4s-java-api and llm4s-rag with it, and no provider module: declare the ones your chat and embedding models use, as for llm4s-java-api.

Maven

1
2
3
4
5
<dependency>
    <groupId>org.llm4s</groupId>
    <artifactId>llm4s-java-rag_3</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle (Kotlin DSL)

1
2
3
dependencies {
    implementation("org.llm4s:llm4s-java-rag_3:1.0.0")
}

sbt

1
libraryDependencies += "org.llm4s" %% "llm4s-java-rag" % "1.0.0"

It needs JDK 21, like llm4s-java-api.

Build a pipeline

A pipeline needs an embedding client; to ask, a chat client too. With both configured in application.conf (see Embeddings and Configure a provider):

1
2
3
4
5
JRag rag = JRag.builder()
    .embeddings(Llm4s.createDefaultEmbeddingClient().get())
    .llm(Llm4s.createDefaultClient().get())
    .build()
    .get();

The imports are org.llm4s.javaapi.rag.* for JRag and its types, and org.llm4s.javaapi.* for Llm4s, LlmResult and the clients. Any JEmbeddingClient and JLlmClient will do: one from Llm4s.createEmbeddingClient, from a builder, or a Scala client wrapped with Llm4s.wrapClient. The pipeline embeds every chunk as a document and every question as a query, with the embedding client’s model; keep using the same model for a store, since vectors from two models cannot be compared.

build() sends no request and never throws. An embedding client or store left out, or a setting out of range, is a failed result of kind VALIDATION that names the field.

Ingest documents

ingest(Path) reads a file, or every file directly in a directory whose name ends in .txt, .md, .pdf, .docx, .json, .xml or .html, and returns how many chunks it indexed. ingestText indexes text you already have, under an id you choose. Both take metadata, attached to every chunk:

1
2
int chunks = rag.ingest(docs).get();
chunks += rag.ingestText("Refunds are paid within 14 days.", "refund-policy", Map.of("team", "billing")).get();

A file’s id is its absolute path, and a directory is read with its subdirectories. Ingesting an id again replaces what was indexed under it, so re-ingest a document after it changes; delete(documentId) removes one and clear() removes them all. documentCount(), chunkCount() and storedChunkCount() read the store, so a pipeline over a SQLite store counts what an earlier run indexed too. storedChunkCount() returns a failed result when the store cannot be read, where the other two count 0.

To keep the store in step with a directory, sync(path) ingests the files that are new, re-ingests the ones that changed, leaves the unchanged ones alone, without embedding them again, and deletes the documents of files that are gone:

1
2
JRagSyncStats stats = rag.sync(docs).get();
System.out.println(stats.added() + " added, " + stats.updated() + " updated, " + stats.deleted() + " deleted");

A SQLite store records what each sync indexed in a third file beside its two (docs-registry.db), so a sync after a restart changes only what changed. An in-memory store starts empty, so its first sync ingests everything. A file that cannot be read is listed in failures() and keeps what was indexed for it before. To sync two directories into one store, give each its own source with sync(path, sourceId); otherwise each sync deletes the other’s documents.

Ask a question

ask embeds the question, finds the chunks that match it best and asks the model to answer from them alone. The answer is a JRagAnswer: its text, the question, and its sources(), best match first:

1
2
3
4
5
JRagAnswer answer = rag.ask("How long do refunds take?").get();
System.out.println(answer.answer());
for (JRagSource source : answer.sources()) {
    System.out.println("  " + source.documentId() + " (" + source.score() + "): " + source.content());
}

A JRagSource has the chunk’s content(), the documentId() it came from, its score() and its metadata(): what you attached, plus docId and chunkIndex, and for a file its name as source and its absolute path. A score compares the sources of one search, not of two. usage() is the tokens the model call used, when the provider reports them. When no chunk is found, for instance because nothing is indexed, the model is not asked: the answer says that nothing relevant was found, and has no sources and no usage.

A question is answered from at most five chunks; set another number with the builder’s topK, or for one question with ask(question, topK). The model is told to answer from the chunks alone, to say when they are not enough and to cite the chunks it uses as [n]; replace those instructions with the builder’s systemPrompt. Each chunk is sent fenced in <context> tags, with its source and heading, and the instructions, yours too, end with a line saying that text inside those tags is data, not instructions. A repeated chunk is sent once, and the lowest-ranked are left out when the question and chunks would not fit the model’s context window. The model answers at temperature 0.0, so it keeps to the chunks; give the builder completionOptions(JCompletionOptions.builder().temperature(0.3).maxTokens(512).build()) for other options.

Hold a conversation

For a chat, pass the conversation so far, oldest first, as the history: the model sees it before the chunks and the question, so it can answer a follow-up. Build the messages with JMessage.user and JMessage.assistant:

1
2
3
4
List<JMessage> history = List.of(
    JMessage.user("How long do refunds take?"),
    JMessage.assistant("Refunds are paid within 14 days."));
JRagAnswer answer = rag.ask("And how do I ask for one?", history).get();

ask(question, topK, history), askStream(question, history, listener) and askStream(question, topK, history, listener) take it too. A null history, a null message in it, or a SYSTEM message (the pipeline sends its own instructions) is a failed result of kind VALIDATION.

A follow-up such as “and the second one?” finds poor chunks on its own. Give the builder a question condenser and, when there is a history, the search uses a standalone question built from it, while the model still answers the question asked. llmQuestionCondenser(client) asks a model to rewrite the question (a small, fast one is usually enough), with the latest 10 user and assistant messages; a failed call fails the ask with that failure’s kind, and a blank reply searches with the question asked. questionCondenser((question, history) -> ...) takes your own function; a null or blank return searches with the question asked.

Stream an answer

askStream answers as ask does, but streams the answer to a listener as the model generates it, so a chat UI can show the sources first and the text as it arrives. The listener hears onSources once, before the model is asked, then onChunk for each piece of the answer’s text, then exactly one of onComplete (the whole JRagAnswer) or onError. askStream returns at once with a running JRagAnswerStream:

1
2
3
4
5
6
7
8
9
10
11
12
JRagAnswerStream stream = rag.askStream("How long do refunds take?", new JRagStreamListener() {
    @Override
    public void onSources(List<JRagSource> sources) {
        sources.forEach(s -> System.out.println("[" + s.documentId() + "]"));
    }

    @Override
    public void onChunk(String text) {
        System.out.print(text);
    }
}).get();
JRagAnswer answer = stream.await().get();

Only onChunk must be implemented, so a lambda is a listener: rag.askStream(question, System.out::print). The search and the model call run on a virtual thread of the stream’s own, and the listener is called there, one call at a time. await() blocks until the listener has heard the end and returns the same outcome. cancel(), or close() in a try-with-resources block, interrupts that thread, which is how llm4s providers are cancelled: no further piece is delivered and onError hears a CANCELLED failure. It works as JLlmClient.stream’s CompletionStream does; see Java threading and cancellation.

What ask fails at once - a null or blank question, a pipeline without a chat client - askStream fails at once, and the listener hears nothing. A failure once the call has started reaches onError: of the search, with no onSources before it, or of the model, after the pieces already delivered. A listener that throws stops the call, and onError hears what it threw. For a Reactor Flux of the same events, see Streaming to Reactor; for a Kotlin Flow, see Answer questions over your documents.

Search without a model

search returns the chunks ask would answer from, without calling a model, so it works on a pipeline built with no chat client:

1
List<JRagSource> sources = rag.search("refunds", 3).get();

The search is hybrid: a chunk’s score fuses its vector similarity to the question with a keyword match, so a rare word in the question (a product name, an error code) finds its chunk even when the embedding model does not know it.

search, ask and askStream also take a JRagQueryOptions: a metadata filter, a minimum score and a topK for that call.

1
2
3
4
5
JRagQueryOptions options = JRagQueryOptions.defaults()
    .filter(JRagFilter.equalTo("team", "billing").and(JRagFilter.hasKey("source")))
    .minScore(0.6)
    .topK(3);
JRagAnswer billing = rag.ask("How long do refunds take?", options).get();

JRagFilter matches a chunk’s metadata with equalTo, contains, hasKey and in, combined with and, or and negate. The filter is applied inside the store’s search. The minimum score is a vector similarity from 0 to 1: every store scores on the same scale, (1 + cos) / 2, so 0.5 is an unrelated chunk. It is not a source’s score(), which is the fused score. A chunk that only the keyword search found has no vector similarity, so a minimum score leaves it out. When the options leave no chunk, ask does not call the model and answers that nothing relevant was found; set another answer with noContextAnswer. A value out of range is a failed result of kind VALIDATION.

Choose a store

Chunks are kept in memory unless you say otherwise, and are lost when the pipeline is closed. JRag.sqlite keeps them in SQLite files, which a later pipeline over the same file reads again:

1
2
3
4
5
6
7
8
JRag rag = JRag.builder()
    .embeddings(embedder)
    .llm(client)
    .store(JRag.sqlite(dir.resolve("docs.db")))   // and docs-fts.db beside it
    .chunking(800, 150)
    .topK(5)
    .build()
    .get();

The vectors go in docs.db and the keyword index in docs-fts.db. chunking(size, overlap) splits documents into chunks of about size characters, each repeating the last overlap characters of the one before; chunks end at a sentence where they can, and a chunk shorter than 100 characters is merged into its neighbour. The defaults are 800 and 150.

The builder also chooses how documents are split, how the two searches are fused and whether the results are reranked:

1
2
3
4
5
6
7
8
JRag tuned = JRag.builder()
    .embeddings(embedder)
    .llm(client)
    .chunking(JRagChunking.MARKDOWN, 1000, 100)
    .fusion(JRagFusion.weighted(0.7, 0.3))
    .reranker(JRagReranker.llm().candidates(20))
    .build()
    .get();
  • JRagChunking is SENTENCE (what chunking(size, overlap) uses), SIMPLE, MARKDOWN or SEMANTIC. SEMANTIC embeds each sentence at ingest to find where the topic changes.
  • JRagFusion is rrf() (the default), rrf(k), weighted(vectorWeight, keywordWeight), vectorOnly() or keywordOnly().
  • JRagReranker.llm() asks the builder’s chat client to score each candidate. JRagReranker.cohere() calls Cohere’s reranking API, with the key from llm4s.rerank.cohere.apiKey or COHERE_API_KEY. A reranker orders candidates(n) chunks, 20 by default, and keeps the best topK.

Postgres and pgvector and GraphRAG are available from Scala (see Vector store) but not yet from Java.

Close it

JRag is AutoCloseable: closing it releases its store. It does not close the clients it was built with, which may serve other pipelines; close those yourself.

1
2
3
4
try (JRag rag = JRag.builder().embeddings(embedder).llm(client).build().get()) {
    rag.ingest(docs).get();
    System.out.println(rag.ask("How long do refunds take?").get().answer());
}

Different documents may be ingested from several threads at once; the same document id from two threads at once is not supported.

Handling a failure

Every call blocks the calling thread and never throws. A failure is a failed LlmResult whose getError().getKind() says what went wrong, as for the Java facade:

1
2
3
4
5
6
7
8
9
10
LlmResult<JRagAnswer> result = rag.ask("How long do refunds take?");
if (result.isFailure()) {
    LlmException error = result.getError();
    switch (error.getKind()) {
        case VALIDATION -> System.err.println("Fix the call: " + error.getMessage());
        case AUTHENTICATION, CONFIGURATION -> System.err.println("Fix the setup: " + error.getMessage());
        case RATE_LIMIT -> System.err.println("Try again later");
        default -> System.err.println("Failed: " + error.getMessage());
    }
}
  • VALIDATION: a null or blank argument, a topK below 1, metadata with a null key or value, or a path that does not exist.
  • CONFIGURATION: ask or askStream on a pipeline built without a chat client.
  • A failure of the embedding provider or the model has that failure’s kind: AUTHENTICATION, RATE_LIMIT, SERVICE, NETWORK, TIMEOUT. A file that cannot be read is OTHER.
  • Interrupting the blocked thread is CANCELLED, with the thread’s interrupt flag still set.

Where next

  • Java: the clients a pipeline is built from, and how to read a result.
  • Vector store and RAG query transformers: the pipeline in Scala, with every store and option.
  • The sample org.llm4s.samples.rag.JavaRagExample in modules/samples.