開始使用免費開始

以字元分割

在實作 Retrieval Augmented Generation(RAG)時,一個關鍵步驟是把文件切成多個區塊,並儲存到向量資料庫中。

LangChain 提供多種分割策略,有些流程較為複雜。本練習中,你將實作一個「字元文字分割器」(character text splitter),它會依字元來分割文件,並以字元數量來衡量區塊長度。

請記住,沒有放諸四海皆準的分割策略。你可能需要多嘗試幾種,才能找到最適合你的情境的做法。

本練習屬於課程

使用 LangChain 開發 LLM 應用

檢視課程

練習說明

  • langchain_text_splitters 匯入 CharacterTextSplitter 類別。
  • separator="\n"chunk_size=24chunk_overlap=10 建立一個 CharacterTextSplitter 實例。
  • 使用 .split_text() 方法分割 quote,並印出各區塊及其長度。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import the character splitter
from langchain_text_splitters import ____

quote = 'Words are flowing out like endless rain into a paper cup,\nthey slither while they pass,\nthey slip away across the universe.'
chunk_size = 24
chunk_overlap = 10

# Create an instance of the splitter class
splitter = CharacterTextSplitter(
    separator=____,
    chunk_size=____,
    chunk_overlap=____)

# Split the string and print the chunks
docs = splitter.____(quote)
print(docs)
print([len(doc) for doc in docs])
編輯並執行程式碼