langchain4j 学习系列(8)-链式调用
接上节继续,langchain4j的名字中既然有个chain,自然要体现出链式调用的特性。根据官网的介绍,目前langchain4j内置了2个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() + "\"}");
}
}
与ConversationalChain相比,ConversationalRetrievalChain新增了RAG的链式处理。
文本示例完整代码:https://github.com/yjmyzz/langchain4j-study/tree/day08
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
浙公网安备 33010602011771号