API Reference
This document describes the programmatic interfaces available in MIF (specification 1.4.2). Script and schema paths are relative to a checkout of the MIF repository.
Scripts
yaml2jsonld.py
Converts MIF ontology YAML files to JSON-LD format for semantic web compatibility.
Location: scripts/yaml2jsonld.py
Usage
# Convert a single filepython scripts/yaml2jsonld.py <input.yaml> [output.jsonld]
# Convert every *.ontology.yaml under a directorypython scripts/yaml2jsonld.py --all --path <path-to-directory>Arguments
| Argument | Required | Description |
|---|---|---|
input |
Yes* | Input YAML file path |
output |
No | Output JSON-LD file path (default: same name with .jsonld extension) |
--all |
No | Convert every *.ontology.yaml file under --path |
--path |
No | Directory to scan with --all; see note below on the default |
*Required unless --all is specified.
Examples
# Basic conversionpython scripts/yaml2jsonld.py <path-to-ontology>.yaml# Output: <path-to-ontology>.jsonld
# Custom output pathpython scripts/yaml2jsonld.py <path-to-ontology>.yaml output/<name>.jsonld
# Batch conversion against an explicit corpus (e.g. a checked-out ontologies# repo, or the MIF repo's vendored public/ontologies/ after# vendor-ontologies.py runs)python scripts/yaml2jsonld.py --all --path <path-to-directory># Converts every *.ontology.yaml under that directory.
# Batch conversion with no --path falls back to the MIF repo's own ontologies/# directory, which no longer exists there -- ontology content is now# authored in the modeled-information-format/ontologies repo (ADR-018) --# so this always converts 0 files unless --path is given.python scripts/yaml2jsonld.py --allExit Codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Error (missing input, invalid YAML, etc.) |
Dependencies
- Python 3.10+
- PyYAML (
pip install pyyaml)
Python API
The yaml2jsonld.py script provides functions that can be imported and used programmatically.
Functions
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 fileoutput_path(Path, optional): Path for output file. Defaults to input path with.jsonldextension.
Returns: Path to created JSON-LD file
Raises:
FileNotFoundError: If input file doesn’t existValueError: If YAML file is empty or invalid
Example:
from pathlib import Pathfrom scripts.yaml2jsonld import convert_file
# Basic usageoutput = convert_file(Path("ontologies/my-ontology.yaml"))print(f"Created: {output}")
# Custom output pathoutput = convert_file( Path("ontologies/my-ontology.yaml"), Path("output/my-ontology.jsonld"))convert_all_ontologies() -> list
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}")yaml_to_jsonld(yaml_data) -> dict
Convert parsed YAML data to JSON-LD format.
Parameters:
yaml_data(dict): Parsed YAML ontology data
Returns: JSON-LD document as dictionary
Example:
import yamlfrom scripts.yaml2jsonld import yaml_to_jsonld
# Load YAML manuallywith open("ontologies/my-ontology.yaml") as f: yaml_data = yaml.safe_load(f)
# Convert to JSON-LDjsonld = yaml_to_jsonld(yaml_data)
# Use the resultprint(jsonld["@id"])print(jsonld["namespaces"])load_context() -> dict
Load the JSON-LD context file.
Returns: Context dictionary from schema/ontology/ontology.context.jsonld
Raises:
FileNotFoundError: If context file doesn’t exist
Transform Functions
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 namespacens_jsonld = transform_namespace("semantic", { "description": "Facts and concepts", "type_hint": "semantic", "children": { "decisions": {"description": "Decisions"} }})
# Transform an entity typeet_jsonld = transform_entity_type({ "name": "component", "base": "semantic", "description": "Software component", "traits": ["versioned"]})
# Transform a traittrait_jsonld = transform_trait("versioned", { "description": "Supports versioning", "fields": { "version": {"type": "string"} }})
# Transform a relationshiprel_jsonld = transform_relationship("implements", { "description": "Realizes a concept", "from": ["component"], "to": ["concept"], "symmetric": False})
# Transform a discovery patternpattern_jsonld = transform_discovery_pattern({ "content_pattern": r"\b(PostgreSQL|MySQL)\b", "suggest_entity": "technology"}, index=0)JSON-LD Context
The MIF JSON-LD context provides vocabulary mappings for semantic web compatibility.
Location: https://mif-spec.dev/schema/context.jsonld (schema/context.jsonld in the MIF repository)
Core Types
| Type | URI | Description |
|---|---|---|
Concept |
mif:Concept |
Concept document (the @type of every MIF concept) |
Memory |
mif:Memory |
Deprecated v0.1 alias of Concept |
Entity |
mif:Entity |
Named entity |
Relationship |
mif:Relationship |
Entity relationship |
EntityReference |
mif:EntityReference |
Reference to entity |
OntologyReference |
mif:OntologyReference |
Reference to ontology |
Citation |
mif:Citation |
Citation reference |
TemporalMetadata |
mif:TemporalMetadata |
Temporal data |
EmbeddingReference |
mif:EmbeddingReference |
Embedding reference |
Entity Types
| Type | URI |
|---|---|
Person |
mif:Person |
Organization |
mif:Organization |
Technology |
mif:Technology |
Concept |
mif:Concept |
File |
mif:File |
Properties
| Property | URI | Type |
|---|---|---|
content |
mif:content |
string |
conceptType |
mif:conceptType |
string (semantic, episodic, procedural) |
memoryType |
mif:memoryType |
string (deprecated alias of conceptType) |
namespace |
mif:namespace |
string |
created |
dc:created |
dateTime |
modified |
dc:modified |
dateTime |
ontology |
mif:ontology |
OntologyReference |
Using the Context
Reference the context in your JSON-LD documents:
{ "@context": "https://mif-spec.dev/schema/context.jsonld", "@type": "Concept", "@id": "urn:mif:550e8400-e29b-41d4-a716-446655440000", ...}Or extend with custom vocabulary:
{ "@context": [ "https://mif-spec.dev/schema/context.jsonld", { "myns": "https://example.com/ns/", "customField": "myns:customField" } ], "@type": "Concept", "customField": "value"}Validation API
JSON Schema Validation
Use the JSON schemas programmatically:
import jsonfrom pathlib import Path
from jsonschema import Draft202012Validator, FormatCheckerfrom referencing import Registry, Resource
# Run from a checkout of the MIF repository. Register every local schema by# its $id so relative $refs (e.g. ./definitions/entity-reference.schema.json)# resolve offline, and check formats such as date-time and uri.schemas = {p: json.loads(p.read_text()) for p in Path("schema").rglob("*.schema.json")}registry = Registry().with_resources( (s["$id"], Resource.from_contents(s)) for s in schemas.values())
def validator_for(path: str) -> Draft202012Validator: return Draft202012Validator( schemas[Path(path)], registry=registry, format_checker=FormatChecker() )
def is_valid(instance: dict, schema_path: str) -> bool: errors = list(validator_for(schema_path).iter_errors(instance)) for error in errors: print(f"Validation error: {error.message}") return not errors
def validate_mif_document(document: dict) -> bool: """Validate a MIF concept's JSON-LD projection.""" return is_valid(document, "schema/mif.schema.json")
def validate_citation(citation: dict) -> bool: """Validate a citation object.""" return is_valid(citation, "schema/citation.schema.json")
def validate_ontology(ontology: dict) -> bool: """Validate an ontology definition (parsed from YAML).""" return is_valid(ontology, "schema/ontology/ontology.schema.json")FormatChecker needs the optional format dependencies to enforce date-time
and uri (pip install "jsonschema[format]").
Using ajv (JavaScript/Node.js)
const Ajv2020 = require('ajv/dist/2020');const addFormats = require('ajv-formats');const fs = require('fs');const path = require('path');
const ajv = new Ajv2020({ allErrors: true });addFormats(ajv);
// Register the referenced definition schemas so $refs resolveconst defsDir = 'schema/definitions';for (const file of fs.readdirSync(defsDir)) { if (file.endsWith('.schema.json')) { ajv.addSchema(JSON.parse(fs.readFileSync(path.join(defsDir, file)))); }}
const validateMif = ajv.compile(JSON.parse(fs.readFileSync('schema/mif.schema.json')));const validateCitation = ajv.compile(JSON.parse(fs.readFileSync('schema/citation.schema.json')));
// Validate a derived JSON-LD projection (produced by scripts/mif_convert.py emit-jsonld).// Node reads .jsonld directly (unlike ajv-cli, which needs a .json file).const document = JSON.parse(fs.readFileSync('concept.jsonld'));if (!validateMif(document)) { console.log('MIF validation errors:', validateMif.errors);}
// Validate a citation objectconst citation = JSON.parse(fs.readFileSync('citation.json'));if (!validateCitation(citation)) { console.log('Citation validation errors:', validateCitation.errors);}Integration Examples
These helpers build a concept’s JSON-LD projection directly, for example when emitting MIF from another system. A concept’s canonical form is its Markdown file in an OKF bundle; for an existing bundle, derive the projection with python scripts/mif_convert.py emit-jsonld <bundle> --out-dir dist/jsonld instead of hand-building it.
Python: Creating MIF Concepts
import jsonimport uuidfrom datetime import datetime, timezone
def create_mif_concept( content: str, concept_type: str = "semantic", namespace: str = "_semantic/knowledge", tags: list = None, ontology: dict = None) -> dict: """Create the JSON-LD projection of a MIF concept.
Args: content: The concept content (Markdown body) concept_type: Base knowledge 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 concept_type is one of the base knowledge types valid_types = {"semantic", "episodic", "procedural"} if concept_type not in valid_types: raise ValueError(f"concept_type must be one of {valid_types}, got '{concept_type}'")
concept_id = str(uuid.uuid4())
mif = { "@context": "https://mif-spec.dev/schema/context.jsonld", "@type": "Concept", "@id": f"urn:mif:{concept_id}", "conceptType": concept_type, "content": content, "created": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "namespace": namespace }
if tags: mif["tags"] = tags
if ontology: mif["ontology"] = { "@type": "OntologyReference", **ontology }
return mif
# Usageconcept = create_mif_concept( content="User prefers dark mode for all applications.", concept_type="semantic", # Base knowledge type namespace="_semantic/preferences", # Specific categorization via namespace tags=["ui", "accessibility"], ontology={"id": "mif-base", "version": "1.0.0"})
print(json.dumps(concept, indent=2))JavaScript: Creating MIF Concepts
function createMifConcept(content, options = {}) { const { conceptType = 'semantic', // Base knowledge types: semantic, episodic, procedural namespace = '_semantic/knowledge', tags, ontology } = options;
// Validate the base knowledge type const validTypes = ['semantic', 'episodic', 'procedural']; if (!validTypes.includes(conceptType)) { throw new Error(`conceptType must be one of ${validTypes.join(', ')}, got '${conceptType}'`); }
const conceptId = crypto.randomUUID();
const mif = { '@context': 'https://mif-spec.dev/schema/context.jsonld', '@type': 'Concept', '@id': `urn:mif:${conceptId}`, conceptType, content, created: new Date().toISOString(), namespace };
if (tags) mif.tags = tags; if (ontology) { mif.ontology = { '@type': 'OntologyReference', ...ontology }; }
return mif;}
// Usageconst concept = createMifConcept( 'User prefers dark mode for all applications.', { conceptType: 'semantic', // Base knowledge type namespace: '_semantic/preferences', // Specific categorization via namespace tags: ['ui', 'accessibility'], ontology: { id: 'mif-base', version: '1.0.0' } });
console.log(JSON.stringify(concept, null, 2));Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
FileNotFoundError: Context file not found |
Missing ontology.context.jsonld |
Ensure schema files are present |
ValueError: Empty or invalid YAML file |
Malformed YAML | Check YAML syntax |
ValidationError: '@id' must match pattern |
Invalid URN | Use urn:mif:<uuid>, where <uuid> is the frontmatter id |
Debugging
Enable verbose output:
import logginglogging.basicConfig(level=logging.DEBUG)
# Now conversion will show detailed logsfrom scripts.yaml2jsonld import convert_fileconvert_file(Path("ontology.yaml"))Version Compatibility
| MIF Version | Python | Node.js | JSON Schema Draft |
|---|---|---|---|
| 1.4.x | 3.10+ | 22+ | 2020-12 |