395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844 | class KnowledgeGraphRAGRetriever(BaseRetriever):
"""知识图谱RAG检索器。
执行对知识图谱进行子图RAG。
Args:
service_context(可选[ServiceContext]):要使用的服务上下文。
storage_context(可选[StorageContext]):要使用的存储上下文。
entity_extract_fn(可选[Callable]):用于提取实体的函数。
entity_extract_template(可选[BasePromptTemplate]):查询关键实体提取提示(参见::ref:`Prompt-Templates`)。
entity_extract_policy(可选[str]):要使用的实体提取策略。
默认值:"union"
可能的取值:"union","intersection"
synonym_expand_fn(可选[Callable]):用于扩展同义词的函数。
synonym_expand_template(可选[QueryKeywordExpandPrompt]):查询关键实体扩展提示(参见::ref:`Prompt-Templates`)。
synonym_expand_policy(可选[str]):要使用的同义词扩展策略。
默认值:"union"
可能的取值:"union","intersection"
max_entities(int):要提取的实体的最大数量。
默认值:5
max_synonyms(int):要扩展的每个实体的最大同义词数量。
默认值:5
retriever_mode(可选[str]):要使用的检索器模式。
默认值:"keyword"
可能的取值:"keyword","embedding","keyword_embedding"
with_nl2graphquery(bool):是否在上下文中结合NL2GraphQuery。
默认值:False
graph_traversal_depth(int):图遍历的深度。
默认值:2
max_knowledge_sequence(int):要包含在响应中的知识序列的最大数量。默认情况下为30。
verbose(bool):是否打印调试信息。"""
def __init__(
self,
storage_context: Optional[StorageContext] = None,
llm: Optional[LLM] = None,
entity_extract_fn: Optional[Callable] = None,
entity_extract_template: Optional[BasePromptTemplate] = None,
entity_extract_policy: Optional[str] = "union",
synonym_expand_fn: Optional[Callable] = None,
synonym_expand_template: Optional[BasePromptTemplate] = None,
synonym_expand_policy: Optional[str] = "union",
max_entities: int = 5,
max_synonyms: int = 5,
retriever_mode: Optional[str] = "keyword",
with_nl2graphquery: bool = False,
graph_traversal_depth: int = 2,
max_knowledge_sequence: int = REL_TEXT_LIMIT,
verbose: bool = False,
callback_manager: Optional[CallbackManager] = None,
# deprecated
service_context: Optional[ServiceContext] = None,
**kwargs: Any,
) -> None:
"""初始化检索器。"""
# Ensure that we have a graph store
assert storage_context is not None, "Must provide a storage context."
assert (
storage_context.graph_store is not None
), "Must provide a graph store in the storage context."
self._storage_context = storage_context
self._graph_store = storage_context.graph_store
self._llm = llm or llm_from_settings_or_context(Settings, service_context)
self._entity_extract_fn = entity_extract_fn
self._entity_extract_template = (
entity_extract_template or DEFAULT_QUERY_KEYWORD_EXTRACT_TEMPLATE
)
self._entity_extract_policy = entity_extract_policy
self._synonym_expand_fn = synonym_expand_fn
self._synonym_expand_template = (
synonym_expand_template or DEFAULT_SYNONYM_EXPAND_PROMPT
)
self._synonym_expand_policy = synonym_expand_policy
self._max_entities = max_entities
self._max_synonyms = max_synonyms
self._retriever_mode = retriever_mode
self._with_nl2graphquery = with_nl2graphquery
if self._with_nl2graphquery:
from llama_index.core.query_engine.knowledge_graph_query_engine import (
KnowledgeGraphQueryEngine,
)
graph_query_synthesis_prompt = kwargs.get(
"graph_query_synthesis_prompt",
None,
)
if graph_query_synthesis_prompt is not None:
del kwargs["graph_query_synthesis_prompt"]
graph_response_answer_prompt = kwargs.get(
"graph_response_answer_prompt",
None,
)
if graph_response_answer_prompt is not None:
del kwargs["graph_response_answer_prompt"]
refresh_schema = kwargs.get("refresh_schema", False)
response_synthesizer = kwargs.get("response_synthesizer", None)
self._kg_query_engine = KnowledgeGraphQueryEngine(
llm=self._llm,
storage_context=self._storage_context,
graph_query_synthesis_prompt=graph_query_synthesis_prompt,
graph_response_answer_prompt=graph_response_answer_prompt,
refresh_schema=refresh_schema,
verbose=verbose,
response_synthesizer=response_synthesizer,
service_context=service_context,
**kwargs,
)
self._graph_traversal_depth = graph_traversal_depth
self._max_knowledge_sequence = max_knowledge_sequence
self._verbose = verbose
refresh_schema = kwargs.get("refresh_schema", False)
try:
self._graph_schema = self._graph_store.get_schema(refresh=refresh_schema)
except NotImplementedError:
self._graph_schema = ""
except Exception as e:
logger.warning(f"Failed to get graph schema: {e}")
self._graph_schema = ""
super().__init__(
callback_manager=callback_manager
or callback_manager_from_settings_or_context(Settings, service_context)
)
def _process_entities(
self,
query_str: str,
handle_fn: Optional[Callable],
handle_llm_prompt_template: Optional[BasePromptTemplate],
cross_handle_policy: Optional[str] = "union",
max_items: Optional[int] = 5,
result_start_token: str = "KEYWORDS:",
) -> List[str]:
"""从查询字符串中获取实体。"""
assert cross_handle_policy in [
"union",
"intersection",
], "Invalid entity extraction policy."
if cross_handle_policy == "intersection":
assert all(
[
handle_fn is not None,
handle_llm_prompt_template is not None,
]
), "Must provide entity extract function and template."
assert any(
[
handle_fn is not None,
handle_llm_prompt_template is not None,
]
), "Must provide either entity extract function or template."
enitities_fn: List[str] = []
enitities_llm: Set[str] = set()
if handle_fn is not None:
enitities_fn = handle_fn(query_str)
if handle_llm_prompt_template is not None:
response = self._llm.predict(
handle_llm_prompt_template,
max_keywords=max_items,
question=query_str,
)
enitities_llm = extract_keywords_given_response(
response, start_token=result_start_token, lowercase=False
)
if cross_handle_policy == "union":
entities = list(set(enitities_fn) | enitities_llm)
elif cross_handle_policy == "intersection":
entities = list(set(enitities_fn).intersection(set(enitities_llm)))
if self._verbose:
print_text(f"Entities processed: {entities}\n", color="green")
return entities
async def _aprocess_entities(
self,
query_str: str,
handle_fn: Optional[Callable],
handle_llm_prompt_template: Optional[BasePromptTemplate],
cross_handle_policy: Optional[str] = "union",
max_items: Optional[int] = 5,
result_start_token: str = "KEYWORDS:",
) -> List[str]:
"""从查询字符串中获取实体。"""
assert cross_handle_policy in [
"union",
"intersection",
], "Invalid entity extraction policy."
if cross_handle_policy == "intersection":
assert all(
[
handle_fn is not None,
handle_llm_prompt_template is not None,
]
), "Must provide entity extract function and template."
assert any(
[
handle_fn is not None,
handle_llm_prompt_template is not None,
]
), "Must provide either entity extract function or template."
enitities_fn: List[str] = []
enitities_llm: Set[str] = set()
if handle_fn is not None:
enitities_fn = handle_fn(query_str)
if handle_llm_prompt_template is not None:
response = await self._llm.apredict(
handle_llm_prompt_template,
max_keywords=max_items,
question=query_str,
)
enitities_llm = extract_keywords_given_response(
response, start_token=result_start_token, lowercase=False
)
if cross_handle_policy == "union":
entities = list(set(enitities_fn) | enitities_llm)
elif cross_handle_policy == "intersection":
entities = list(set(enitities_fn).intersection(set(enitities_llm)))
if self._verbose:
print_text(f"Entities processed: {entities}\n", color="green")
return entities
def _get_entities(self, query_str: str) -> List[str]:
"""从查询字符串中获取实体。"""
entities = self._process_entities(
query_str,
self._entity_extract_fn,
self._entity_extract_template,
self._entity_extract_policy,
self._max_entities,
"KEYWORDS:",
)
expanded_entities = self._expand_synonyms(entities)
return list(set(entities) | set(expanded_entities))
async def _aget_entities(self, query_str: str) -> List[str]:
"""从查询字符串中获取实体。"""
entities = await self._aprocess_entities(
query_str,
self._entity_extract_fn,
self._entity_extract_template,
self._entity_extract_policy,
self._max_entities,
"KEYWORDS:",
)
expanded_entities = await self._aexpand_synonyms(entities)
return list(set(entities) | set(expanded_entities))
def _expand_synonyms(self, keywords: List[str]) -> List[str]:
"""扩展关键词的同义词或类似表达。"""
return self._process_entities(
str(keywords),
self._synonym_expand_fn,
self._synonym_expand_template,
self._synonym_expand_policy,
self._max_synonyms,
"SYNONYMS:",
)
async def _aexpand_synonyms(self, keywords: List[str]) -> List[str]:
"""扩展关键词的同义词或类似表达。"""
return await self._aprocess_entities(
str(keywords),
self._synonym_expand_fn,
self._synonym_expand_template,
self._synonym_expand_policy,
self._max_synonyms,
"SYNONYMS:",
)
def _get_knowledge_sequence(
self, entities: List[str]
) -> Tuple[List[str], Optional[Dict[Any, Any]]]:
"""从实体中获取知识序列。"""
# Get SubGraph from Graph Store as Knowledge Sequence
rel_map: Optional[Dict] = self._graph_store.get_rel_map(
entities, self._graph_traversal_depth, limit=self._max_knowledge_sequence
)
logger.debug(f"rel_map: {rel_map}")
# Build Knowledge Sequence
knowledge_sequence = []
if rel_map:
knowledge_sequence.extend(
[str(rel_obj) for rel_objs in rel_map.values() for rel_obj in rel_objs]
)
else:
logger.info("> No knowledge sequence extracted from entities.")
return [], None
return knowledge_sequence, rel_map
async def _aget_knowledge_sequence(
self, entities: List[str]
) -> Tuple[List[str], Optional[Dict[Any, Any]]]:
"""从实体中获取知识序列。"""
# Get SubGraph from Graph Store as Knowledge Sequence
# TBD: async in graph store
rel_map: Optional[Dict] = self._graph_store.get_rel_map(
entities, self._graph_traversal_depth, limit=self._max_knowledge_sequence
)
logger.debug(f"rel_map from GraphStore:\n{rel_map}")
# Build Knowledge Sequence
knowledge_sequence = []
if rel_map:
knowledge_sequence.extend(
[str(rel_obj) for rel_objs in rel_map.values() for rel_obj in rel_objs]
)
else:
logger.info("> No knowledge sequence extracted from entities.")
return [], None
return knowledge_sequence, rel_map
def _build_nodes(
self, knowledge_sequence: List[str], rel_map: Optional[Dict[Any, Any]] = None
) -> List[NodeWithScore]:
"""从知识序列构建节点。"""
if len(knowledge_sequence) == 0:
logger.info("> No knowledge sequence extracted from entities.")
return []
_new_line_char = "\n"
context_string = (
f"The following are knowledge sequence in max depth"
f" {self._graph_traversal_depth} "
f"in the form of directed graph like:\n"
f"`subject -[predicate]->, object, <-[predicate_next_hop]-,"
f" object_next_hop ...`"
f" extracted based on key entities as subject:\n"
f"{_new_line_char.join(knowledge_sequence)}"
)
if self._verbose:
print_text(f"Graph RAG context:\n{context_string}\n", color="blue")
rel_node_info = {
"kg_rel_map": rel_map,
"kg_rel_text": knowledge_sequence,
}
metadata_keys = ["kg_rel_map", "kg_rel_text"]
if self._graph_schema != "":
rel_node_info["kg_schema"] = {"schema": self._graph_schema}
metadata_keys.append("kg_schema")
node = NodeWithScore(
node=TextNode(
text=context_string,
score=1.0,
metadata=rel_node_info,
excluded_embed_metadata_keys=metadata_keys,
excluded_llm_metadata_keys=metadata_keys,
)
)
return [node]
def _retrieve_keyword(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
"""以关键字模式检索。"""
if self._retriever_mode not in ["keyword", "keyword_embedding"]:
return []
# Get entities
entities = self._get_entities(query_bundle.query_str)
# Before we enable embedding/semantic search, we need to make sure
# we don't miss any entities that's synoynm of the entities we extracted
# in string matching based retrieval in following steps, thus we expand
# synonyms here.
if len(entities) == 0:
logger.info("> No entities extracted from query string.")
return []
# Get SubGraph from Graph Store as Knowledge Sequence
knowledge_sequence, rel_map = self._get_knowledge_sequence(entities)
return self._build_nodes(knowledge_sequence, rel_map)
async def _aretrieve_keyword(
self, query_bundle: QueryBundle
) -> List[NodeWithScore]:
"""以关键字模式检索。"""
if self._retriever_mode not in ["keyword", "keyword_embedding"]:
return []
# Get entities
entities = await self._aget_entities(query_bundle.query_str)
# Before we enable embedding/semantic search, we need to make sure
# we don't miss any entities that's synoynm of the entities we extracted
# in string matching based retrieval in following steps, thus we expand
# synonyms here.
if len(entities) == 0:
logger.info("> No entities extracted from query string.")
return []
# Get SubGraph from Graph Store as Knowledge Sequence
knowledge_sequence, rel_map = await self._aget_knowledge_sequence(entities)
return self._build_nodes(knowledge_sequence, rel_map)
def _retrieve_embedding(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
"""以嵌入模式检索。"""
if self._retriever_mode not in ["embedding", "keyword_embedding"]:
return []
# TBD: will implement this later with vector store.
raise NotImplementedError
async def _aretrieve_embedding(
self, query_bundle: QueryBundle
) -> List[NodeWithScore]:
"""以嵌入模式检索。"""
if self._retriever_mode not in ["embedding", "keyword_embedding"]:
return []
# TBD: will implement this later with vector store.
raise NotImplementedError
def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
"""为响应构建节点。"""
nodes: List[NodeWithScore] = []
if self._with_nl2graphquery:
try:
nodes_nl2graphquery = self._kg_query_engine._retrieve(query_bundle)
nodes.extend(nodes_nl2graphquery)
except Exception as e:
logger.warning(f"Error in retrieving from nl2graphquery: {e}")
nodes.extend(self._retrieve_keyword(query_bundle))
nodes.extend(self._retrieve_embedding(query_bundle))
return nodes
async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
"""为响应构建节点。"""
nodes: List[NodeWithScore] = []
if self._with_nl2graphquery:
try:
nodes_nl2graphquery = await self._kg_query_engine._aretrieve(
query_bundle
)
nodes.extend(nodes_nl2graphquery)
except Exception as e:
logger.warning(f"Error in retrieving from nl2graphquery: {e}")
nodes.extend(await self._aretrieve_keyword(query_bundle))
nodes.extend(await self._aretrieve_embedding(query_bundle))
return nodes
|