SkilVaultSign inStart free

Catalogue / langchain4j-rag-pipelines

langchain4j-rag-pipelines

Older skill: source not recordedSignedGuides implementation of Retrieval-Augmented Generation in Java using LangChain4j, covering document loading and splitting, embedding models, embedding stores, ingest pipelines, metadata filtering, AI services wired to retrievers, and re-ranking. Use when building question answering over document co…
---
name: langchain4j-rag-pipelines
description: >
  Guides implementation of Retrieval-Augmented Generation in Java using
  LangChain4j, covering document loading and splitting, embedding models,
  embedding stores, ingest pipelines, metadata filtering, AI services wired
  to retrievers, and re-ranking. Use when building question answering over
  document collections, knowledge-base assistants, or semantic search in a
  Java or Spring Boot codebase. Not for Python LLM tooling, agent
  orchestration frameworks, or model fine-tuning.
allowed-tools: Read, Write, Edit
---

Java RAG Pipelines with LangChain4j

Build retrieval-augmented applications in Java: load documents, split them into chunks, embed the chunks into a vector store, retrieve the best matches for a question, and answer through an AI service grounded in that context. RAG trades hallucination for grounded answers, but only when ingestion, filtering, and prompting are done deliberately — this skill walks each stage with the reasoning behind it.

This skill does not cover multi-modal retrieval over images or audio, token-streaming responses, or autonomous agent orchestration; it stays within text retrieval pipelines.

Workflow overview

  1. Lay down dependencies.
  2. Configure the embedding model, chat model, and vector store.
  3. Build the ingest pipeline: load → enrich metadata → split → embed → store.
  4. Configure retrieval: top-k, score floor, filters.
  5. Expose an AI service that answers from retrieved context.
  6. Optionally add query compression and re-ranking.
  7. Tune, test, and troubleshoot.

Step 1: Lay down dependencies

For a Spring Boot project, add the starter plus the model module:

<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai</artifactId>
    <version>1.8.0</version>
</dependency>

Keep every dev.langchain4j artifact on the same version — mixed versions are a common source of runtime errors. When the user picks a vector store, add that store's artifact too (for example the pgvector or qdrant module). If the project is plain Java rather than Spring, skip the starter and construct the same objects by hand; every bean below is just a plain object.

Step 2: Configure models and store

@Configuration
public class RagConfig {

    @Bean
    EmbeddingModel embeddingModel() {
        return OpenAiEmbeddingModel.builder()
                .apiKey(System.getenv("OPENAI_API_KEY"))
                .modelName("text-embedding-3-small")
                .build();
    }

    @Bean
    ChatModel chatModel() {
        return OpenAiChatModel.builder()
                .apiKey(System.getenv("OPENAI_API_KEY"))
                .modelName("gpt-4o-mini")
                .build();
    }

    @Bean
    EmbeddingStore<TextSegment> embeddingStore() {
        return new InMemoryEmbeddingStore<>(); // development only — see store table below
    }
}

Reasoning for each choice:

  • Have the application read credentials from environment variables or a secrets store the user already controls. Never place a literal key in source, in committed configuration, or in log output.
  • The store's vector dimension must match the embedding model's output dimension (1536 for text-embedding-3-small). Mismatched dimensions fail at first search, not at startup, so set them together.
  • In-memory is fine for tests and demos; data is lost on restart. Pick a persistent store before anything resembling production.

Choosing a store

| Store | Module to add | Reach for it when | |---|---|---| | InMemoryEmbeddingStore | core | Unit tests, demos, small prototypes | | PgVectorEmbeddingStore | pgvector | Postgres already in the stack; one database for rows and vectors | | QdrantEmbeddingStore | qdrant | Self-hosted dedicated vector search with rich filtering | | ChromaEmbeddingStore | chroma | Lightweight local development server | | WeaviateEmbeddingStore | weaviate | Combined vector and keyword workflows | | PineconeEmbeddingStore | pinecone | Fully managed service, minimal operations | | MilvusEmbeddingStore | milvus | Very large collections, high throughput | | Neo4jEmbeddingStore | neo4j | Graph context alongside vectors, plus a full-text index | | MongoDbEmbeddingStore | mongodb-atlas | Vectors living beside documents already in Atlas |

Set the create-table / create-index flags for the first run, then consider disabling them so stray restarts cannot alter schema.

Step 3: Build the ingest pipeline

Chain loading, metadata enrichment, splitting, embedding, and storing with EmbeddingStoreIngestor. Example — ingesting an HR handbook per tenant:

@Service
@RequiredArgsConstructor
public class HandbookIngestor {

    private final EmbeddingStore<TextSegment> store;
    private final EmbeddingModel model;

    public void ingest(Path file, String tenantId) {
        Document doc = FileSystemDocumentLoader.loadDocument(file);
        doc.metadata().put("tenant", tenantId);
        doc.metadata().put("kind", "hr-handbook");
        doc.metadata().put("ingestedAt", LocalDate.now().toString());
        doc.metadata().put("version", 3);

        EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()
                .documentSplitter(DocumentSplitters.recursive(
                        450, 45,
                        new OpenAiTokenCountEstimator("text-embedding-3-small")))
                .embeddingModel(model)
                .embeddingStore(store)
                .build();

        ingestor.ingest(doc);
    }
}

Why each piece matters:

  • Metadata at ingest time is what makes filtering, attribution, and multi-tenancy possible later. Write the keys you intend to filter on, with exact names — a mismatch between ingest keys and query filters silently returns nothing.
  • Overlap (45 tokens here) keeps sentences that straddle a chunk boundary retrievable from both sides. Without it, boundary-spanning facts get orphaned.
  • Token-aware splitting matters because embedding providers bill and cap by tokens; a token estimator keeps chunks inside the model's window.
  • Batching: pass an entire collection to ingestor.ingest(documents) in one call rather than looping per document. Batched embedding of, say, 120 handbooks in one pass is dramatically cheaper and faster than 120 separate API calls. Read IngestionResult.tokenUsage() afterward and report the token count to the user.

Loaders available: FileSystemDocumentLoader for paths, ClassPathDocumentLoader for bundled resources, UrlDocumentLoader for web pages. Only point the URL loader at addresses the user explicitly named.

Splitter options

| Splitter | Behaviour | Good for | |---|---|---| | DocumentSplitters.recursive | Descends paragraphs → sentences → words until chunks fit the cap | Default for prose | | byParagraph / bySentence / byLine | Splits strictly on that boundary | Structured or line-oriented text |

Start in the 300–500 token range with 10–50 tokens of overlap. Smaller chunks sharpen retrieval precision but fragment context; larger chunks preserve context but drag in noise. There is no universally right size — measure retrieval quality on real questions before tuning further.

Confirmation before bulk ingest

Before you ingest more than a couple of documents, or anything the user has not already staged for you, stop and get explicit approval. Embedding a corpus sends its full text to the embedding provider (data leaves the machine) and bills the user's account. Tell the user the document count, an estimated token total — a one-document dry run with tokenUsage() gives a solid per-document estimate — and wait for a yes.

Step 4: Configure retrieval

@Bean
ContentRetriever contentRetriever(EmbeddingStore<TextSegment> store, EmbeddingModel model) {
    return EmbeddingStoreContentRetriever.builder()
            .embeddingStore(store)
            .embeddingModel(model)
            .maxResults(4)
            .minScore(0.65)
            .dynamicFilter(query -> new IsEqualTo("tenant", currentTenant()))
            .build();
}
  • maxResults of 3–5 chunks suits standard context windows; more chunks dilute the prompt.
  • minScore (0–1 relevance) trades precision against recall. 0.65–0.85 is the usual band; raise it when wrong chunks pollute answers, lower it when valid answers come back empty-handed.
  • dynamicFilter runs per request — this is where tenant and access scoping belongs, not in an optional static filter someone can forget to set.

Handle empty retrieval deliberately. Over-tight filters legitimately return zero matches. Log the filter and result count on every query; when retrieval is empty, either tell the user no matching documents exist or answer with an explicit "not found in the knowledge base" caveat. Do not silently drop the filter to force results.

Step 5: Expose an AI service

interface PolicyAssistant {
    @SystemMessage("""
            You answer staff questions using only the supplied handbook excerpts.

            Rules:
            - Ground every claim in the retrieved excerpts.
            - If the excerpts do not contain the answer, say so plainly; do not guess.
            - Name the document and section you drew from when available.
            """)
    String ask(@MemoryId String userId, String question);
}

@Service
public class PolicyQA {
    private final PolicyAssistant assistant;

    public PolicyQA(ChatModel chatModel, ContentRetriever retriever) {
        this.assistant = AiServices.builder(PolicyAssistant.class)
                .chatModel(chatModel)
                .contentRetriever(retriever)
                .build();
    }

    public String answer(String userId, String question) {
        return assistant.ask(userId, question);
    }
}

The framework embeds the question, runs the retriever, and injects matching excerpts into the prompt before the model answers — you never assemble that context by hand. @MemoryId keys conversation memory per user so one employee's follow-up question does not bleed into another's session. The system message carries the grounding discipline: it is your main lever against the model improvising beyond the excerpts.

Step 6: Optional upgrades

Query compression and re-ranking. In multi-turn chats, the raw user message is a poor search query ("what about part-time staff?" embeds badly on its own). A compressing transformer condenses the conversation into one focused query; a re-ranker then scores candidate chunks against it and keeps the best:

RetrievalAugmentor augmentor = DefaultRetrievalAugmentor.builder()
        .queryTransformer(new CompressingQueryTransformer(chatModel))
        .contentRetriever(baseRetriever)
        .contentAggregator(ReRankingContentAggregator.builder()
                .scoringModel(scoringModel)
                .minScore(0.8)
                .build())
        .build();

// then: AiServices.builder(PolicyAssistant.class).retrievalAugmentor(augmentor)...

Tenant isolation. Default to one shared store with a mandatory dynamicFilter on tenant. Use a store per tenant only when compliance demands hard physical separation — it multiplies operational overhead.

Hybrid search. Run vector search and a keyword/full-text engine in parallel and fuse their rankings (reciprocal rank fusion); exact names and codes that embeddings miss, keyword search catches. Neo4j's store can host both behind one index.

Metadata filter toolkit

Compose filters from these when scoping retrieval:

| Operation | Meaning | |---|---| | IsEqualTo / IsNotEqualTo | Exact match / exclusion on a metadata key | | IsGreaterThan, IsGreaterThanOrEqualTo, IsLessThan, IsLessThanOrEqualTo | Numeric comparison | | IsIn / IsNotIn | Membership in a value list |

Preview shortened. The full SKILL.md is in the pack.