Skip to content
JavaAgentic

Type at least two characters. Try “RAG”, “pgvector” or “tool calling”.

LangChain4j Cheat Sheet

LangChain4j essentials in one page: AiServices, chat models, memory, embedding stores, retrievers and tools, with the annotations and builders you need.

AI Services

  • Declare an interface

    The implementation is generated against the model.

    interface Assistant { String chat(String message); }
  • Build it

    Wire the model, memory, tools and retriever.

    AiServices.builder(Assistant.class).chatModel(model).build();
  • @SystemMessage

    Static role instructions for every call.

    @SystemMessage("You are a Java expert.")
  • @UserMessage

    Template with {{it}} or named @V parameters.

    @UserMessage("Summarise: {{text}}") String summarise(@V("text") String text);
  • Typed return

    Return a POJO, enum, List or boolean and it is parsed for you.

    Sentiment analyse(String review);  // enum Sentiment

Memory

  • Message window

    Keep the last N messages — simple and predictable.

    MessageWindowChatMemory.withMaxMessages(20)
  • Token window

    Bound memory by tokens instead of message count.

    TokenWindowChatMemory.withMaxTokens(2000, tokenizer)
  • Per user

    Memory keyed by a @MemoryId argument.

    .chatMemoryProvider(id -> MessageWindowChatMemory.withMaxMessages(20))

Retrieval

  • Load documents

    Filesystem, URL, S3, GitHub — plus Tika for mixed formats.

    FileSystemDocumentLoader.loadDocuments(dir, new ApacheTikaDocumentParser());
  • Split

    Recursive splitter with overlap preserves sentence boundaries.

    DocumentSplitters.recursive(600, 120)
  • Ingest

    Split, embed and store in one pipeline.

    EmbeddingStoreIngestor.builder().documentSplitter(splitter).embeddingModel(m).embeddingStore(s).build().ingest(docs);
  • Retriever

    Attach to an AI Service to get RAG automatically.

    EmbeddingStoreContentRetriever.builder().embeddingStore(s).maxResults(5).minScore(0.6).build();

Tools

  • Define

    Annotate a method; the description drives model selection.

    @Tool("Adds two numbers") int add(int a, int b) { return a + b; }
  • Register

    Pass the object holding the tool methods.

    AiServices.builder(Assistant.class).tools(new Calculator()).build();
  • Guard the loop

    Cap tool iterations so a confused agent cannot spin.

    .maxSequentialToolsInvocations(5)