SemanticSlicer
v1.4.0
SemanticSlicer 是一個 C# 函式庫,用於將文字資料分割成更小的片段,同時嘗試在有意義的邊界上打破文字。
GitHub:https://github.com/drittich/SemanticSlicer
該庫接受文字並將其分解為更小的區塊,通常在創建 LLM AI 嵌入時有用。
套件名稱是drittich.SemanticSlicer
。您可以透過命令列從 Nuget 安裝它:
dotnet add package drittich.SemanticSlicer
或從套件管理器控制台:
NuGetInstall-Package drittich.SemanticSlicer
簡單的文字文件:
// The default options uses text separators, a max chunk size of 1,000, and
// cl100k_base encoding to count tokens.
var slicer = new Slicer ( ) ;
var text = File . ReadAllText ( " MyDocument.txt " ) ;
var documentChunks = slicer . GetDocumentChunks ( text ) ;
降價文檔:
// Let's use Markdown separators and reduce the chunk size
var options = new SlicerOptions { MaxChunkTokenCount = 600 , Separators = Separators . Markdown } ;
var slicer = new Slicer ( options ) ;
var text = File . ReadAllText ( " MyDocument.md " ) ;
var documentChunks = slicer . GetDocumentChunks ( text ) ;
HTML 文件:
var options = new SlicerOptions { Separators = Separators . Html } ;
var slicer = new Slicer ( options ) ;
var text = File . ReadAllText ( " MyDocument.html " ) ;
var documentChunks = slicer . GetDocumentChunks ( text ) ;
刪除 HTML 標籤:
對於任何內容,您都可以選擇從區塊中刪除 HTML 標籤,以最大限度地減少標記數量。內部文字被保留,如果有<Title>
標籤,標題將被添加到結果之前:
// Let's remove the HTML tags as they just consume a lot of tokens without adding much value
var options = new SlicerOptions { Separators = Separators . Html , StripHtml = true } ;
var slicer = new Slicer ( options ) ;
var text = File . ReadAllText ( " MyDocument.html " ) ;
var documentChunks = slicer . GetDocumentChunks ( text ) ;
自訂分隔符號:
如果您願意,您可以傳入自己的分隔符號列表,例如,如果您希望新增對其他文件的支援。
區塊將按照它們在文件中找到的順序返回,並包含一個 Index 屬性,您可以在必要時使用它來將它們按順序放回原處。
您可以將任何您想要的附加元資料作為字典傳遞,它將隨每個文件區塊返回,因此很容易保留。您可以使用元資料來儲存文件 ID、標題或上次修改日期。
var slicer = new Slicer ( ) ;
var text = File . ReadAllText ( " MyDocument.txt " ) ;
var metadata = new Dictionary < string , object ? > ( ) ;
metadata [ " Id " ] = 123 ;
metadata [ " FileName " ] = " MyDocument.txt " ;
var documentChunks = slicer . GetDocumentChunks ( text , metadata ) ;
// All chunks returned will have a Metadata property with the data you passed in.
如果您願意,可以傳遞一個標頭以包含在每個區塊的頂部。範例用例包括將文件標題或標籤作為區塊內容的一部分,以幫助維護上下文。
var slicer = new Slicer ( ) ;
var fileName = " MyDocument.txt " ;
var text = File . ReadAllText ( fileName ) ;
var header = $" FileName: { fileName } " ;
var documentChunks = slicer . GetDocumentChunks ( text , null , header ) ;
該項目根據 MIT 許可證獲得許可 - 有關詳細信息,請參閱許可證文件。
如果您有任何問題或回饋,請在此儲存庫上提出問題。