llama_index [Bug]: 知识图谱 _extract_rel_text_keywords() 函数在 retrievers.py 中未按预期工作

m4pnthwp  于 2个月前  发布在  其他
关注(0)|答案(1)|浏览(29)

Bug描述

当在 retrievers.py 的 _retrieve() 方法中将 _include_text 设置为 True 时,代码本意是从 rel_texts 中的扁平化图关系中提取关键词,并使用它们来搜索作为 LLM 响应查询的上下文的相关块(节点)。

然而,在使用 Neo4j 图存储时,返回的扁平化关系如下所示,第一个图节点被省略,关系名称和图节点名称之间交替出现。

当前实现的 _extract_rel_text_keywords() 没有考虑到这种关系格式,尝试从每个关系中获取第0个和第2个字符串,错误地剥离它们,并将它们作为用于在知识库支持的字典中查找的关键字返回。表示为 "['HAS', 'a dog', 'LIKES_TO', 'chase squirrels']" 的扁平化关系会提取 keywords=["['HAS", "LIKES_TO"] 而不是预期的 keywords= ["a dog", "chase squirrels"]。请注意,无论如何都会错误地剥离第一个元素,因为 "[]" 不在 strip() 函数中。

建议解决方案:

我假设该函数只预期三元组的形式为 "(subject, predicate, object)",因此这是有意义的。但是应该包含功能以支持 Neo4j/Cypher 格式的关系。此功能无法正常工作使得大部分知识图变得多余,过度强调使用向量嵌入来搜索相关上下文。

版本

0.10.44

重现步骤

查询一个 KnowledgeGraphIndex,调试并进入知识图的知识检索器(retriever)文件中的函数。

相关日志/回溯

  • 无响应*
sshcrbum

sshcrbum1#

嘿,@pdugar02!我在这里帮助你解决任何bug、问题或贡献。让我们一起解决你面临的任何问题。
要解决retrievers.py中的_extract_rel_text_keywords函数在正确处理Neo4j/Cypher格式化关系方面的问题,你可以修改该函数以解析Cypher关系格式。通常,Cypher关系格式为(node1)-[relationship]->(node2)。你可以相应地从节点和关系中提取关键字。
这是更新后的_extract_rel_text_keywords函数:

def _extract_rel_text_keywords(self, rel_texts: List[str]) -> List[str]:
    """Find the keywords for given rel text triplets."""
    keywords = []
    for rel_text in rel_texts:
        # Assuming the format is (node1)-[relationship]->(node2)
        parts = rel_text.split("->")
        if len(parts) == 2:
            left_part = parts[0].strip()
            right_part = parts[1].strip()
            
            # Extract node1 and relationship
            if left_part.startswith("(") and left_part.endswith(")"):
                node1 = left_part[1:-1].split("-")[0].strip()
                relationship = left_part.split("[")[1].split("]")[0].strip()
                if node1:
                    keywords.append(node1.strip("(\"'"))
                if relationship:
                    keywords.append(relationship.strip("(\"'"))
            
            # Extract node2
            if right_part.startswith("(") and right_part.endswith(")"):
                node2 = right_part[1:-1].strip()
                if node2:
                    keywords.append(node2.strip("(\"'"))
    return keywords

这个函数现在通过拆分关系文本并从节点和关系中提取关键字(1(https://github.com/run-llama/llama_index/blob/main/llama-index-legacy/llama_index/legacy/indices/knowledge_graph/retrievers.py)2(https://github.com/run-llama/llama_index/blob/main/llama-index-core/llama_index/core/indices/knowledge_graph/retrievers.py))来正确处理Neo4j/Cypher格式化关系。

  • 要继续与Dosu交流,请提及@dosu。*

相关问题