Llama-Indexのドキュメントにある「GraphRAG Implementation with LlamaIndex – V2」を参考にNeo4jを用いたGraphRAGを構築しようとした際に、正規表現での抽出が上手くいきませんでした。
使用する正規表現のそもそものバグ並びに日本語に対応できていなかったことが原因でした。
本記事ではその対応方法をまとめます。
結論
GraphRAGQueryEngineクラスの、以下の正規表現を変更します。
節:GraphRAGQueryEngine
pattern = r"(\w+(?:\s+\w+)*)\s*\({[^}]*}\)\s*->\s*([^(]+?)\s*\({[^}]*}\)\s*->\s*(\w+(?:\s+\w+)*)"
for node in nodes_retrieved:
matches = re.findall(pattern, node.text, re.DOTALL)
for match in matches:
subject = match[0]
obj = match[2]
enitites.add(subject)
enitites.add(obj)
を以下に修正
pattern = r"((\w+(?:\s+\w+)*):)?\s*(.+?)\s->\s*(.+?)\s->\s*(.*?)\s"
for node in nodes_retrieved:
matches = re.findall(pattern, node.text, re.DOTALL)
for match in matches:
subject = match[2]
obj = match[4]
enitites.add(subject)
enitites.add(obj)
節:Build End to End GraphRAG Pipeline
KG_TRIPLET_EXTRACT_TMPL = """
... 省略 ...
Format each relationship as ("relationship"$$$$<source_entity>$$$$<target_entity>$$$$<relation>$$$$<relationship_description>)
... 省略 ...
"""
を以下に修正(「”」が足りない)
KG_TRIPLET_EXTRACT_TMPL = """
... 省略 ...
Format each relationship as ("relationship"$$$$"<source_entity>"$$$$"<target_entity>"$$$$"<relation>"$$$$"<relationship_description>")
... 省略 ...
"""
コメント