Skip to content

API Reference

This document describes the programmatic interfaces available in MIF.

Converts MIF ontology YAML files to JSON-LD format for semantic web compatibility.

Location: scripts/yaml2jsonld.py

Terminal window
# Convert a single file
python scripts/yaml2jsonld.py <input.yaml> [output.jsonld]
# Convert all ontologies in ontologies/ directory
python scripts/yaml2jsonld.py --all
ArgumentRequiredDescription
inputYes*Input YAML file path
outputNoOutput JSON-LD file path (default: same name with .jsonld extension)
--allNoConvert all *.ontology.yaml files in ontologies/ directory

*Required unless --all is specified.

ontologies/mif-base.ontology.jsonld
# Basic conversion
python scripts/yaml2jsonld.py ontologies/mif-base.ontology.yaml
# Custom output path
python scripts/yaml2jsonld.py ontologies/mif-base.ontology.yaml output/mif-base.jsonld
# Batch conversion
python scripts/yaml2jsonld.py --all
# Converts all *.ontology.yaml files in ontologies/
CodeMeaning
0Success
1Error (missing input, invalid YAML, etc.)
  • Python 3.8+
  • PyYAML (pip install pyyaml)

The yaml2jsonld.py script provides functions that can be imported and used programmatically.

convert_file(input_path, output_path=None) -> Path

Section titled “convert_file(input_path, output_path=None) -> Path”

Convert a single YAML ontology file to JSON-LD.

Parameters:

  • input_path (Path): Path to input YAML file
  • output_path (Path, optional): Path for output file. Defaults to input path with .jsonld extension.

Returns: Path to created JSON-LD file

Raises:

  • FileNotFoundError: If input file doesn’t exist
  • ValueError: If YAML file is empty or invalid

Example:

from pathlib import Path
from scripts.yaml2jsonld import convert_file
# Basic usage
output = convert_file(Path("ontologies/my-ontology.yaml"))
print(f"Created: {output}")
# Custom output path
output = convert_file(
Path("ontologies/my-ontology.yaml"),
Path("output/my-ontology.jsonld")
)

Convert all ontology YAML files in the ontologies/ directory.

Returns: List of paths to created JSON-LD files

Example:

from scripts.yaml2jsonld import convert_all_ontologies
converted = convert_all_ontologies()
print(f"Converted {len(converted)} files")
for path in converted:
print(f" - {path}")

Convert parsed YAML data to JSON-LD format.

Parameters:

  • yaml_data (dict): Parsed YAML ontology data

Returns: JSON-LD document as dictionary

Example:

import yaml
from scripts.yaml2jsonld import yaml_to_jsonld
# Load YAML manually
with open("ontologies/my-ontology.yaml") as f:
yaml_data = yaml.safe_load(f)
# Convert to JSON-LD
jsonld = yaml_to_jsonld(yaml_data)
# Use the result
print(jsonld["@id"])
print(jsonld["namespaces"])

Load the JSON-LD context file.

Returns: Context dictionary from schema/ontology/ontology.context.jsonld

Raises:

  • FileNotFoundError: If context file doesn’t exist

Lower-level functions for transforming specific ontology elements:

from scripts.yaml2jsonld import (
transform_namespace,
transform_entity_type,
transform_trait,
transform_relationship,
transform_discovery_pattern
)
# Transform a namespace
ns_jsonld = transform_namespace("semantic", {
"description": "Facts and concepts",
"type_hint": "semantic",
"children": {
"decisions": {"description": "Decisions"}
}
})
# Transform an entity type
et_jsonld = transform_entity_type({
"name": "component",
"base": "semantic",
"description": "Software component",
"traits": ["versioned"]
})
# Transform a trait
trait_jsonld = transform_trait("versioned", {
"description": "Supports versioning",
"fields": {
"version": {"type": "string"}
}
})
# Transform a relationship
rel_jsonld = transform_relationship("implements", {
"description": "Realizes a concept",
"from": ["component"],
"to": ["concept"],
"symmetric": False
})
# Transform a discovery pattern
pattern_jsonld = transform_discovery_pattern({
"content_pattern": r"\b(PostgreSQL|MySQL)\b",
"suggest_entity": "technology"
}, index=0)

The MIF JSON-LD context provides vocabulary mappings for semantic web compatibility.

Location: schema/ontology/ontology.context.jsonld

TypeURIDescription
Memorymif:MemoryMemory document
Entitymif:EntityNamed entity
Relationshipmif:RelationshipEntity relationship
EntityReferencemif:EntityReferenceReference to entity
OntologyReferencemif:OntologyReferenceReference to ontology
Citationmif:CitationCitation reference
TemporalMetadatamif:TemporalMetadataTemporal data
EmbeddingReferencemif:EmbeddingReferenceEmbedding reference
TypeURI
Personmif:Person
Organizationmif:Organization
Technologymif:Technology
Conceptmif:Concept
Filemif:File
PropertyURIType
contentmif:contentstring
memoryTypemif:memoryTypestring
namespacemif:namespacestring
createddc:createddateTime
modifieddc:modifieddateTime
ontologymif:ontologyOntologyReference

Reference the context in your JSON-LD documents:

{
"@context": "https://mif-spec.dev/schema/context.jsonld",
"@type": "Memory",
"@id": "urn:mif:my-memory",
...
}

Or extend with custom vocabulary:

{
"@context": [
"https://mif-spec.dev/schema/context.jsonld",
{
"myns": "https://example.com/ns/",
"customField": "myns:customField"
}
],
"@type": "Memory",
"customField": "value"
}

Use the JSON schemas programmatically:

import json
import jsonschema
from pathlib import Path
def validate_mif_document(document: dict) -> bool:
"""Validate a MIF document against the schema."""
schema_path = Path("schema/mif.schema.json")
with open(schema_path) as f:
schema = json.load(f)
try:
jsonschema.validate(document, schema)
return True
except jsonschema.ValidationError as e:
print(f"Validation error: {e.message}")
return False
def validate_citation(citation: dict) -> bool:
"""Validate a citation object."""
schema_path = Path("schema/citation.schema.json")
with open(schema_path) as f:
schema = json.load(f)
try:
jsonschema.validate(citation, schema)
return True
except jsonschema.ValidationError as e:
print(f"Validation error: {e.message}")
return False
def validate_ontology(ontology: dict) -> bool:
"""Validate an ontology definition."""
schema_path = Path("schema/ontology/ontology.schema.json")
with open(schema_path) as f:
schema = json.load(f)
try:
jsonschema.validate(ontology, schema)
return True
except jsonschema.ValidationError as e:
print(f"Validation error: {e.message}")
return False
const Ajv = require('ajv');
const fs = require('fs');
const ajv = new Ajv({ allErrors: true });
// Load schemas
const mifSchema = JSON.parse(fs.readFileSync('schema/mif.schema.json'));
const citationSchema = JSON.parse(fs.readFileSync('schema/citation.schema.json'));
// Compile validators
const validateMif = ajv.compile(mifSchema);
const validateCitation = ajv.compile(citationSchema);
// Validate a document
const document = JSON.parse(fs.readFileSync('memory.json'));
const valid = validateMif(document);
if (!valid) {
console.log('Validation errors:', validateMif.errors);
}

import json
import uuid
from datetime import datetime
def create_mif_memory(
content: str,
memory_type: str = "semantic",
namespace: str = "_semantic/knowledge",
tags: list = None,
ontology: dict = None
) -> dict:
"""Create a valid MIF memory document.
Args:
content: The memory content text
memory_type: Base memory type - "semantic", "episodic", or "procedural"
namespace: Hierarchical scope (e.g., "_semantic/decisions", "_episodic/sessions")
tags: Classification tags
ontology: Optional ontology reference dict with "id" and optional "version"
Returns:
A valid MIF document as a dictionary
"""
# Validate memory_type is base memory types
valid_types = {"semantic", "episodic", "procedural"}
if memory_type not in valid_types:
raise ValueError(f"memory_type must be one of {valid_types}, got '{memory_type}'")
memory_id = str(uuid.uuid4())
mif = {
"@context": "https://mif-spec.dev/schema/context.jsonld",
"@type": "Memory",
"@id": f"urn:mif:{memory_id}",
"memoryType": memory_type,
"content": content,
"created": datetime.utcnow().isoformat() + "Z",
"namespace": namespace
}
if tags:
mif["tags"] = tags
if ontology:
mif["ontology"] = {
"@type": "OntologyReference",
**ontology
}
return mif
# Usage
memory = create_mif_memory(
content="User prefers dark mode for all applications.",
memory_type="semantic", # Base memory type
namespace="_semantic/preferences", # Specific categorization via namespace
tags=["ui", "accessibility"],
ontology={"id": "mif-base", "version": "1.0.0"}
)
print(json.dumps(memory, indent=2))
function createMifMemory(content, options = {}) {
const {
memoryType = 'semantic', // Base types: semantic, episodic, procedural
namespace = '_semantic/knowledge',
tags,
ontology
} = options;
// Validate memory type
const validTypes = ['semantic', 'episodic', 'procedural'];
if (!validTypes.includes(memoryType)) {
throw new Error(`memoryType must be one of ${validTypes.join(', ')}, got '${memoryType}'`);
}
const memoryId = crypto.randomUUID();
const mif = {
'@context': 'https://mif-spec.dev/schema/context.jsonld',
'@type': 'Memory',
'@id': `urn:mif:${memoryId}`,
memoryType,
content,
created: new Date().toISOString(),
namespace
};
if (tags) mif.tags = tags;
if (ontology) {
mif.ontology = {
'@type': 'OntologyReference',
...ontology
};
}
return mif;
}
// Usage
const memory = createMifMemory(
'User prefers dark mode for all applications.',
{
memoryType: 'semantic', // Base memory type
namespace: '_semantic/preferences', // Specific categorization via namespace
tags: ['ui', 'accessibility'],
ontology: { id: 'mif-base', version: '1.0.0' }
}
);
console.log(JSON.stringify(memory, null, 2));

ErrorCauseSolution
FileNotFoundError: Context file not foundMissing ontology.context.jsonldEnsure schema files are present
ValueError: Empty or invalid YAML fileMalformed YAMLCheck YAML syntax
ValidationError: '@id' must match patternInvalid URNUse urn:mif: prefix

Enable verbose output:

import logging
logging.basicConfig(level=logging.DEBUG)
# Now conversion will show detailed logs
from scripts.yaml2jsonld import convert_file
convert_file(Path("ontology.yaml"))

MIF VersionPythonNode.jsJSON Schema Draft
0.1.x3.8+16+2020-12