How to Generate RDF Triplets from Text Using Semantica: A Complete Developer Guide
Semantica converts raw text into RDF-compatible subject-predicate-object triplets through a pipeline orchestrated by the TripletExtractor class and serialized via the RDFSerializer or RDFExporter classes.
Semantica is an open-source semantic extraction framework designed to bridge natural language processing and knowledge graph construction. This guide demonstrates how to generate RDF triplets from text using Semantica's architectural components, from pattern-based extraction to LLM-powered Relation Extraction (RE), based on the current implementation in the semantica-agi/semantica repository.
The RDF Triplet Generation Pipeline
Semantica implements a four-stage pipeline that transforms unstructured text into structured RDF data. The process moves through extraction orchestration, optional entity/relation preprocessing, triplet generation, and finally format-specific serialization.
Step 1: Initialize the TripletExtractor
The TripletExtractor class serves as the primary orchestrator. During initialization, it selects an extraction backend—pattern-based, rule-based, HuggingFace models, or LLM providers—and configures metadata enrichment options.
Key initialization parameters include:
method: Selects the extraction engine ("pattern","rule","huggingface", or"llm")include_temporal: Enriches triplets with OWL-Time timestamps for temporal reasoninginclude_provenance: Attaches source-sentence metadata for traceability
The constructor also instantiates a built-in RDFSerializer for immediate in-memory serialization, accessible via the rdf_serializer attribute.
Step 2: Extract Triplets from Text
Call the extract_triplets method to process raw text or batch documents. This method returns a List[Triplet] where each Triplet dataclass (defined in [semantica/semantic_extract/types.py](https://github.com/semantica-agi/semantica/blob/main/semantica/semantic_extract/types.py)) contains structured subject, predicate, and object fields.
You can optionally pass pre-computed entities and relations to bypass internal NER models, or let the extractor handle the entire pipeline end-to-end.
Step 3: Serialize to Standard RDF Formats
Semantica supports multiple W3C-standard serialization formats through two primary classes:
RDFSerializer: Handles in-memory conversion to Turtle, N-Triples, JSON-LD, or RDF/XML strings. The core implementation resides in [semantica/export/rdf_exporter.py](https://github.com/semantica-agi/semantica/blob/main/semantica/export/rdf_exporter.py#L315-L340).RDFExporter: Provides file-system persistence and optional RDF validation. Theexportmethod writes directly to disk while leveraging utilities from [semantica/utils/helpers.py](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/helpers.py) for stable IRI minting.
Practical Code Examples
Basic Pattern-Based Extraction
Use the default pattern-based method for fast, deterministic extraction without external API dependencies:
from semantica.semantic_extract import TripletExtractor
# Initialize with pattern-based extraction
extractor = TripletExtractor(method="pattern")
# Raw text input
sample_text = """
Alice founded Acme Corp in 2020. Bob works at Acme Corp.
"""
# Generate triplets
triplets = extractor.extract_triplets(sample_text)
# Serialize to Turtle format
turtle_output = extractor.rdf_serializer.serialize_to_turtle(triplets)
print(turtle_output)
LLM-Based Extraction with File Export
For complex relational extraction requiring semantic understanding, configure the LLM backend and export results directly to file:
from semantica.semantic_extract import TripletExtractor
from semantica.export import RDFExporter
# Configure LLM extraction with provenance tracking
extractor = TripletExtractor(
method="llm",
provider="openai",
llm_model="gpt-4",
include_provenance=True,
)
text = "The treaty was signed on 12-Jan-2022 by the United Nations."
triplets = extractor.extract_triplets(text)
# Export to Turtle file with validation
exporter = RDFExporter()
exporter.export(triplets, "output.ttl", format="turtle")
Batch Processing with Temporal Enrichment
Process multiple documents simultaneously while capturing temporal metadata using the OWL-Time ontology:
from semantica.semantic_extract import TripletExtractor
# Enable temporal extraction
extractor = TripletExtractor(
method="pattern",
include_temporal=True,
)
documents = [
"Event A happened yesterday.",
"Event B will occur tomorrow."
]
# Batch extraction returns List[List[Triplet]]
batch_results = extractor.extract_triplets(documents)
# Serialize each document separately
for idx, triplet_list in enumerate(batch_results):
turtle_data = extractor.rdf_serializer.serialize_to_turtle(triplet_list)
print(f"Document {idx} RDF:\n{turtle_data}")
Key Configuration Flags
Semantica provides granular control over triplet metadata through boolean flags passed to the TripletExtractor.__init__ method:
include_temporal=True: Parses temporal expressions and attaches OWL-Time compliant timestamps to relevant tripletsinclude_provenance=True: Records the source sentence and character offsets for each extracted triplet, enabling full audit trails
These flags propagate through the extraction pipeline and are respected by both the RDFSerializer and RDFExporter during output generation.
Summary
- TripletExtractor acts as the central orchestrator, supporting four distinct extraction methods (pattern, rule, HuggingFace, LLM)
- The extract_triplets method converts text or document batches into structured
Tripletobjects defined in the core types module - RDFSerializer provides in-memory serialization to Turtle, N-Triples, JSON-LD, and RDF/XML formats
- RDFExporter handles file persistence and optional RDF validation using helper utilities for IRI generation
- Configuration flags for temporal and provenance metadata enable semantic enrichment compatible with OWL-Time standards
Frequently Asked Questions
What RDF serialization formats does Semantica support?
Semantica supports W3C-standard formats including Turtle, N-Triples, JSON-LD, and RDF/XML. The RDFSerializer class provides dedicated methods such as serialize_to_turtle() and serialize_to_json_ld(), while the RDFExporter handles format detection via file extensions or explicit format parameters.
Can I use custom LLM providers for relation extraction?
Yes. When initializing TripletExtractor with method="llm", specify your provider through the provider parameter (e.g., "openai"). The architecture supports pluggable LLM backends, allowing integration with OpenAI, Anthropic, or local models via the unified interface defined in the extraction module.
How does Semantica handle temporal information in triplets?
When include_temporal=True is set during extractor initialization, Semantica parses temporal expressions in the source text and generates additional triplets using the OWL-Time ontology. These triplets link events to specific timestamps or temporal intervals, enabling time-aware querying in downstream knowledge graph applications.
What is the difference between RDFSerializer and RDFExporter?
RDFSerializer performs in-memory conversion of Triplet objects to RDF string representations suitable for immediate use in Python workflows. RDFExporter extends this functionality to the file system, handling directory creation (via [semantica/utils/helpers.py](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/helpers.py)), file I/O operations, and optional RDF validation before persistence.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →