코드 분할
이 장에서는 LangChain의 코드 텍스트 분할기를 소개합니다. 코드를 코드 조각으로 분할해야 하는 경우 이 장의 내용을 주의 깊게 공부해야 합니다. CodeTextSplitter는 여러 프로그래밍 언어에 대한 코드 분할을 지원합니다.
종속성 설치
%pip install -qU langchain-text-splitters
다음으로 "Language" 열거형을 가져와 코드 분할을 지원하는 프로그래밍 언어가 무엇인지 확인합니다.
from langchain_text_splitters import (
Language,
RecursiveCharacterTextSplitter,
)
[e.value for e in Language]
['cpp',
'go',
'java',
'js',
'php',
'proto',
'python',
'rst',
'ruby',
'rust',
'scala',
'swift',
'markdown',
'latex',
'html',
'sol',]
RecursiveCharacterTextSplitter.get_separators_for_language(Language.PYTHON)
['\\nclass ', '\\ndef ', '\\n\\tdef ', '\\n\\n', '\\n', ' ', '']
Python
PythonTextSplitter를 사용하여 코드를 분할하는 예제입니다.
PYTHON_CODE = """
def hello_world():
print("Hello, World!")
hello_world()
"""
python_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.PYTHON, chunk_size=50, chunk_overlap=0
)
python_docs = python_splitter.create_documents([PYTHON_CODE])
python_docs
[Document(page_content='def hello_world():\\\\n print("Hello, World!")', metadata={}), Document(page_content='# 함수 호출\\\\nhello_world()', metadata={})]
JS
JS 텍스트 분할기를 사용하여 JS 코드를 분할하는 예제입니다.
JS_CODE = """
function helloWorld() {
console.log("Hello, World!");
}
// 함수 호출
helloWorld();
"""
js_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.JS, chunk_size=60, chunk_overlap=0
)
js_docs = js_splitter.create_documents([JS_CODE])
js_docs
[Document(page_content='function helloWorld() {\n console.log("Hello, World!");\n}', metadata={}),
Document(page_content='// 함수 호출\nhelloWorld();', metadata={})]
Markdown
Markdown 코드를 분할하는 예제입니다.
markdown_text = """
⚡ LLMs를 통한 조립 가능한 애플리케이션 빌드 ⚡
\`\`\`bash
pip install langchain
\`\`\`
빠르게 발전하는 분야의 오픈 소스 프로젝트로, 기여에 대해 매우 열려 있습니다.
"""
md_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.MARKDOWN, chunk_size=60, chunk_overlap=0
)
md_docs = md_splitter.create_documents([markdown_text])
md_docs
[Document(page_content='# ?️? LangChain', metadata={}),
Document(page_content='⚡ LLMs를 통한 조립 가능한 애플리케이션 빌드 ⚡', metadata={}),
Document(page_content='## 빠른 설치', metadata={}),
Document(page_content="```bash\n# 이 코드 블록은 더 이상 분할되지 않았으면 좋겠습니다", metadata={}),
Document(page_content='pip install langchain', metadata={}),
Document(page_content='```', metadata={}),
Document(page_content='빠르게 발전하는 분야의 오픈 소스 프로젝트로,', metadata={}),
Document(page_content='기여에 대해 매우 열려 있습니다.', metadata={})]
라텍스 텍스트 분할 예
latex_text = """ \documentclass{article}
\begin{document}
\maketitle
\section{Introduction} 대형 언어 모델(Large Language Models, LLMs)은 방대한 양의 텍스트 데이터로 훈련될 수 있는 기계 학습 모델로, 인간과 유사한 언어를 생성할 수 있습니다. 최근 몇 년간 LLMs는 언어 번역, 텍스트 생성, 감성 분석 등 다양한 자연 언어 처리 작업에서 큰 발전을 이루었습니다.
\subsection{LLMs의 역사} 가장 초기의 LLMs는 1980년대와 1990년대에 개발되었지만, 당시에 처리할 수 있는 데이터 양과 사용 가능한 컴퓨팅 파워에 제한을 받았습니다. 그러나 지난 10년 동안 하드웨어와 소프트웨어의 발전으로 대규모 데이터셋으로 LLMs를 훈련할 수 있게 되었으며, 이로 인해 성능이 크게 향상되었습니다.
\subsection{LLMs의 응용} LLMs는 챗봇, 콘텐츠 생성, 가상 비서 등을 포함한 다양한 산업 분야에서 응용될 수 있습니다. 또한 언어학, 심리학, 계산 언어학 등의 연구를 위해 학계에서도 활용될 수 있습니다.
\end{document} """
latex_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.MARKDOWN, chunk_size=60, chunk_overlap=0 ) latex_docs = latex_splitter.create_documents([latex_text]) latex_docs
[Document(page_content='\documentclass{article}\n\n\x08egin{document}\n\n\maketitle', metadata={}), Document(page_content='\section{Introduction}', metadata={}), Document(page_content='Large language models (LLMs) are a type of machine learning', metadata={}), Document(page_content='model that can be trained on vast amounts of text data to', metadata={}), Document(page_content='generate human-like language. In recent years, LLMs have', metadata={}), Document(page_content='made significant advances in a variety of natural language', metadata={}), Document(page_content='processing tasks, including language translation, text', metadata={}), Document(page_content='generation, and sentiment analysis.', metadata={}), Document(page_content='\subsection{History of LLMs}', metadata={}), Document(page_content='The earliest LLMs were developed in the 1980s and 1990s,', metadata={}), Document(page_content='but they were limited by the amount of data that could be', metadata={}), Document(page_content='processed and the computational power available at the', metadata={}), Document(page_content='time. In the past decade, however, advances in hardware and', metadata={}), Document(page_content='software have made it possible to train LLMs on massive', metadata={}), Document(page_content='datasets, leading to significant improvements in', metadata={}), Document(page_content='performance.', metadata={}), Document(page_content='\subsection{Applications of LLMs}', metadata={}), Document(page_content='LLMs have many applications in industry, including', metadata={}), Document(page_content='chatbots, content creation, and virtual assistants. They', metadata={}), Document(page_content='can also be used in academia for research in linguistics,', metadata={}), Document(page_content='psychology, and computational linguistics.', metadata={}), Document(page_content='\end{document}', metadata={})]
```html
html_text = """
<!DOCTYPE html>
<html>
<head>
<title>🌐 LangChain</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: darkblue;
}
</style>
</head>
<body>
<div>
<h1>🌐 LangChain</h1>
<p>⚡ LLM을 통해 조립 가능한 애플리케이션 구축 ⚡</p>
</div>
<div>
빠르게 발전하는 분야의 오픈 소스 프로젝트로, 기여에 대해 매우 열려 있습니다.
</div>
</body>
</html>
"""
html_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.HTML, chunk_size=60, chunk_overlap=0
)
html_docs = html_splitter.create_documents([html_text])
html_docs
[Document(page_content='<!DOCTYPE html>\n<html>', metadata={}),
Document(page_content='<head>\n <title>🌐 LangChain</title>', metadata={}),
Document(page_content='<style>\n body {\n font-family: Arial', metadata={}),
Document(page_content=', sans-serif;\n }\n h1 {', metadata={}),
Document(page_content='color: darkblue;\n }\n </style>\n </head', metadata={}),
Document(page_content='>', metadata={}),
Document(page_content='<body>', metadata={}),
Document(page_content='<div>\n <h1>🌐 LangChain</h1>', metadata={}),
Document(page_content='<p>⚡ LLM을 통해 조립 가능한 애플리케이션 구축 ⚡', metadata={}),
Document(page_content='</p>\n </div>', metadata={}),
Document(page_content='<div>\n 빠르게 발전하는 분야의 오픈 소스 프로젝트로, 기여에 대해 매우 열려 있습니', metadata={}),
Document(page_content='니다.', metadata={}),
Document(page_content='</div>\n </body>\n</html>', metadata={})]
Solidity
SOL_CODE = """
pragma solidity ^0.8.20;
contract HelloWorld {
function add(uint a, uint b) pure public returns(uint) {
return a + b;
}
}
"""
sol_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.SOL, chunk_size=128, chunk_overlap=0
)
sol_docs = sol_splitter.create_documents([SOL_CODE])
sol_docs