Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(agno): read the keys ContextGraph returns in the Agno graph tools (#1738)

Chaoqid72bbf672811
diff --git a/integrations/agno/kg_toolkit.py b/integrations/agno/kg_toolkit.py
index db4ba01e..fdefe8a6 100644
--- a/integrations/agno/kg_toolkit.py
+++ b/integrations/agno/kg_toolkit.py
@@ -268,7 +268,7 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
Query the context graph in natural language or Cypher.
For natural-language queries all nodes are retrieved and filtered by
- whether ``query`` appears in their ``node_id``. Pass a string starting
+ whether ``query`` appears in their ``id`` or ``type``. Pass a string starting
with ``"MATCH"`` for raw Cypher execution (requires a Neo4j / FalkorDB
backend).
@@ -303,8 +303,8 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
out = []
for n in (all_nodes or []):
if isinstance(n, dict):
- node_id = n.get("node_id", "")
- node_type = n.get("node_type", "")
+ node_id = n.get("id", "")
+ node_type = n.get("type", "")
else:
node_id = getattr(n, "id", getattr(n, "label", str(n)))
node_type = getattr(n, "node_type", "")
@@ -344,7 +344,7 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
neighbours = self._graph.get_neighbors(node_id=e, hops=1) # type: ignore[attr-defined]
for n in (neighbours or []):
if isinstance(n, dict):
- label = n.get("node_id", "")
+ label = n.get("id", "")
else:
label = getattr(n, "label", str(n))
if label and label not in visited:
@@ -397,8 +397,8 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
all_nodes = self._graph.find_nodes() # type: ignore[attr-defined]
for node in (all_nodes or [])[:50]:
if isinstance(node, dict):
- label = node.get("node_id", "")
- ntype = node.get("node_type", "Entity")
+ label = node.get("id", "")
+ ntype = node.get("type", "Entity")
else:
label = getattr(node, "label", str(node))
ntype = getattr(node, "node_type", "Entity")
@@ -409,7 +409,7 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
try:
result = self._reasoner.infer_facts(fact_list, rule_list)
- inferred = getattr(result, "inferred_facts", []) or []
+ inferred = result or []
inferred_strs = [str(f) for f in inferred]
logger.debug("infer_facts → %d new facts", len(inferred_strs))
return json.dumps({"inferred_facts": inferred_strs, "count": len(inferred_strs)})
@@ -446,7 +446,9 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
rdf_format = {"ttl": "turtle", "json-ld": "json-ld", "xml": "xml", "nt": "nt"}.get(
format, format
)
- output = exporter.export_to_rdf(self._graph, format=rdf_format) # type: ignore[arg-type]
+ output = exporter.export_to_rdf(
+ self._graph.to_kg_dict(), format=rdf_format
+ )
return json.dumps({"format": rdf_format, "data": output})
except Exception as exc:
logger.warning("export_subgraph failed: %s", exc)
@@ -456,7 +458,7 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]
nodes = []
for n in (all_nodes or []):
if isinstance(n, dict):
- nodes.append({"id": n.get("node_id", ""), "label": n.get("node_id", "")})
+ nodes.append({"id": n.get("id", ""), "label": n.get("id", "")})
else:
nodes.append(
{"id": getattr(n, "id", ""), "label": getattr(n, "label", "")}
diff --git a/integrations/agno/knowledge_graph.py b/integrations/agno/knowledge_graph.py
index 78004bc3..4862cdd9 100644
--- a/integrations/agno/knowledge_graph.py
+++ b/integrations/agno/knowledge_graph.py
@@ -328,9 +328,9 @@ class AgnoKnowledgeGraph(_KnowledgeBase): # type: ignore[misc]
neighbours = self._graph.get_neighbors(node_id=entity, hops=1)
for n in (neighbours or [])[:10]:
if isinstance(n, dict):
- node_id = n.get("node_id", "")
- ntype = n.get("node_type", "")
- edge_type = n.get("edge_type", "related_to")
+ node_id = n.get("id", "")
+ ntype = n.get("type", "")
+ edge_type = n.get("relationship", "related_to")
suffix = f" (type: {ntype})" if ntype else ""
lines.append(f" --[{edge_type}]--> {node_id}{suffix}")
else:
@@ -458,9 +458,9 @@ class AgnoKnowledgeGraph(_KnowledgeBase): # type: ignore[misc]
neighbours = self._graph.get_neighbors(node_id=entity, hops=1)
for n in (neighbours or [])[:3]:
if isinstance(n, dict):
- node_id = n.get("node_id", "")
- ntype = n.get("node_type", "")
- edge_type = n.get("edge_type", "related_to")
+ node_id = n.get("id", "")
+ ntype = n.get("type", "")
+ edge_type = n.get("relationship", "related_to")
lines.append(
f"- {entity} --[{edge_type}]--> {node_id}"
+ (f" ({ntype})" if ntype else "")
diff --git a/tests/integrations/agno/test_kg_toolkit.py b/tests/integrations/agno/test_kg_toolkit.py
index d9dcdbfc..b9e1a40b 100644
--- a/tests/integrations/agno/test_kg_toolkit.py
+++ b/tests/integrations/agno/test_kg_toolkit.py
@@ -79,28 +79,26 @@ class _FakeRelExtractor:
class _FakeReasoner:
def infer_facts(self, facts, rules):
- result = MagicMock()
- result.inferred_facts = ["Human(EthicalAI)"]
- return result
+ return ["Human(EthicalAI)"]
class _FakeGraph:
"""Fake ContextGraph whose signatures match the real ContextGraph API."""
def __init__(self):
- self._node_store: dict = {} # node_id -> {"node_id": ..., "node_type": ...}
+ self._node_store: dict = {}
self._edge_store: list = []
# ContextGraph.find_nodes(node_type=None) -> List[Dict]
def find_nodes(self, node_type=None):
nodes = list(self._node_store.values())
if node_type:
- nodes = [n for n in nodes if n.get("node_type") == node_type]
+ nodes = [n for n in nodes if n.get("type") == node_type]
return nodes
# ContextGraph.add_node(node_id, node_type, content=None, **props) -> bool
def add_node(self, node_id, node_type="Entity", content=None, **props):
- self._node_store[node_id] = {"node_id": node_id, "node_type": node_type}
+ self._node_store[node_id] = {"id": node_id, "type": node_type}
return True
# ContextGraph.add_edge(source_id, target_id, edge_type, **props) -> bool
@@ -110,7 +108,7 @@ class _FakeGraph:
# ContextGraph.get_neighbors(node_id, hops=1, ...) -> List[Dict]
def get_neighbors(self, node_id, hops=1, relationship_types=None, min_weight=0.0):
- return [{"node_id": f"Neighbour_of_{node_id}", "node_type": "Entity"}]
+ return [{"id": f"Neighbour_of_{node_id}", "type": "Entity", "relationship": "related_to"}]
class TestAgnoKGToolkitInit(unittest.TestCase):
diff --git a/tests/integrations/agno/test_real_context_graph.py b/tests/integrations/agno/test_real_context_graph.py
new file mode 100644
index 00000000..37d7c069
--- /dev/null
+++ b/tests/integrations/agno/test_real_context_graph.py
@@ -0,0 +1,60 @@
+"""AgnoKGToolkit and AgnoKnowledgeGraph read what ContextGraph returns (#1726)."""
+
+import json
+
+import pytest
+
+from integrations.agno.kg_toolkit import AgnoKGToolkit
+from integrations.agno.knowledge_graph import AgnoKnowledgeGraph
+from semantica.context import ContextGraph
+
+
+def graph():
+ graph = ContextGraph()
+ graph.add_node("Alice", "Person", content="Alice Smith")
+ graph.add_node("Acme", "Organization", content="Acme Corp")
+ graph.add_edge("Alice", "Acme", "WORKS_AT")
+ return graph
+
+
+def toolkit(graph):
+ return AgnoKGToolkit(context=graph)
+
+
+def test_query_graph_matches_node_ids(toolkit):
+ result = json.loads(toolkit.query_graph("Alice"))
+
+ assert result["results"] == [{"label": "Alice", "type": "Person", "id": "Alice"}]
+
+
+def test_find_related_returns_neighbors(toolkit):
+ result = json.loads(toolkit.find_related("Alice"))
+
+ assert result["related"] == ["Acme"]
+
+
+def test_infer_facts_derives_facts_from_graph_nodes(toolkit):
+ result = json.loads(toolkit.infer_facts(json.dumps(["IF Person(?x) THEN Human(?x)"])))
+
+ assert result["inferred_facts"] == ["Human(Alice)"]
+
+
+def test_export_subgraph_serializes_the_graph(toolkit):
+ result = json.loads(toolkit.export_subgraph())
+
+ assert result["format"] == "json-ld"
+ assert "Alice" in result["data"]
+ assert "WORKS_AT" in result["data"]
+
+
+def test_graph_context_names_the_edge_and_neighbor(graph):
+ knowledge = AgnoKnowledgeGraph(context_graph=graph)
+
+ assert knowledge.get_graph_context("Alice") == (
+ "Entity: Alice\n --[WORKS_AT]--> Acme (type: Organization)"
+ )
+ assert knowledge._graph_context_for(["Alice"]) == (
+ "- Alice --[WORKS_AT]--> Acme (Organization)"
+ )