텍스트 분할기와 임베딩
대규모 문서를 관리하기 쉬운 덩어리로 나누고 의미 검색을 위한 수치 임베딩을 생성하는 기법을 익힙니다.
텍스트 분할기와 임베딩은(는) CoddyKit의 무료 AI Agents with LangChain & Autonomous Workflows 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents with LangChain & Autonomous Workflows 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Split & Embed Text?
When working with large documents, directly feeding them to a Large Language Model (LLM) often causes problems. LLMs have strict input limits, known as context windows.
This lesson teaches you how to prepare large texts for LLMs using two key techniques: text splitting and embeddings. These are essential for building advanced AI agents.
The Problem: Long Documents
Imagine you have a 100-page PDF document. If you try to ask an LLM a question about it, you can't just send the whole document.
- Context Window Limits: LLMs can only process a certain amount of text at once (e.g., 4,000 to 128,000 tokens).
- Cost: Longer inputs mean higher API costs.
- Relevance: Filling the context window with irrelevant information can make the LLM 'forget' the important parts.
Text splitting solves this by breaking documents into smaller, manageable chunks.
Introducing Text Splitters
LangChain provides various text splitters to divide documents efficiently. Their goal is to keep semantically related pieces of text together while respecting size limits.
Instead of just cutting at arbitrary character counts, smart splitters try to break text at logical points, like paragraphs or sentences.
A common and versatile splitter is the RecursiveCharacterTextSplitter.
Recursive Character Text Splitter
The RecursiveCharacterTextSplitter is a powerful tool. It attempts to split text using a list of characters, trying them in order until the chunks are small enough.
- It starts by trying to split by
\n\n(double newline for paragraphs). - If chunks are still too big, it tries
\n(single newline for lines). - Then spaces, and finally individual characters.
This recursive approach helps maintain semantic coherence.
Code: Basic Splitting Demo
Let's see how RecursiveCharacterTextSplitter works. We'll split a short story into chunks.
from langchain_text_splitters import RecursiveCharacterTextSplitter
story = (
"Alice was beginning to get very tired of sitting by her sister on the bank, "
"and of having nothing to do: once or twice she had peeped into the book her "
"sister was reading, but it had no pictures or conversations in it, 'and what "
"is the use of a book,' thought Alice 'without pictures or conversation?'"
"So she was considering in her own mind (as well as she could, for the hot "
"day made her feel very sleepy and stupid), whether the pleasure of making "
"a daisy-chain would be worth the trouble of getting up and picking the "
"daisies, when suddenly a White Rabbit with pink eyes ran close by her."
)
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=100,
chunk_overlap=0
)
chunks = text_splitter.split_text(story)
for i, chunk in enumerate(chunks):
print(f"Chunk {i+1}: {chunk}\n")Chunk Size & Overlap Explained
Two crucial parameters for text splitting are chunk_size and chunk_overlap:
- Chunk Size: This is the maximum number of characters (or tokens, depending on the splitter) in each chunk. Choose a size that fits within your LLM's context window.
- Chunk Overlap: This specifies how many characters (or tokens) should overlap between consecutive chunks. Overlap helps preserve context across splits, ensuring that important information isn't lost at chunk boundaries.
Finding the right balance for these parameters is key to effective retrieval.
Code: Splitting with Overlap
Let's modify our previous example to use a chunk_overlap. Notice how parts of the text are repeated in adjacent chunks, providing continuity.
from langchain_text_splitters import RecursiveCharacterTextSplitter
story = (
"Alice was beginning to get very tired of sitting by her sister on the bank, "
"and of having nothing to do: once or twice she had peeped into the book her "
"sister was reading, but it had no pictures or conversations in it, 'and what "
"is the use of a book,' thought Alice 'without pictures or conversation?'"
"So she was considering in her own mind (as well as she could, for the hot "
"day made her feel very sleepy and stupid), whether the pleasure of making "
"a daisy-chain would be worth the trouble of getting up and picking the "
"daisies, when suddenly a White Rabbit with pink eyes ran close by her."
)
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=100,
chunk_overlap=20 # Added overlap
)
chunks = text_splitter.split_text(story)
for i, chunk in enumerate(chunks):
print(f"Chunk {i+1}: {chunk}\n")What are Text Embeddings?
Once you've split your documents, how do you find the most relevant chunks for a user's query? This is where text embeddings come in.
- An embedding is a numerical representation (a vector) of text.
- Texts with similar meanings have embeddings that are 'closer' to each other in a high-dimensional space.
- This allows us to perform semantic search: finding chunks that are conceptually similar to a query, not just keyword matches.
Embeddings are the backbone of Retrieval Augmented Generation (RAG).
Generating Embeddings with LangChain
LangChain makes it easy to generate embeddings using various models. You interact with an Embeddings object, which abstracts away the underlying model details.
Popular embedding models include those from OpenAI, Hugging Face, Cohere, and many open-source options like `all-MiniLM-L6-v2`.
You typically initialize an embedding model and then call its embed_query() for a single text or embed_documents() for a list of chunks.
Code: Creating Embeddings
Here's how to generate an embedding for a simple text using OpenAI's embedding model. Remember, you'll need an OpenAI API key for this to run successfully.
import os
# Set your OpenAI API key as an environment variable
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
from langchain_openai import OpenAIEmbeddings
# Initialize the embedding model
# Requires OPENAI_API_KEY env var or direct pass
embeddings_model = OpenAIEmbeddings()
text_to_embed = "The quick brown fox jumps over the lazy dog."
# Generate the embedding vector
embedding_vector = embeddings_model.embed_query(text_to_embed)
print(f"Original Text: '{text_to_embed}'")
print(f"Embedding Vector (first 5 values): {embedding_vector[:5]}...")
print(f"Vector Dimension: {len(embedding_vector)}")Quick Check: Splitting & Embeddings
Consider the following statements about text splitting and embeddings:
Recap: Splitting & Embedding for RAG
You've learned two fundamental techniques for handling large documents in AI agents:
- Text Splitting: Breaking large texts into smaller, manageable chunks using tools like
RecursiveCharacterTextSplitter, controlled bychunk_sizeandchunk_overlap. - Embeddings: Converting text chunks into numerical vectors using embedding models (e.g.,
OpenAIEmbeddings) to enable semantic similarity search.
These techniques are crucial for building effective Retrieval Augmented Generation (RAG) systems, allowing your agents to intelligently find and use relevant information from vast knowledge bases.
자주 묻는 질문
“텍스트 분할기와 임베딩” 강의는 무료인가요?
네 — “텍스트 분할기와 임베딩” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents with LangChain & Autonomous Workflows 강의 전체를 잠금 해제할 수 있습니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
“텍스트 분할기와 임베딩”에서 뭘 배우나요?
대규모 문서를 관리하기 쉬운 덩어리로 나누고 의미 검색을 위한 수치 임베딩을 생성하는 기법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents with LangChain & Autonomous Workflows을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents with LangChain & Autonomous Workflows을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents with LangChain & Autonomous Workflows은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“텍스트 분할기와 임베딩” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents with LangChain & Autonomous Workflows 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents with LangChain & Autonomous Workflows 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 문서 로더 해설
- 텍스트 분할기와 임베딩
- 검색을 위한 벡터 저장소
- 검색기 및 맥락 압축