Add advanced-rag module: Easy RAG, query compression and expansion, routing, minScore, content injection, chat-memory cost and sources, each with a captured transcript
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b85ApxQRK2Z8yuzC5r
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.lc4j.advancedrag;
|
||||
|
||||
import dev.langchain4j.data.document.Document;
|
||||
import dev.langchain4j.data.document.loader.ClassPathDocumentLoader;
|
||||
import dev.langchain4j.data.segment.TextSegment;
|
||||
import dev.langchain4j.model.embedding.EmbeddingModel;
|
||||
import dev.langchain4j.model.embedding.onnx.bgesmallenv15q.BgeSmallEnV15QuantizedEmbeddingModel;
|
||||
import dev.langchain4j.store.embedding.EmbeddingStore;
|
||||
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
|
||||
import dev.langchain4j.store.embedding.IngestionResult;
|
||||
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Easy RAG in one class: load files from the classpath, let EmbeddingStoreIngestor split and embed
|
||||
* them with the defaults the langchain4j-easy-rag module registers, and keep the vectors in memory.
|
||||
*/
|
||||
public final class KnowledgeBase {
|
||||
|
||||
/** The same quantized bge-small model Easy RAG picks by default. Created once: loading the ONNX model is slow. */
|
||||
public static final EmbeddingModel EMBEDDING_MODEL = new BgeSmallEnV15QuantizedEmbeddingModel();
|
||||
|
||||
private final EmbeddingStore<TextSegment> store = new InMemoryEmbeddingStore<>();
|
||||
private final IngestionResult ingestion;
|
||||
|
||||
private KnowledgeBase(String classpathDir) {
|
||||
List<Document> documents = ClassPathDocumentLoader.loadDocumentsRecursively(classpathDir);
|
||||
// The static ingest(documents, store) is the "Easy RAG" call: no splitter, no embedding model
|
||||
// configured here. It finds a splitter through a service-provider file in the easy-rag jar and an
|
||||
// embedding model through one in the bge-small jar.
|
||||
this.ingestion = EmbeddingStoreIngestor.ingest(documents, store);
|
||||
}
|
||||
|
||||
public static KnowledgeBase load(String classpathDir) {
|
||||
return new KnowledgeBase(classpathDir);
|
||||
}
|
||||
|
||||
public EmbeddingStore<TextSegment> store() {
|
||||
return store;
|
||||
}
|
||||
|
||||
public IngestionResult ingestion() {
|
||||
return ingestion;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.ankurm.lc4j.advancedrag;
|
||||
|
||||
import dev.langchain4j.data.segment.TextSegment;
|
||||
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
|
||||
import dev.langchain4j.model.chat.ChatModel;
|
||||
import dev.langchain4j.rag.DefaultRetrievalAugmentor;
|
||||
import dev.langchain4j.rag.RetrievalAugmentor;
|
||||
import dev.langchain4j.rag.content.injector.ContentInjector;
|
||||
import dev.langchain4j.rag.content.retriever.ContentRetriever;
|
||||
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
|
||||
import dev.langchain4j.rag.query.router.LanguageModelQueryRouter;
|
||||
import dev.langchain4j.rag.query.router.QueryRouter;
|
||||
import dev.langchain4j.rag.query.transformer.CompressingQueryTransformer;
|
||||
import dev.langchain4j.rag.query.transformer.ExpandingQueryTransformer;
|
||||
import dev.langchain4j.rag.query.transformer.QueryTransformer;
|
||||
import dev.langchain4j.service.AiServices;
|
||||
import dev.langchain4j.store.embedding.EmbeddingStore;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Small builders so each demo reads as "what is different from the previous one". */
|
||||
public final class Pipelines {
|
||||
|
||||
private Pipelines() {
|
||||
}
|
||||
|
||||
/** A retriever over one store. maxResults 3 and minScore 0 are the library defaults, made explicit. */
|
||||
public static ContentRetriever retriever(EmbeddingStore<TextSegment> store, int maxResults, double minScore) {
|
||||
return EmbeddingStoreContentRetriever.builder()
|
||||
.embeddingStore(store)
|
||||
.embeddingModel(KnowledgeBase.EMBEDDING_MODEL)
|
||||
.maxResults(maxResults)
|
||||
.minScore(minScore)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Naive RAG: the user's message, as typed, is the search query. */
|
||||
public static SupportAssistant naive(ChatModel answerModel, ContentRetriever retriever) {
|
||||
return AiServices.builder(SupportAssistant.class)
|
||||
.chatModel(answerModel)
|
||||
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
|
||||
.contentRetriever(retriever)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Advanced RAG: every stage of the pipeline is a plug-in point on the augmentor. */
|
||||
public static SupportAssistant advanced(ChatModel answerModel, RetrievalAugmentor augmentor) {
|
||||
return AiServices.builder(SupportAssistant.class)
|
||||
.chatModel(answerModel)
|
||||
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
|
||||
.retrievalAugmentor(augmentor)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as advanced(), but chat memory keeps the user's own message instead of the message with retrieved
|
||||
* text injected. The LLM still receives the augmented message for the current turn.
|
||||
*/
|
||||
public static SupportAssistant advancedLeanMemory(ChatModel answerModel, RetrievalAugmentor augmentor) {
|
||||
return AiServices.builder(SupportAssistant.class)
|
||||
.chatModel(answerModel)
|
||||
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
|
||||
.retrievalAugmentor(augmentor)
|
||||
.storeRetrievedContentInChatMemory(false)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Returning Result<String> is what makes the retrieved Content available as result.sources(). */
|
||||
public static SourcedAssistant sourced(ChatModel answerModel, ContentRetriever retriever) {
|
||||
return AiServices.builder(SourcedAssistant.class)
|
||||
.chatModel(answerModel)
|
||||
.contentRetriever(retriever)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static RetrievalAugmentor compressing(ChatModel rewriter, ContentRetriever retriever) {
|
||||
return DefaultRetrievalAugmentor.builder()
|
||||
.queryTransformer(new CompressingQueryTransformer(rewriter))
|
||||
.contentRetriever(retriever)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static RetrievalAugmentor expanding(ChatModel expander, int n, ContentRetriever retriever) {
|
||||
return DefaultRetrievalAugmentor.builder()
|
||||
.queryTransformer(new ExpandingQueryTransformer(expander, n))
|
||||
.contentRetriever(retriever)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Numbering in the router prompt follows map iteration order, so the map must be ordered. */
|
||||
public static QueryRouter router(ChatModel routerModel, ContentRetriever support, ContentRetriever engineering) {
|
||||
Map<ContentRetriever, String> options = new LinkedHashMap<>();
|
||||
options.put(support, "Billing, refunds, hardware returns and account security for customers");
|
||||
options.put(engineering, "API rate limits, deployments and webhooks for developers");
|
||||
return LanguageModelQueryRouter.builder()
|
||||
.chatModel(routerModel)
|
||||
.retrieverToDescription(options)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static RetrievalAugmentor full(QueryTransformer transformer, QueryRouter router, ContentInjector injector) {
|
||||
return DefaultRetrievalAugmentor.builder()
|
||||
.queryTransformer(transformer)
|
||||
.queryRouter(router)
|
||||
.contentInjector(injector)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.lc4j.advancedrag;
|
||||
|
||||
import dev.langchain4j.data.message.AiMessage;
|
||||
import dev.langchain4j.data.message.ChatMessage;
|
||||
import dev.langchain4j.model.chat.ChatModel;
|
||||
import dev.langchain4j.model.chat.request.ChatRequest;
|
||||
import dev.langchain4j.model.chat.response.ChatResponse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A deterministic stand-in for a real LLM. It lets every example run offline and lets the
|
||||
* tests assert exactly which messages LangChain4j sent, which is the thing worth looking at.
|
||||
* Swap it for OpenAiChatModel (or any other ChatModel) and the AI Service code does not change.
|
||||
*/
|
||||
public class ScriptedChatModel implements ChatModel {
|
||||
|
||||
private final Function<ChatRequest, AiMessage> script;
|
||||
private final List<ChatRequest> requests = new ArrayList<>();
|
||||
|
||||
public ScriptedChatModel(Function<ChatRequest, AiMessage> script) {
|
||||
this.script = script;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatResponse doChat(ChatRequest request) {
|
||||
requests.add(request);
|
||||
return ChatResponse.builder().aiMessage(script.apply(request)).build();
|
||||
}
|
||||
|
||||
/** Every request this model has received, oldest first. */
|
||||
public List<ChatRequest> requests() {
|
||||
return requests;
|
||||
}
|
||||
|
||||
public ChatRequest lastRequest() {
|
||||
return requests.get(requests.size() - 1);
|
||||
}
|
||||
|
||||
/** Renders the messages of a request as one line per message, for transcripts. */
|
||||
public static String render(List<ChatMessage> messages) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (ChatMessage m : messages) {
|
||||
sb.append(m.type()).append(": ").append(text(m)).append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String text(ChatMessage m) {
|
||||
return switch (m) {
|
||||
case dev.langchain4j.data.message.SystemMessage s -> s.text();
|
||||
case dev.langchain4j.data.message.UserMessage u -> u.singleText();
|
||||
case AiMessage a -> a.hasToolExecutionRequests()
|
||||
? "tool calls " + a.toolExecutionRequests().stream()
|
||||
.map(r -> r.name() + r.arguments()).toList()
|
||||
: a.text();
|
||||
case dev.langchain4j.data.message.ToolExecutionResultMessage t -> t.text();
|
||||
default -> m.toString();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.ankurm.lc4j.advancedrag;
|
||||
|
||||
import dev.langchain4j.service.Result;
|
||||
|
||||
/** Wrapping the return type in Result tells AI Services to hand back the retrieved sources with the answer. */
|
||||
public interface SourcedAssistant {
|
||||
Result<String> chat(String message);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.ankurm.lc4j.advancedrag;
|
||||
|
||||
/** The AI Service the demos talk to. RAG is attached when it is built, not declared here. */
|
||||
public interface SupportAssistant {
|
||||
String chat(String message);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Cloud Deployments
|
||||
|
||||
A standard deployment takes about 4 minutes from push to live. The first 5 percent of traffic goes to the new version as a canary for 2 minutes before the rest is shifted.
|
||||
|
||||
A rollback takes about 30 seconds because the previous version stays warm for one hour after every deployment. After that hour, a rollback is a normal 4 minute deployment of the older build.
|
||||
|
||||
Deployments are blocked automatically when the error rate of the canary is more than 2 percent above the baseline.
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Cloud API Rate Limits
|
||||
|
||||
Every API key is limited to 600 requests per minute, with a burst allowance of 100 requests per second. Requests over the limit receive HTTP 429 with a Retry-After header giving the number of seconds to wait.
|
||||
|
||||
Limits are per key, not per organisation, so a noisy integration cannot starve the others. Batch endpoints count as one request regardless of how many items they contain.
|
||||
|
||||
To raise a limit, open a ticket with the key id and the peak traffic you expect. Increases are applied within one business day.
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Cloud Webhooks
|
||||
|
||||
Every webhook delivery is signed. The signature is sent in the X-Acme-Signature header and is an HMAC-SHA256 of the raw request body using your endpoint secret. Reject any delivery whose signature does not match.
|
||||
|
||||
If your endpoint does not answer with a 2xx status within 10 seconds, the delivery is retried up to 8 times with exponential backoff. The retries are spread over 24 hours. After the last failed attempt the endpoint is marked as failing and an email is sent to the organisation owner.
|
||||
|
||||
Deliveries can arrive more than once and out of order, so handlers must be idempotent. Use the event id to deduplicate.
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Cloud Account Security
|
||||
|
||||
Password reset links expire after 30 minutes and can be used only once. If a link has expired, request a new one from the sign-in page.
|
||||
|
||||
Two-factor authentication is mandatory for organisation owners. Supported methods are authenticator apps and hardware security keys. SMS codes are not supported.
|
||||
|
||||
SSO via SAML 2.0 is available on the Business plan. After SSO is enforced, password sign-in is disabled for every member except the organisation owner, who keeps a break-glass login.
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Edge Box Hardware Returns
|
||||
|
||||
The Acme Edge Box can be returned within 45 days of delivery if it is in its original packaging. Request a return label from the support portal; the label is valid for 14 days.
|
||||
|
||||
After our warehouse receives the box, the refund is processed within 3 business days. It then follows the normal card timeline of 5 to 10 business days.
|
||||
|
||||
Boxes that arrive damaged or with missing power adapters are inspected first, which can add up to 5 business days.
|
||||
@@ -0,0 +1,7 @@
|
||||
Acme Cloud Refund Policy
|
||||
|
||||
Annual plans can be refunded in full within 30 days of purchase. Monthly plans can be refunded within 7 days of the first charge. After those windows, no refund is issued, but you can cancel at any time and keep access until the end of the paid period.
|
||||
|
||||
Once a refund is approved, it takes 5 to 10 business days to appear on your card statement. The time depends on your bank, not on Acme Cloud. Refunds always go back to the original payment method; we cannot pay them out to a different card.
|
||||
|
||||
If a refund does not show up after 10 business days, contact support with the invoice number so we can send you the acquirer reference number.
|
||||
Reference in New Issue
Block a user