การแบ่งข้อความตามอักขระ
กระบวนการสำคัญอย่างหนึ่งในการใช้งาน Retrieval Augmented Generation (RAG) คือการแบ่งเอกสารออกเป็น chunk เพื่อจัดเก็บในฐานข้อมูลเวกเตอร์
LangChain มีกลยุทธ์การแบ่งข้อความให้เลือกใช้หลายแบบ บางแบบมีกระบวนการที่ซับซ้อนกว่าแบบอื่น ในแบบฝึกหัดนี้ จะได้ลองใช้ character text splitter ซึ่งแบ่งเอกสารตามอักขระและวัดความยาวของแต่ละ chunk จากจำนวนอักขระ
ไม่มีกลยุทธ์การแบ่งข้อความที่ดีที่สุดสำหรับทุกกรณี อาจต้องลองหลายแบบเพื่อหาวิธีที่เหมาะกับการใช้งานของคุณ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain
คำแนะนำการฝึกหัด
- Import คลาส
CharacterTextSplitterจากlangchain_text_splitters - สร้าง instance ของ
CharacterTextSplitterโดยกำหนดseparator="\n",chunk_size=24, และchunk_overlap=10 - ใช้เมธอด
.split_text()เพื่อแบ่งquoteจากนั้นแสดงผล chunk และความยาวของแต่ละ chunk
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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])