Schema inference engine

From paulpas/agent-skill-router · View interactive version

Schema inference engine is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent schema inference engine with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Schema Inference Engine

Orchestrates intelligent skill selection and execution for schema inference engine workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

def infer_schema_from_sample(
    raw_data: List[Dict],
    source_metadata: Dict,
    min_confidence: float = 0.75
) -> Dict:
    """Infer schema fields from raw data samples with multi-factor scoring.
    
    Applies Law 1 (Early Exit) and Law 2 (Immutable State) to ensure
    only valid, well-typed fields are extracted. Returns a new schema dict.
    """
    if not raw_data or not isinstance(raw_data, list):
        raise ValueError("raw_data must be a non-empty list of records")
        
    inferred_fields = {}
    
    for record in raw_data:
        for key, value in record.items():
            if key not in inferred_fields:
                inferred_fields[key] = {
                    "name": key,
                    "type": _detect_type(value),
                    "nullable": False,
                    "sample_values": [],
                    "confidence": 0.0
                }
            
            inferred_fields[key]["sample_values"].append(value)
            inferred_fields[key]["nullable"] |= value is None
            
    # Calculate multi-factor confidence scores
    for field_name, field in inferred_fields.items():
        type_confidence = _calculate_type_confidence(field["sample_values"])
        consistency_score = _calculate_consistency(field["sample_values"])
        field["confidence"] = (type_confidence * 0.6) + (consistency_score * 0.4)
        
        if field["confidence"] < min_confidence:
            field["fallback_strategy"] = "human_review"
            
    # Law 3: Return new structure, never mutate input
    return {
        "schema_version": "1.0",
        "fields": list(inferred_fields.values()),
        "source": source_metadata.get("source_id"),
        "inference_timestamp": time.time()
    }

Pattern 2: Execution with Fallback

def resolve_schema_conflicts(
    primary_schema: Dict,
    secondary_schema: Dict,
    conflict_resolution_policy: str = "highest_confidence"
) -> Dict:
    """Merge two inferred schemas, resolving field conflicts via fallback chain.
    
    Implements Law 4 (Fail Fast) and fallback logic for ambiguous merges.
    """
    if not primary_schema or not secondary_schema:
        raise ValueError("Both schemas must be provided for merging")
        
    merged_fields = {f["name"]: dict(f) for f in primary_schema["fields"]}
    conflicts = []
    
    for field in secondary_schema["fields"]:
        if field["name"] in merged_fields:
            existing = merged_fields[field["name"]]
            if existing["type"] != field["type"]:
                # Fallback Chain: 1. Type coercion, 2. Union type, 3. Human review
                if _can_coerce(existing["type"], field["type"]):
                    existing["type"] = _coerce_type(existing["type"], field["type"])
                elif existing["confidence"] >= field["confidence"]:
                    conflicts.append({
                        "field": field["name"],
                        "action": "defer_to_human",
                        "reason": "type_mismatch_low_confidence"
                    })
                else:
                    merged_fields[field["name"]] = dict(field)
        else:
            merged_fields[field["name"]] = dict(field)
            
    # Law 3: Return new merged structure
    return {
        "merged_schema": list(merged_fields.values()),
        "conflicts": conflicts,
        "resolution_policy": conflict_resolution_policy,
        "audit_log": f"Merged {len(primary_schema['fields'])} + {len(secondary_schema['fields'])} fields"
    }

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios

Related Skills

| Skill | Purpose |

|---|---|

| nosql-data-modeling | Provides data modeling strategies that complement schema inference for non-relational databases |

| postgresql-optimization | Uses inferred schemas to generate optimized PostgreSQL queries and indexes |


Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.