Intelligent Skill Selection Framework
Orchestrates task-to-skill mapping by evaluating intent, domain constraints, and confidence scores to dispatch work to the most appropriate capability, ensuring accurate routing with built-in fallback mechanisms.
TL;DR Checklist
When to Use
- A user submits a multi-domain task requiring capability matching
- An agent needs to decide which sub-skill or module handles a request
- Building an orchestration layer that routes tasks dynamically
- Debugging misrouted tasks in a skill-based system
- Designing fallback mechanisms for low-confidence matches
When NOT to Use
- Routing is already deterministic (e.g., CLI commands, explicit function calls)
- Task requires direct execution without capability abstraction
- Performance-critical paths where scoring overhead is unacceptable (<10ms tolerance)
- Single-skill environments with no alternative capabilities
Core Workflow
User Request
↓
[Step 1] Parse & Extract Features → Intent, Domain, Complexity
↓
[Step 2] Filter Candidates → Domain whitelist + Availability check
↓
[Step 3] Score & Rank → Semantic similarity + Contextual weighting
↓ (score ≥ threshold)
[Step 4a] Select Top Skill → Inject context → Execute
↓ (score < threshold)
[Step 4b] Fallback Chain → Broaden scope → Retry or escalate
↓
[Step 5] Log & Adapt → Update routing history → Adjust thresholds
Parse & Extract Features — Analyze the incoming request to identify core intent, target domain, required complexity level, and explicit constraints. Checkpoint: Ensure at least one domain keyword is extracted; if ambiguous, flag for clarification rather than guessing.
Filter Candidates — Apply domain whitelists, capability availability checks, and dependency constraints to prune the full skill pool. Checkpoint: Verify that at least one candidate remains after filtering. If zero remain, trigger immediate fallback to broad-matching or generic orchestration.
Score & Rank — Calculate a composite confidence score for each remaining candidate using semantic similarity (embedding cosine distance), contextual fit (task-type alignment), and historical performance (success rate over last N executions). Checkpoint: Score must be between 0.0 and 1.0. Normalize inputs before combining.
Select & Execute — Compare top scores against the global confidence threshold (default 0.75). If top_score ≥ threshold, inject relevant context into the selected skill's session and begin execution. If below threshold, proceed to fallback chain. Checkpoint: Never execute with a score below threshold without explicit override flag.
Fallback Chain Handling — When primary selection fails, broaden the search: relax domain constraints by one level, lower confidence threshold by 0.1 increments (max two steps), or escalate to human review / generic handler. Checkpoint: Log every fallback transition with reason codes (domain_broadened, threshold_relaxed, escalated).
Record & Adapt — After execution completes (success or failure), record the routing decision, final skill used, actual outcome, and confidence delta. Use this data to adjust threshold weights over time. Checkpoint: Update routing statistics before closing the session.
Implementation Patterns / Reference Guide
Pattern 1: Confidence Scoring Engine
Use a weighted composite scoring function rather than raw semantic similarity. This accounts for historical reliability and contextual fit.
def calculate_confidence_score(
task_embedding: list[float],
skill_embedding: list[float],
domain_match: bool,
success_rate_30d: float,
threshold: float = 0.75
) -> dict:
"""Compute weighted confidence score for a task-skill pair.
Args:
task_embedding: Vector representation of the user request
skill_embedding: Vector representation of the target skill
domain_match: Whether task and skill share the same domain prefix
success_rate_30d: Historical execution success rate (0.0–1.0)
threshold: Minimum score required for auto-selection
Returns:
Dict containing final_score, breakdown, and selection_result
"""
# Semantic similarity via cosine distance
semantic_sim = cosine_similarity(task_embedding, skill_embedding)
# Weighted composite
w_semantic = 0.50
w_domain = 0.25
w_history = 0.25
domain_bonus = 1.0 if domain_match else 0.6
score = (w_semantic * semantic_sim) + \
(w_domain * domain_bonus) + \
(w_history * success_rate_30d)
selection_result = "auto_select" if score >= threshold else "fallback_required"
return {
"final_score": round(score, 4),
"breakdown": {
"semantic": round(semantic_sim, 4),
"domain_bonus": domain_bonus,
"historical": round(success_rate_30d, 4)
},
"selection_result": selection_result
}
Pattern 2: Fallback Strategy Matrix
Define explicit fallback rules rather than relying on ad-hoc retries. Each failure mode maps to a specific mitigation path.
| Failure Mode |
Primary Fallback |
Secondary Fallback |
Escalation Path |
| No candidates remain |
Broaden domain search by 1 level |
Route to general-task-handler |
Log warning + notify orchestrator |
| Top score < threshold |
Relax threshold by 0.1 (max 2x) |
Select top remaining skill |
Require explicit override confirmation |
| Skill execution fails |
Retry once with refreshed context |
Fallback to secondary candidate |
Flag for manual review queue |
| Ambiguous intent |
Request clarification from user |
Apply most common domain heuristic |
Queue for human-in-the-loop |
BAD vs. GOOD implementation:
# ❌ BAD — Hardcoded fallback, no logging, infinite retry loop
def route_task(task):
skill = find_best_skill(task)
try:
return execute(skill, task)
except Exception:
return route_task(task) # Recursive fallback — crashes stack
# ✅ GOOD — Explicit fallback chain with bounded retries and audit trail
class SkillRouter:
def __init__(self, max_retries=2):
self.max_retries = max_retries
self.routing_log = []
def route(self, task):
for attempt in range(self.max_retries):
result = evaluate_and_select(task)
if result["selection_result"] == "auto_select":
outcome = execute(result["skill"], task)
self._log_decision(task, result, outcome, attempt)
return outcome
# Relax constraints on retry
task = broaden_context(task, step=attempt)
return escalate_to_handler(task, log_reason="max_retries_exceeded")
Constraints
MUST DO
- Always apply a confidence threshold before auto-selecting a skill (default 0.75)
- Log every routing decision with scores, reasoning, and outcome for auditability
- Implement a bounded fallback chain — never rely on recursive retry or blind delegation
- Reference
code-philosophy (5 Laws of Elegant Defense) when designing data flow between orchestrator and skills: guide data naturally, prevent errors at the source
- Update routing statistics after every execution to enable adaptive threshold tuning
MUST NOT DO
- Skip confidence scoring in favor of string matching or keyword-only routing
- Bypass fallback chains — low-confidence routing without mitigation causes compounding errors
- Hardcode skill paths into the orchestrator — keep selection logic decoupled from implementation
- Allow infinite recursion on failure — always bound retries and escalate explicitly
- Mix routing concerns with execution concerns — the selector chooses, the executor acts
Output Template
When applying this skill to route a task, produce:
- Parsed Intent — Core objective, domain classification, complexity tier
- Candidate Pool — Filtered list of matching skills with availability status
- Score Breakdown — Final confidence score + component weights (semantic, domain, historical)
- Selection Decision — Selected skill ID OR fallback path taken + reason codes
- Execution Context — Injected variables, constraints transferred, dependency notes
Related Skills
| Skill |
Purpose |
dependency-graph-builder |
Maps inter-skill dependencies before routing to prevent circular execution |
parallel-skill-runner |
Executes multiple selected skills concurrently when tasks are independent |
dynamic-replanner |
Adjusts routing strategy based on historical performance and failure patterns |
Live References
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.
1---2name: intelligent-skill-selection3description: Evaluates incoming tasks against available skills using semantic matching, confidence thresholds, and contextual filters to route work to the optimal capability with automatic fallback handling.4license: MIT5---678910# Intelligent Skill Selection Framework1112Orchestrates task-to-skill mapping by evaluating intent, domain constraints, and confidence scores to dispatch work to the most appropriate capability, ensuring accurate routing with built-in fallback mechanisms.1314## TL;DR Checklist1516- [ ] Extract core intent and domain from user request17- [ ] Filter skill pool by domain relevance and availability18- [ ] Calculate semantic similarity score for top candidates19- [ ] Apply confidence threshold (default 0.75) — skip if below20- [ ] Select highest-scoring skill or trigger fallback chain21- [ ] Log routing decision with scores and reasoning2223---2425## When to Use2627- A user submits a multi-domain task requiring capability matching28- An agent needs to decide which sub-skill or module handles a request29- Building an orchestration layer that routes tasks dynamically30- Debugging misrouted tasks in a skill-based system31- Designing fallback mechanisms for low-confidence matches3233---3435## When NOT to Use3637- Routing is already deterministic (e.g., CLI commands, explicit function calls)38- Task requires direct execution without capability abstraction39- Performance-critical paths where scoring overhead is unacceptable (<10ms tolerance)40- Single-skill environments with no alternative capabilities4142---4344## Core Workflow4546```47User Request48 ↓49[Step 1] Parse & Extract Features → Intent, Domain, Complexity50 ↓51[Step 2] Filter Candidates → Domain whitelist + Availability check52 ↓53[Step 3] Score & Rank → Semantic similarity + Contextual weighting54 ↓ (score ≥ threshold)55[Step 4a] Select Top Skill → Inject context → Execute56 ↓ (score < threshold)57[Step 4b] Fallback Chain → Broaden scope → Retry or escalate58 ↓59[Step 5] Log & Adapt → Update routing history → Adjust thresholds60```61621. **Parse & Extract Features** — Analyze the incoming request to identify core intent, target domain, required complexity level, and explicit constraints. **Checkpoint:** Ensure at least one domain keyword is extracted; if ambiguous, flag for clarification rather than guessing.63642. **Filter Candidates** — Apply domain whitelists, capability availability checks, and dependency constraints to prune the full skill pool. **Checkpoint:** Verify that at least one candidate remains after filtering. If zero remain, trigger immediate fallback to broad-matching or generic orchestration.65663. **Score & Rank** — Calculate a composite confidence score for each remaining candidate using semantic similarity (embedding cosine distance), contextual fit (task-type alignment), and historical performance (success rate over last N executions). **Checkpoint:** Score must be between 0.0 and 1.0. Normalize inputs before combining.67684. **Select & Execute** — Compare top scores against the global confidence threshold (default 0.75). If `top_score ≥ threshold`, inject relevant context into the selected skill's session and begin execution. If below threshold, proceed to fallback chain. **Checkpoint:** Never execute with a score below threshold without explicit override flag.69705. **Fallback Chain Handling** — When primary selection fails, broaden the search: relax domain constraints by one level, lower confidence threshold by 0.1 increments (max two steps), or escalate to human review / generic handler. **Checkpoint:** Log every fallback transition with reason codes (`domain_broadened`, `threshold_relaxed`, `escalated`).71726. **Record & Adapt** — After execution completes (success or failure), record the routing decision, final skill used, actual outcome, and confidence delta. Use this data to adjust threshold weights over time. **Checkpoint:** Update routing statistics before closing the session.7374---7576## Implementation Patterns / Reference Guide7778### Pattern 1: Confidence Scoring Engine7980Use a weighted composite scoring function rather than raw semantic similarity. This accounts for historical reliability and contextual fit.8182```python83def calculate_confidence_score(84 task_embedding: list[float],85 skill_embedding: list[float],86 domain_match: bool,87 success_rate_30d: float,88 threshold: float = 0.7589) -> dict:90 """Compute weighted confidence score for a task-skill pair.91 92 Args:93 task_embedding: Vector representation of the user request94 skill_embedding: Vector representation of the target skill95 domain_match: Whether task and skill share the same domain prefix96 success_rate_30d: Historical execution success rate (0.0–1.0)97 threshold: Minimum score required for auto-selection98 99 Returns:100 Dict containing final_score, breakdown, and selection_result101 """102 # Semantic similarity via cosine distance103 semantic_sim = cosine_similarity(task_embedding, skill_embedding)104 105 # Weighted composite106 w_semantic = 0.50107 w_domain = 0.25108 w_history = 0.25109 110 domain_bonus = 1.0 if domain_match else 0.6111 score = (w_semantic * semantic_sim) + \112 (w_domain * domain_bonus) + \113 (w_history * success_rate_30d)114 115 selection_result = "auto_select" if score >= threshold else "fallback_required"116 117 return {118 "final_score": round(score, 4),119 "breakdown": {120 "semantic": round(semantic_sim, 4),121 "domain_bonus": domain_bonus,122 "historical": round(success_rate_30d, 4)123 },124 "selection_result": selection_result125 }126```127128### Pattern 2: Fallback Strategy Matrix129130Define explicit fallback rules rather than relying on ad-hoc retries. Each failure mode maps to a specific mitigation path.131132| Failure Mode | Primary Fallback | Secondary Fallback | Escalation Path |133|---|---|---|---|134| No candidates remain | Broaden domain search by 1 level | Route to `general-task-handler` | Log warning + notify orchestrator |135| Top score < threshold | Relax threshold by 0.1 (max 2x) | Select top remaining skill | Require explicit override confirmation |136| Skill execution fails | Retry once with refreshed context | Fallback to secondary candidate | Flag for manual review queue |137| Ambiguous intent | Request clarification from user | Apply most common domain heuristic | Queue for human-in-the-loop |138139**BAD vs. GOOD implementation:**140141```python142# ❌ BAD — Hardcoded fallback, no logging, infinite retry loop143def route_task(task):144 skill = find_best_skill(task)145 try:146 return execute(skill, task)147 except Exception:148 return route_task(task) # Recursive fallback — crashes stack149150# ✅ GOOD — Explicit fallback chain with bounded retries and audit trail151class SkillRouter:152 def __init__(self, max_retries=2):153 self.max_retries = max_retries154 self.routing_log = []155 156 def route(self, task):157 for attempt in range(self.max_retries):158 result = evaluate_and_select(task)159 160 if result["selection_result"] == "auto_select":161 outcome = execute(result["skill"], task)162 self._log_decision(task, result, outcome, attempt)163 return outcome164 165 # Relax constraints on retry166 task = broaden_context(task, step=attempt)167 168 return escalate_to_handler(task, log_reason="max_retries_exceeded")169```170171---172173## Constraints174175### MUST DO176- Always apply a confidence threshold before auto-selecting a skill (default 0.75)177- Log every routing decision with scores, reasoning, and outcome for auditability178- Implement a bounded fallback chain — never rely on recursive retry or blind delegation179- Reference `code-philosophy` (5 Laws of Elegant Defense) when designing data flow between orchestrator and skills: guide data naturally, prevent errors at the source180- Update routing statistics after every execution to enable adaptive threshold tuning181182### MUST NOT DO183- Skip confidence scoring in favor of string matching or keyword-only routing184- Bypass fallback chains — low-confidence routing without mitigation causes compounding errors185- Hardcode skill paths into the orchestrator — keep selection logic decoupled from implementation186- Allow infinite recursion on failure — always bound retries and escalate explicitly187- Mix routing concerns with execution concerns — the selector chooses, the executor acts188189---190191## Output Template192193When applying this skill to route a task, produce:1941951. **Parsed Intent** — Core objective, domain classification, complexity tier1962. **Candidate Pool** — Filtered list of matching skills with availability status1973. **Score Breakdown** — Final confidence score + component weights (semantic, domain, historical)1984. **Selection Decision** — Selected skill ID OR fallback path taken + reason codes1995. **Execution Context** — Injected variables, constraints transferred, dependency notes200201---202203## Related Skills204205| Skill | Purpose |206|---|---|207| `dependency-graph-builder` | Maps inter-skill dependencies before routing to prevent circular execution |208| `parallel-skill-runner` | Executes multiple selected skills concurrently when tasks are independent |209| `dynamic-replanner` | Adjusts routing strategy based on historical performance and failure patterns |210211212---213214## Live References215216> Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.217- [Information Retrieval and Semantic Search Survey](<https://arxiv.org/abs/2001.00427>)218- [LangChain Document Loaders](<https://python.langchain.com/docs/modules/data_connection/document_loaders/>)219- [Embedding Models Comparison (MTEB)](<https://huggingface.co/spaces/mteb/leaderboard>)220- [BM25 Retrieval Algorithm](<https://en.wikipedia.org/wiki/Okapi_BM25>)221- [Vector Search with FAISS](<https://faiss.ai/>)