import re
# from langchain_text_splitters import RecursiveCharacterTextSplitter
# LangChainがインストールされていない環境でも動くように、シンプルなスプリッターを仮実装
class SimpleRecursiveCharacterTextSplitter:
def __init__(self, chunk_size, chunk_overlap, length_function):
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.length_function = length_function
def split_text(self, text: str) -> list[str]:
if self.length_function(text) <= self.chunk_size:
return [text]
chunks = []
start = 0
while start < len(text):
end = start + self.chunk_size
chunks.append(text[start:end])
start += self.chunk_size - self.chunk_overlap
return chunks
# --- 設定 ---
MAX_TOKENS = 200
# トークン計算用の関数
def count_tokens(text):
return len(text)
# フォールバック用のスプリッター
fallback_splitter = SimpleRecursiveCharacterTextSplitter(
chunk_size=MAX_TOKENS,
chunk_overlap=50,
length_function=count_tokens
)
# --- 1. マークダウン解析と木構造構築 (parentリンクを追加) ---
def parse_markdown_to_tree(markdown_text):
lines = markdown_text.split('\n')
# ノードに 'parent' を追加
root = {'header': None, 'level': 0, 'content': '', 'children': [], 'full_text': '', 'parent': None}
stack = [root]
header_pattern = re.compile(r'^(#+)\s+(.*)')
current_content = []
for line in lines:
match = header_pattern.match(line)
if match:
stack[-1]['content'] = '\n'.join(current_content).strip()
current_content = []
level = len(match.group(1))
header_text = line
# new_node に parent への参照を持たせる
new_node = {'header': header_text, 'level': level, 'content': '', 'children': [], 'full_text': '',
'parent': stack[-1]}
while stack[-1]['level'] >= level:
stack.pop()
stack[-1]['children'].append(new_node)
stack.append(new_node)
else:
current_content.append(line)
if current_content:
stack[-1]['content'] = '\n'.join(current_content).strip()
return root
def build_full_text_recursively(node):
for child in node['children']:
build_full_text_recursively(child)
children_full_text = "\n\n".join(child['full_text'] for child in node['children']).strip()
node_parts = []
if node['header']:
node_parts.append(node['header'])
if node['content']:
node_parts.append(node['content'])
if children_full_text:
node_parts.append(children_full_text)
node['full_text'] = "\n\n".join(node_parts).strip()
# --- 2. 新しいチャンキングとフォーマット関数 ---
def chunk_recursively_with_context(node, final_chunk_infos):
"""
元のロジックを維持しつつ、各チャンクにコンテキスト(元のノード)を付与する。
結果は final_chunk_infos に追加される。
"""
# このノード全体が上限以下なら、丸ごと1つのチャンクとする
if count_tokens(node['full_text']) <= MAX_TOKENS:
if node['full_text']: # 空のテキストは追加しない
final_chunk_infos.append({'text': node['full_text'], 'node': node})
return
# ノード全体が大きすぎる場合、作業用のチャンクリストを作成
current_chunk_infos = []
# このノード自身のテキスト(ヘッダー+コンテンツ)を生成
node_own_text = ""
if node['header']:
node_own_text += node['header']
if node['content']:
node_own_text += "\n\n" + node['content']
node_own_text = node_own_text.strip()
if node_own_text:
# このノード自身のテキストですら大きすぎる場合は、フォールバック分割
if count_tokens(node_own_text) > MAX_TOKENS:
split_texts = fallback_splitter.split_text(node_own_text)
for text in split_texts:
current_chunk_infos.append({'text': text, 'node': node})
else:
current_chunk_infos.append({'text': node_own_text, 'node': node})
# 子ノードを処理
for child in node['children']:
last_chunk_info = current_chunk_infos[-1] if current_chunk_infos else None
# 直前のチャンクと子ノードを結合できるか試す
can_merge = False
if last_chunk_info:
merged_text = last_chunk_info['text'] + "\n\n" + child['full_text']
if count_tokens(merged_text) <= MAX_TOKENS:
can_merge = True
if can_merge:
# 結合して、コンテキストは元のままにする
last_chunk_info['text'] = merged_text
else:
# 結合できない場合 -> 子ノードのチャンキングを再帰的に行い、結果を現在の作業リストに追加
chunk_recursively_with_context(child, current_chunk_infos)
final_chunk_infos.extend(current_chunk_infos)
def format_chunk_with_context(chunk_text: str, node: dict) -> str:
"""
チャンクとそのコンテキストノードから、ヘッダー階層付きの最終的なテキストを生成する。
"""
# 1. 祖先ノードと自身のノードのヘッダーリストを作成
headers = []
current_node = node
while current_node and current_node['header']:
headers.append(current_node['header'])
current_node = current_node['parent']
headers.reverse() # ルート -> ... -> 子 の順にする
# 2. チャンクテキストが自身のヘッダーで始まっているか判定
own_header = node.get('header')
text_starts_with_header = own_header and chunk_text.strip().startswith(own_header)
# 3. 表示するコンテキストヘッダーを構築
context_parts = []
# 祖先ヘッダーをループ (自分自身は含まない)
if len(headers) > 1:
for header in headers[:-1]: # 最後のヘッダー(自分自身)は除く
context_parts.append(header)
context_parts.append('[...]')
# 4. 最終的なテキストを結合
full_text_parts = []
if context_parts:
full_text_parts.append('\n\n'.join(context_parts))
# チャンクテキストの先頭に自身のヘッダーがない場合(フォールバック分割時など)、補完する
if not text_starts_with_header and own_header:
full_text_parts.append(own_header)
full_text_parts.append(chunk_text)
# 空の要素を除外して結合
return '\n\n'.join(p for p in full_text_parts if p)
# --- 3. 実行のメインロジック (新方式を呼び出すように変更) ---
def main_process(markdown_text):
# 1. 木構造を構築
root_node = parse_markdown_to_tree(markdown_text)
build_full_text_recursively(root_node)
# 2. コンテキスト付きでチャンキング
chunk_infos = []
chunk_recursively_with_context(root_node, chunk_infos)
# 3. 各チャンクをヘッダー階層付きでフォーマット
final_chunks = []
for info in chunk_infos:
if info['text'].strip():
formatted_chunk = format_chunk_with_context(info['text'], info['node'])
final_chunks.append(formatted_chunk)
# 空のチャンクが生成された場合は除去
return [chunk for chunk in final_chunks if chunk.strip()]
# --- デモ用データと実行 ---
if __name__ == "__main__":
sample_markdown = """
# (1) 大規模言語モデル(LLM)の進化
本稿では、近年のAI技術の中核をなす大規模言語モデル(LLM)の進化の歴史と、その影響について概説する。LLMは、自然言語処理の分野に革命をもたらした。
## (1-1) Transformerモデルの登場
2017年にGoogleから発表された「Attention Is All You Need」という論文で提案されたTransformerモデルが、現代のLLMの基礎となっている。このモデルは、再帰型ニューラルネットワーク(RNN)や畳み込みニューラルネットワーク(CNN)に代わる、全く新しいアーキテクチャであった。自己注意機構(Self-Attention)により、文中の単語間の依存関係を効率的に捉えることができる。
### (1-1-1) 自己注意機構(Self-Attention)とは
自己注意機構は、入力されたシーケンス内の各要素が、他のどの要素に注目すべきかを動的に計算するメカニズムである。これにより、文脈に応じた単語の表現を獲得することが可能になる。クエリ(Query)、キー(Key)、バリュー(Value)の3つのベクトルを用いて計算される。この技術が、長い文章の理解能力を飛躍的に向上させた。
## (1-2) GPTシリーズの発展
OpenAIが開発したGPT(Generative Pre-trained Transformer)シリーズは、LLMの能力を世界に知らしめた。
### (1-2-1) GPT-3
2020年に発表されたGPT-3は、1750億ものパラメータを持ち、その巨大さから「Few-shot学習」や「Zero-shot学習」といった新しい学習パラダイムを可能にした。人間が書いたような自然な文章を生成する能力は、多くの人々を驚かせた。このモデルのAPIが公開されたことで、様々なアプリケーションが生まれた。金融、医療、教育など、多岐にわたる分野での活用が期待されている。しかし、その一方で、誤情報やバイアスの問題も指摘されている。倫理的な課題への対応が今後の重要なテーマとなるだろう。このセクションは意図的に長くしており、フォールバック分割のテスト用です。トークン数が上限を超えるように、さらに文章を追加します。ダミーテキスト、ダミーテキスト、ダミーテキスト。
### (1-2-2) GPT-4以降
GPT-4は、マルチモーダル対応となり、テキストだけでなく画像も入力として扱えるようになった。これにより、さらに応用範囲が広がり、より高度な推論が可能になった。
# (2) まとめ
LLMの技術は日進月歩で進化しており、私たちの社会に大きな変革をもたらす可能性を秘めている。今後の動向から目が離せない。
"""
chunks = main_process(sample_markdown)
print(f"--- 階層的チャンキングの結果({len(chunks)}個のチャンク) ---\n")
for i, chunk in enumerate(chunks):
chunk_token_count = count_tokens(chunk)
# コンテキスト表示によるトークン数の変化を考慮し、元のチャンクテキストのトークン数も計算
original_chunk_token_count = count_tokens(re.sub(r'.*\[...\]\n\n', '', chunk, flags=re.DOTALL))
print(f"--- チャンク {i + 1} (合計トークン数: {chunk_token_count})---")
print(chunk)
print("\n" + "=" * 80 + "\n")
def format_chunk_with_context(chunk_text: str, node: dict) -> str:
"""
チャンクとそのコンテキストノードから、ヘッダー階層付きの最終的なテキストを生成する。
"""
# チャンクテキストに含まれる最上位の見出しを特定
lines = chunk_text.strip().split('\n')
top_header_in_chunk = None
header_pattern = re.compile(r'^(#+)\s+')
for line in lines:
match = header_pattern.match(line)
if match:
top_header_in_chunk = line
break
if not top_header_in_chunk:
# チャンクに見出しが含まれていない場合は、元のノードのヘッダーを使用
return chunk_text
# チャンクの最上位見出しに対応するノードを探す
def find_node_by_header(root, target_header):
if root.get('header') == target_header:
return root
for child in root['children']:
result = find_node_by_header(child, target_header)
if result:
return result
return None
# ルートノードを取得
root = node
while root['parent']:
root = root['parent']
# チャンクの最上位見出しに対応するノードを見つける
top_node_in_chunk = find_node_by_header(root, top_header_in_chunk)
if not top_node_in_chunk:
return chunk_text
# そのノードの祖先ヘッダーを収集
headers = []
current = top_node_in_chunk
while current and current['header']:
headers.append(current['header'])
current = current['parent']
headers.reverse()
# コンテキストヘッダーを構築
context_parts = []
for i, header in enumerate(headers[:-1]): # 最後の要素(チャンクに含まれる最上位見出し)は除く
context_parts.append(header)
context_parts.append('[...]')
# 最終的なテキストを構築
if context_parts:
return '\n\n'.join(context_parts) + '\n\n' + chunk_text
else:
return chunk_text