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
docs(cookbook): preserve complete semantic layer RDF
taochec20a46f02676
diff --git a/cookbook/introduction/26_Semantic_Layer_Basics.ipynb b/cookbook/introduction/26_Semantic_Layer_Basics.ipynbindex 13a5683f..05419411 100644--- a/cookbook/introduction/26_Semantic_Layer_Basics.ipynb+++ b/cookbook/introduction/26_Semantic_Layer_Basics.ipynb@@ -98,7 +98,7 @@"source": ["## Step 2: Generate a Starter Ontology\n","\n",- "`OntologyGenerator` infers OWL classes and properties from the graph. Two settings matter here:\n",+ "`OntologyGenerator` infers OWL classes and properties from graph records. Because `GraphBuilder` keeps business attributes inside each entity's `properties` dictionary while ontology inference reads record fields, we first create a flat **inference view**. The knowledge graph itself remains unchanged. Two settings matter here:\n","\n","- `base_uri` puts every generated term in *your* namespace\n","- `min_occurrences=1` includes classes that occur only once (the default of 2 would drop `Organization` and `Project` from this tiny demo graph)\n",@@ -114,18 +114,40 @@"\n","BASE_URI = \"https://example.org/company/\"\n","\n",+ "# Adapt the property-graph representation to the record shape consumed by\n",+ "# OntologyGenerator, so age/role/founded/status become declared properties.\n",+ "ontology_input = {\n",+ " \"entities\": [\n",+ " {\n",+ " **{key: value for key, value in entity.items() if key != \"properties\"},\n",+ " **entity.get(\"properties\", {}),\n",+ " }\n",+ " for entity in knowledge_graph[\"entities\"]\n",+ " ],\n",+ " \"relationships\": knowledge_graph[\"relationships\"],\n",+ "}\n",+ "\n","generator = OntologyGenerator(base_uri=BASE_URI, min_occurrences=1)\n",- "ontology = generator.generate_from_graph(knowledge_graph)\n",+ "ontology = generator.generate_from_graph(ontology_input)\n",+ "\n",+ "# OntologyGenerator calls datatype properties `data`; TripletStore's public\n",+ "# ontology contract calls them `datatype`. Normalize that boundary explicitly.\n",+ "store_ontology = {\n",+ " **ontology,\n",+ " \"properties\": [\n",+ " {**prop, \"type\": \"datatype\" if prop[\"type\"] == \"data\" else prop[\"type\"]}\n",+ " for prop in ontology[\"properties\"]\n",+ " ],\n",+ "}\n","\n","print(\"Classes:\")\n","for ontology_class in ontology[\"classes\"]:\n"," print(f\" {ontology_class['name']:<14} {ontology_class['uri']}\")\n","\n",- "print(\"\\nObject properties:\")\n",+ "print(\"\\nProperties:\")\n","for prop in ontology[\"properties\"]:\n",- " if prop[\"type\"] == \"object\":\n",- " print(f\" {prop['name']:<14} {prop['uri']} \"\n",- " f\"(domain={prop['domain']}, range={prop['range']})\")\n",+ " print(f\" {prop['name']:<14} {prop['type']:<7} {prop['uri']} \"\n",+ " f\"(domain={prop['domain']}, range={prop['range']})\")\n","\n","assert len(ontology[\"classes\"]) == 3"],@@ -141,7 +163,7 @@"The heart of a semantic layer is the mapping contract: which source type, relationship, and property corresponds to which ontology term.\n","\n","- **Entity types** and **relationship types**: each generated class/property records the source name it was inferred from (`metadata[\"inferred_from\"]`), so the mapping is read off the ontology itself — no fragile name matching between `works_for` and `worksFor`.\n",- "- **Properties**: the entity's `name` maps to the ontology's generated `name` datatype property; the remaining property keys (`age`, `role`, `founded`, `status`) are mapped to terms minted explicitly in our namespace.\n"+ "- **Properties**: the flat inference view makes `name`, `age`, `role`, `founded`, and `status` real generated datatype properties. Every mapping therefore points to a term declared in the ontology — no URI is invented only at mapping time.\n"]},{@@ -165,13 +187,7 @@" if prop[\"type\"] != \"object\"\n","}\n","\n",- "property_mappings = {\n",- " \"name\": datatype_property_uris[\"name\"],\n",- " \"age\": BASE_URI + \"age\",\n",- " \"role\": BASE_URI + \"role\",\n",- " \"founded\": BASE_URI + \"founded\",\n",- " \"status\": BASE_URI + \"status\",\n",- "}\n",+ "property_mappings = datatype_property_uris\n","\n","semantic_layer = {\n"," \"graph\": knowledge_graph,\n",@@ -190,7 +206,9 @@"\n","# Every type and relationship in the graph must have an ontology term\n","assert set(entity_type_mappings) == {entity[\"type\"] for entity in entities}\n",- "assert set(relationship_type_mappings) == {rel[\"type\"] for rel in relationships}"+ "assert set(relationship_type_mappings) == {rel[\"type\"] for rel in relationships}\n",+ "assert set(property_mappings) == {\"name\", \"age\", \"role\", \"founded\", \"status\"}\n",+ "assert set(property_mappings.values()) <= {prop[\"uri\"] for prop in ontology[\"properties\"]}"],"execution_count": null,"outputs": []@@ -246,29 +264,54 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 5: Export Ontology-Aligned RDF\n",- "\n",- "`RDFExporter` writes the aligned graph as Turtle. Entity types (`rdf:type`) and relationship predicates now use the ontology URIs.\n",+ "## Step 5: Store and Export Complete Ontology-Aligned RDF\n","\n",- "> [!NOTE]\n",- "> The file exporter serializes a compact projection of each entity (name and confidence); the complete property triples are produced by the triplet store in Step 6.\n"+ "`TripletStore.store()` materializes both the ontology declarations and the aligned instance graph. We then read those triples through the store's public API and serialize that complete RDF graph as Turtle. This avoids the compact `RDFExporter` entity projection, which does not include arbitrary entries from an entity's `properties` dictionary.\n"]},{"cell_type": "code","metadata": {},"source": [- "from semantica.export import RDFExporter\n",+ "from rdflib import Graph, Literal, URIRef\n",+ "from rdflib.namespace import OWL, RDF\n",+ "from semantica.triplet_store import TripletStore\n","\n",- "exporter = RDFExporter()\n",- "exporter.export(aligned_graph, \"semantic_layer.ttl\", format=\"turtle\")\n",+ "store = TripletStore(backend=\"oxigraph\")\n",+ "result = store.store(aligned_graph, store_ontology)\n",+ "print(f\"Stored triples: {result['processed']} (failed: {result['failed']})\")\n","\n",- "turtle = open(\"semantic_layer.ttl\").read()\n",+ "rdf_graph = Graph()\n",+ "for triplet in store.get_triplets():\n",+ " datatype = triplet.metadata.get(\"datatype\")\n",+ " if datatype:\n",+ " object_term = Literal(triplet.object, datatype=URIRef(datatype))\n",+ " elif triplet.object.startswith((\"http://\", \"https://\", \"urn:\")):\n",+ " object_term = URIRef(triplet.object)\n",+ " else:\n",+ " object_term = Literal(triplet.object)\n",+ " rdf_graph.add((URIRef(triplet.subject), URIRef(triplet.predicate), object_term))\n",+ "\n",+ "rdf_graph.serialize(destination=\"semantic_layer.ttl\", format=\"turtle\")\n",+ "turtle = open(\"semantic_layer.ttl\", encoding=\"utf-8\").read()\n","print(turtle[:600])\n","\n",- "# The RDF reflects the ontology mappings, not the raw source labels\n",- "assert BASE_URI + \"Person\" in turtle\n",- "assert BASE_URI + \"worksFor\" in turtle\n",+ "# The exported RDF contains declarations plus mapped instance facts.\n",+ "declared_datatype_properties = {\n",+ " str(subject) for subject in rdf_graph.subjects(RDF.type, OWL.DatatypeProperty)\n",+ "}\n",+ "assert result[\"failed\"] == 0\n",+ "assert set(property_mappings.values()) <= declared_datatype_properties\n",+ "assert (\n",+ " URIRef(BASE_URI + \"e1\"),\n",+ " URIRef(property_mappings[\"role\"]),\n",+ " Literal(\"Engineer\"),\n",+ ") in rdf_graph\n",+ "assert (\n",+ " URIRef(BASE_URI + \"e1\"),\n",+ " URIRef(relationship_type_mappings[\"works_for\"]),\n",+ " URIRef(BASE_URI + \"e3\"),\n",+ ") in rdf_graph\n","print(\"... exported semantic_layer.ttl\")"],"execution_count": null,@@ -278,24 +321,19 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 6: Store and Query\n",+ "## Step 6: Query the Semantic Layer\n","\n",- "`TripletStore.store()` loads the aligned graph together with the ontology. The embedded Oxigraph backend runs in memory, so there is nothing to install or start beyond the `pip` extra. With the data in the store, a business question — *who works for Tech Corp, and in which role?* — becomes one small SPARQL query over the ontology's terms.\n"+ "The embedded Oxigraph backend runs in memory, so there is nothing to start beyond installing the `tripletstore-oxigraph` extra. The organization is constrained by its mapped `name` predicate; the query therefore means *Tech Corp*, rather than accidentally matching employees of every organization.\n"]},{"cell_type": "code","metadata": {},"source": [- "from semantica.triplet_store import TripletStore\n",- "\n",- "store = TripletStore(backend=\"oxigraph\")\n",- "result = store.store(aligned_graph, ontology)\n",- "print(f\"Stored triples: {result['processed']} (failed: {result['failed']})\")\n",- "\n","query = f\"\"\"\n","SELECT ?name ?role WHERE {{\n"," ?person <{BASE_URI}worksFor> ?org .\n",+ " ?org <{BASE_URI}name> \"Tech Corp\" .\n"," ?person <{BASE_URI}name> ?name .\n"," ?person <{BASE_URI}role> ?role .\n","}}\n",@@ -307,8 +345,10 @@"for binding in query_result.bindings:\n"," print(f\" {binding['name']['value']} — {binding['role']['value']}\")\n","\n",- "assert result[\"failed\"] == 0\n",- "assert len(query_result.bindings) == 2"+ "assert [(row[\"name\"][\"value\"], row[\"role\"][\"value\"]) for row in query_result.bindings] == [\n",+ " (\"Alice\", \"Engineer\"),\n",+ " (\"Bob\", \"Manager\"),\n",+ "]"],"execution_count": null,"outputs": []