ConversationalChain 把模型和对话记忆组合起来,ConversationalRetrievalChain 在此基础上加入检索。两者都是旧版 API,使用前请核对项目依赖。

LangChain4j 文档列出的两种旧版 Chain。
ConversationalChain示例
@GetMapping(value = "/chat/chain", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> chatChain(@RequestParam String query) {
try {
String responseText = ConversationalChain.builder()
.chatModel(ollamaChatModel)
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.build()
.execute(query);
return ResponseEntity.ok(responseText);
} catch (Exception e) {
log.error("chatChain", e);
return ResponseEntity.ok("{\"error\":\"chatChain error: " + e.getMessage() + "\"}");
}
}
这段链式调用把模型配置、对话记忆和查询执行组织在一起。
ConversationalRetrievalChain示例
/**
* 示例用测试文本data.txt向量化存储(按行分隔)
* @return
*/
EmbeddingStore<TextSegment> getEmbeddingStore() {
Resource resource = resourceLoader.getResource("classpath:data.txt");
File file = null;
try {
file = resource.getFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
String path = file.getAbsolutePath();
EmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
Document document = FileSystemDocumentLoader.loadDocument(path);
DocumentByLineSplitter splitter = new DocumentByLineSplitter(100, 0);
List<TextSegment> split = splitter.split(document);
for (TextSegment textSegment : split) {
Embedding embedding = ollamaEmbeddingModel.embed(textSegment).content();
embeddingStore.add(embedding, textSegment);
}
return embeddingStore;
}
@GetMapping(value = "/rag/chain", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> ragChain(@RequestParam String query) {
try {
String answer = ConversationalRetrievalChain.builder()
.chatModel(ollamaChatModel)
.contentRetriever(EmbeddingStoreContentRetriever
.builder()
.embeddingModel(ollamaEmbeddingModel)
.embeddingStore(getEmbeddingStore())
.maxResults(1)
.build())
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.build()
.execute(query);
return ResponseEntity.ok(answer);
} catch (Exception e) {
log.error("argChain", e);
return ResponseEntity.ok("{\"error\":\"argChain error: " + e.getMessage() + "\"}");
}
}
检索链把查到的内容和对话上下文一起交给模型,用于生成回答。