Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(agno): read Entity/Relation as text/label and subject/object (#1769)
Amir Fathi4d648c2b4342
diff --git a/integrations/agno/context_store.py b/integrations/agno/context_store.pyindex e51e3ef2..952f203b 100644--- a/integrations/agno/context_store.py+++ b/integrations/agno/context_store.py@@ -228,8 +228,8 @@ class AgnoContextStore(_MemoryDbBase): # type: ignore[misc]kg = getattr(self._context, "knowledge_graph", None)if kg is not None:for ent in entities:- name = getattr(ent, "name", str(ent))- ntype = getattr(ent, "type", "Entity")+ name = getattr(ent, "text", getattr(ent, "name", str(ent)))+ ntype = getattr(ent, "label", getattr(ent, "type", "Entity"))try:kg.add_node(node_id=name, node_type=ntype)except Exception:diff --git a/integrations/agno/kg_toolkit.py b/integrations/agno/kg_toolkit.pyindex fdefe8a6..78366e52 100644--- a/integrations/agno/kg_toolkit.py+++ b/integrations/agno/kg_toolkit.py@@ -154,8 +154,8 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]entities = [{- "name": getattr(e, "name", str(e)),- "type": getattr(e, "type", ""),+ "name": getattr(e, "text", str(e)),+ "type": getattr(e, "label", ""),"confidence": _conf(getattr(e, "confidence", None)),}for e in raw@@ -182,20 +182,30 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]strJSON list of ``{"source": str, "relation": str, "target": str, "confidence": float}``."""- entity_list: Optional[List[str]] = None+ requested_names: Optional[List[str]] = Noneif entities:try:- entity_list = json.loads(entities)+ requested_names = json.loads(entities)except json.JSONDecodeError:- entity_list = [e.strip() for e in entities.split(",") if e.strip()]+ requested_names = [e.strip() for e in entities.split(",") if e.strip()]try:- raw = self._rel.extract_relations(text, entities=entity_list) or []+ # RelationExtractor.extract_relations() needs real Entity objects+ # (it reads len(entities) and each entity's .text), not None or+ # bare name strings, so run NER first and hand it those (#1737).+ entity_objs = self._ner.extract_entities(text) or []+ if requested_names:+ wanted = {name.strip().lower() for name in requested_names}+ entity_objs = [+ e for e in entity_objs+ if getattr(e, "text", str(e)).strip().lower() in wanted+ ]+ raw = self._rel.extract_relations(text, entities=entity_objs) or []relations = [{- "source": getattr(r, "source", ""),- "relation": getattr(r, "type", getattr(r, "relation", "")),- "target": getattr(r, "target", ""),+ "source": getattr(getattr(r, "subject", None), "text", ""),+ "relation": getattr(r, "predicate", ""),+ "target": getattr(getattr(r, "object", None), "text", ""),"confidence": round(float(getattr(r, "confidence", 1.0)), 4),}for r in rawdiff --git a/integrations/agno/knowledge_graph.py b/integrations/agno/knowledge_graph.pyindex 4862cdd9..99966be2 100644--- a/integrations/agno/knowledge_graph.py+++ b/integrations/agno/knowledge_graph.py@@ -379,7 +379,7 @@ class AgnoKnowledgeGraph(_KnowledgeBase): # type: ignore[misc]ner_result: List[Any] = []try:ner_result = self._ner.extract_entities(chunk) or []- chunk_entities = [getattr(e, "name", str(e)) for e in ner_result]+ chunk_entities = [getattr(e, "text", str(e)) for e in ner_result]all_entities.extend(chunk_entities)except Exception as exc:logger.debug("NER failed for chunk in '%s': %s", source, exc)diff --git a/tests/integrations/agno/test_context_store.py b/tests/integrations/agno/test_context_store.pyindex b9fd7ddc..4733943a 100644--- a/tests/integrations/agno/test_context_store.py+++ b/tests/integrations/agno/test_context_store.py@@ -229,5 +229,74 @@ class TestAgnoContextStoreExtendedAPI(unittest.TestCase):self.store._context.record_decision.assert_called()+class TestAgnoContextStoreUpsertNERAttributes(unittest.TestCase):+ """upsert_memory() must read .text/.label from Entity, not .name/.type (#1737)."""++ def setUp(self):+ self.store = AgnoContextStore(decision_tracking=False)++ def _make_row(self, text: str):+ row = MagicMock()+ row.memory = text+ row.id = None+ row.user_id = "u1"+ row.last_updated = 0.0+ row.topics = []+ return row++ def test_upsert_indexes_entity_text_not_repr(self):+ """Entities added to the knowledge graph must use .text, not str(entity)."""+ from semantica.semantic_extract.types import Entity++ captured_node_ids: list = []+ fake_kg = MagicMock()+ fake_kg.add_node.side_effect = lambda node_id, node_type: captured_node_ids.append(node_id)++ fake_context = MagicMock()+ fake_context.store.return_value = None+ fake_context.knowledge_graph = fake_kg++ with patch(+ "integrations.agno.context_store.NERExtractor"+ ) as MockNER:+ instance = MockNER.return_value+ instance.extract_entities.return_value = [+ Entity(text="Alice Smith", label="PERSON", start_char=0, end_char=11),+ Entity(text="Acme Corp", label="ORG", start_char=20, end_char=29),+ ]+ self.store._context = fake_context+ self.store.upsert_memory(self._make_row("Alice Smith works at Acme Corp."))++ self.assertIn("Alice Smith", captured_node_ids)+ self.assertIn("Acme Corp", captured_node_ids)+ # Confirm no repr strings leaked through+ for node_id in captured_node_ids:+ self.assertNotIn("Entity(", node_id)++ def test_upsert_indexes_entity_label_as_type(self):+ """Node type must be the .label value (e.g. 'PERSON'), not an empty string."""+ from semantica.semantic_extract.types import Entity++ captured_types: list = []+ fake_kg = MagicMock()+ fake_kg.add_node.side_effect = lambda node_id, node_type: captured_types.append(node_type)++ fake_context = MagicMock()+ fake_context.store.return_value = None+ fake_context.knowledge_graph = fake_kg++ with patch(+ "integrations.agno.context_store.NERExtractor"+ ) as MockNER:+ instance = MockNER.return_value+ instance.extract_entities.return_value = [+ Entity(text="Alice Smith", label="PERSON", start_char=0, end_char=11),+ ]+ self.store._context = fake_context+ self.store.upsert_memory(self._make_row("Alice Smith is here."))++ self.assertIn("PERSON", captured_types)++if __name__ == "__main__":unittest.main()diff --git a/tests/integrations/agno/test_kg_toolkit.py b/tests/integrations/agno/test_kg_toolkit.pyindex b9e1a40b..9c2dcb24 100644--- a/tests/integrations/agno/test_kg_toolkit.py+++ b/tests/integrations/agno/test_kg_toolkit.py@@ -67,6 +67,49 @@ def _fake_relation(src="Tesla", rel="FOUNDED_BY", tgt="Elon Musk", conf=0.85):return r+class _DataclassNER:+ """Returns Semantica's real ``Entity`` dataclass shape (text/label, no name)."""++ def extract_entities(self, text):+ from semantica.semantic_extract.types import Entity++ return [+ Entity(text="Tesla", label="ORG", start_char=0, end_char=5),+ Entity(text="Elon Musk", label="PERSON", start_char=17, end_char=26),+ ]+++class _DataclassRelExtractor:+ """Returns Semantica's real ``Relation`` dataclass shape (subject/object).++ Validates that ``entities`` is a list of real ``Entity`` objects, not+ ``None`` or bare name strings (#1737). The non-empty check is intentionally+ omitted: when the caller filters all entities out the real extractor returns+ ``[]`` from its ``if not entities: return []`` guard; asserting non-empty+ here would turn that into a caught ``AssertionError`` and mask the path.+ """++ def extract_relations(self, text, entities=None):+ from semantica.semantic_extract.types import Entity, Relation++ assert isinstance(entities, list), "entities must be a list"+ assert all(isinstance(e, Entity) for e in entities), "entities must be Entity objects"++ # Mirror the real extractor: return nothing when the caller has no entities.+ if not entities:+ return []++ return [+ Relation(+ subject=Entity(text="Tesla", label="ORG", start_char=0, end_char=5),+ predicate="FOUNDED_BY",+ object=Entity(+ text="Elon Musk", label="PERSON", start_char=17, end_char=26+ ),+ )+ ]++class _FakeNER:def extract_entities(self, text):return [_fake_entity("Tesla"), _fake_entity("Elon Musk", "PERSON")]@@ -389,5 +432,79 @@ class TestExportSubgraph(unittest.TestCase):self.assertIsInstance(result, dict)+class TestAgnoKGToolkitDataclassShapes(unittest.TestCase):+ """Real Semantica ``Entity``/``Relation`` dataclasses (text/label,+ subject/object) instead of MagicMock-shaped fakes."""++ def setUp(self):+ self.kit = AgnoKGToolkit(+ ner_extractor=_DataclassNER(),+ relation_extractor=_DataclassRelExtractor(),+ reasoner=_FakeReasoner(),+ )++ def test_extract_entities_reads_text_label(self):+ result = json.loads(+ self.kit.extract_entities("Tesla founded by Elon Musk")+ )+ self.assertEqual(result["count"], 2)+ self.assertEqual(result["entities"][0]["name"], "Tesla")+ self.assertEqual(result["entities"][0]["type"], "ORG")+ self.assertEqual(result["entities"][1]["name"], "Elon Musk")+ self.assertEqual(result["entities"][1]["type"], "PERSON")++ def test_extract_relations_reads_subject_object(self):+ result = json.loads(+ self.kit.extract_relations("Tesla founded by Elon Musk")+ )+ self.assertEqual(result["count"], 1)+ self.assertEqual(result["relations"][0]["source"], "Tesla")+ self.assertEqual(result["relations"][0]["relation"], "FOUNDED_BY")+ self.assertEqual(result["relations"][0]["target"], "Elon Musk")+++class TestExtractRelationsAgainstRealExtractor(unittest.TestCase):+ """extract_relations() against the real NERExtractor/RelationExtractor+ (pattern method, no model download), not a fake that accepts whatever+ it's given. The real RelationExtractor needs actual Entity objects, so+ this is what would have caught #1737 (both with and without the+ optional name filter)."""++ def setUp(self):+ from semantica.semantic_extract import NERExtractor, RelationExtractor++ self.kit = AgnoKGToolkit(+ ner_extractor=NERExtractor(method="pattern"),+ relation_extractor=RelationExtractor(),+ reasoner=_FakeReasoner(),+ )+ self.text = "Tim Cook works at Apple Inc."++ def test_without_filter_finds_the_real_relation(self):+ result = json.loads(self.kit.extract_relations(self.text))+ self.assertNotIn("error", result)+ self.assertEqual(result["count"], 1)+ self.assertEqual(result["relations"][0]["source"], "Tim Cook")+ self.assertEqual(result["relations"][0]["relation"], "works_for")+ self.assertEqual(result["relations"][0]["target"], "Apple Inc.")++ def test_filter_matching_both_names_still_finds_it(self):+ result = json.loads(self.kit.extract_relations(+ self.text, entities=json.dumps(["Tim Cook", "Apple Inc."])+ ))+ self.assertNotIn("error", result)+ self.assertEqual(result["count"], 1)++ def test_filter_dropping_one_name_finds_nothing(self):+ # Restricting to one name removes the relation's other side from+ # the real extractor's entity list, so it can no longer pair a+ # subject with an object and correctly returns none.+ result = json.loads(self.kit.extract_relations(+ self.text, entities=json.dumps(["Tim Cook"])+ ))+ self.assertNotIn("error", result)+ self.assertEqual(result["count"], 0)++if __name__ == "__main__":unittest.main()diff --git a/tests/integrations/agno/test_knowledge_graph.py b/tests/integrations/agno/test_knowledge_graph.pyindex 68a360c7..5fea94e9 100644--- a/tests/integrations/agno/test_knowledge_graph.py+++ b/tests/integrations/agno/test_knowledge_graph.py@@ -85,6 +85,39 @@ class _FakeGraphBuilder:return MagicMock()+class _DataclassNER:+ """Returns Semantica's real ``Entity`` dataclass shape (text/label, no name)."""++ def extract_entities(self, text):+ from semantica.semantic_extract.types import Entity++ return [Entity(text="Tesla", label="ORG", start_char=0, end_char=5)]+++class _DataclassRelExtractor:+ """Returns Semantica's real ``Relation`` dataclass shape (subject/object)."""++ def extract_relations(self, text, entities=None):+ from semantica.semantic_extract.types import Entity, Relation++ return [+ Relation(+ subject=Entity(text="Tesla", label="ORG", start_char=0, end_char=5),+ predicate="FOUNDED_BY",+ object=Entity(text="Elon Musk", label="PERSON", start_char=17, end_char=26),+ )+ ]+++class _CapturingGraphBuilder:+ def __init__(self):+ self.sources = None++ def build(self, sources):+ self.sources = sources+ return MagicMock()++class _FakeContextGraph:def find_nodes(self, label=None):node = MagicMock()@@ -229,5 +262,21 @@ class TestAgnoKnowledgeGraphPathLoading(unittest.TestCase):os.unlink(tmp_path)+class TestAgnoKnowledgeGraphDataclassShapes(unittest.TestCase):+ """Real Semantica ``Entity``/``Relation`` dataclasses (text/label,+ subject/object) instead of MagicMock-shaped fakes."""++ def test_ingest_text_reads_entity_text(self):+ builder = _CapturingGraphBuilder()+ kg = AgnoKnowledgeGraph(+ graph_builder=builder,+ ner_extractor=_DataclassNER(),+ relation_extractor=_DataclassRelExtractor(),+ context_graph=_FakeContextGraph(),+ )+ kg._ingest_text("Tesla was founded by Elon Musk.", source="test")+ self.assertEqual(builder.sources[0]["entities"], ["Tesla"])++if __name__ == "__main__":unittest.main()