AI / LangChain4j interview questions
What is the AI Services feature in LangChain4j and how do you define one?
AI Services is the flagship abstraction in LangChain4j. The idea is simple but powerful: you write a plain Java interface, annotate its methods with LangChain4j annotations that describe what each method should do with the LLM, and the library generates a working implementation at runtime using JDK dynamic proxies. You never write prompt-construction or HTTP-calling code — that is all handled by the generated proxy.
A minimal example:
import dev.langchain4j.service.AiServices; import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; interface CodeReviewer { @SystemMessage("You are a senior Java developer. Review code concisely.") @UserMessage("Review this code snippet for bugs and style issues: {{code}}") String review(String code); } // Wire it up CodeReviewer reviewer = AiServices.builder(CodeReviewer.class) .chatLanguageModel(model) .build(); // Use it like any Java object String feedback = reviewer.review("public void foo() { int x = 1/0; }");
The interface method can return String for raw text, a custom POJO for structured output (LangChain4j adds JSON extraction instructions automatically), TokenStream for streaming, or AiMessage for full response metadata. You can also inject ChatMemory into the service for conversational state, add @Tool-annotated methods to the same class for function calling, and mix multiple retrieval augmentors for RAG — all declared at the builder level, none of it in your interface methods.
More Related questions...