LangChain4j如何自定義文檔轉(zhuǎn)換器實(shí)現(xiàn)數(shù)據(jù)清洗?
LangChain4j 提供了 3 種 RAG(Retrieval-Augmented Generation,檢索增強(qiáng)生成)實(shí)現(xiàn),我們通常在原生或高級的 RAG 實(shí)現(xiàn)中,要對數(shù)據(jù)進(jìn)行清洗,也就是將外接知識(shí)庫中的原數(shù)據(jù)進(jìn)行噪音去除,留下有價(jià)值的信息。
例如在帶有 HTML 標(biāo)簽的文本中,HTML 標(biāo)簽就是噪音,他對于搜索結(jié)果是沒有任何幫助,甚至?xí)绊懖樵兘Y(jié)果的,因此我們就需要將 HTML 標(biāo)簽進(jìn)行清除。
那問題來了,怎么進(jìn)行數(shù)據(jù)清洗呢?
這就要使用到文檔轉(zhuǎn)換器了,那么在不使用 LangChain4j 內(nèi)置文檔轉(zhuǎn)換器的前提下(因?yàn)闃I(yè)務(wù)需求是復(fù)雜且多變的,因此很多時(shí)候我們需要使用自定義文檔轉(zhuǎn)換器才能實(shí)現(xiàn)預(yù)期的效果),那怎么實(shí)現(xiàn)呢?接下來一起來看。
自定義文檔轉(zhuǎn)換器
以去除文本中的 HTML 標(biāo)簽為例,LangChain4j 中自定義文檔轉(zhuǎn)換器的實(shí)現(xiàn)步驟如下:
- 新建類實(shí)現(xiàn) DocumentTransformer 接口。
- 重寫 transform 和 transformAll 方法,前者是對 Document 對象進(jìn)行文檔轉(zhuǎn)換,后者是對 List進(jìn)行數(shù)據(jù)轉(zhuǎn)換。
- 在 transform 和 transformAll 方法中,實(shí)現(xiàn)數(shù)據(jù)清除的具體業(yè)務(wù)落地。
具體實(shí)現(xiàn)代碼
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentTransformer;
import java.util.ArrayList;
import java.util.List;
/**
* 自定義文檔轉(zhuǎn)換器
*/
public class HtmlToTextDocumentTransformer implements DocumentTransformer {
@Override
public Document transform(Document document) {
return Document.from(removeHtmlTags(document.text()));
}
// 使用正則表達(dá)式清除內(nèi)容中的 HTML 標(biāo)簽
public static String removeHtmlTags(String html) {
if (html == null || html.isEmpty()) {
return "";
}
// 定義正則表達(dá)式,匹配所有HTML標(biāo)簽
String regex = "<[^>]+>";
// 替換所有匹配的標(biāo)簽為空字符串
return html.replaceAll(regex, "").trim();
}
@Override
public List<Document> transformAll(List<Document> documents) {
List<Document> list = new ArrayList<Document>();
documents.stream().forEach(document -> {
list.add(this.transform(document));
});
return list;
}
}
調(diào)用文檔轉(zhuǎn)換器
Document htmlDoc = Document.from(
"<html><body><p>Clean <b>me</b>!</p></body></html>"
);
// 文檔轉(zhuǎn)換器
DocumentTransformer transformer = new HtmlToTextDocumentTransformer();
Document cleanedDoc = transformer.transform(htmlDoc);
System.out.println(cleanedDoc.text());
最終的執(zhí)行結(jié)果為:
Clean me!
小結(jié)
文檔轉(zhuǎn)換器只是實(shí)現(xiàn)生產(chǎn)級別 RAG 的實(shí)現(xiàn)步驟之一,生產(chǎn)級別的 RAG 實(shí)現(xiàn)的步驟通常包含:文檔加載器、文檔解析器、文檔轉(zhuǎn)換器、文檔分詞器、文檔向量化、向量持久化、向量檢索等過程,而且每個(gè)過程可能都要反復(fù)調(diào)優(yōu),才能實(shí)現(xiàn)生產(chǎn)級別的準(zhǔn)確性要求,所以道阻且長,吾輩尚需努力??!