Local LLM Router for Air-Gapped Networks
Intelligent routing of AI coding queries to local LLMs with Serena LSP integration for secure, offline-capable development environments.
Prerequisites (CRITICAL)
Before using this skill, ensure:
- Serena MCP Server installed and running (PRIMARY TOOL)
- At least one local LLM service running (Ollama, LM Studio, Jan, etc.)
# Install Serena (required)
pip install serena
# Or via uvx
uvx --from git+https://github.com/oraios/serena serena start-mcp-server
# Verify local LLM service
curl http://localhost:11434/api/version # Ollama
curl http://localhost:1234/v1/models # LM Studio
curl http://localhost:1337/v1/models # Jan
Quick Start
import httpx
import asyncio
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class TaskCategory(Enum):
CODING = "coding"
REASONING = "reasoning"
ANALYSIS = "analysis"
DOCUMENTATION = "documentation"
@dataclass
class RouterConfig:
"""Local LLM Router configuration."""
ollama_url: str = "http://localhost:11434"
lmstudio_url: str = "http://localhost:1234"
jan_url: str = "http://localhost:1337"
serena_enabled: bool = True
timeout: int = 30
async def quick_route(query: str, config: RouterConfig = RouterConfig()):
"""Quick routing example - detects services and routes query."""
# 1. Detect available services
services = await discover_services(config)
if not services:
raise RuntimeError("No local LLM services available")
# 2. Classify task
category = classify_task(query)
# 3. Select best model for task
model = select_model(category, services)
# 4. Execute query
return await execute_query(query, model, services[0])
# Example usage
async def main():
response = await quick_route("Write a function to parse JSON safely")
print(response)
asyncio.run(main())
Serena Integration (PRIMARY TOOL)
CRITICAL: Serena MCP MUST be invoked FIRST for all code-related tasks. This provides semantic understanding of the codebase before routing to an LLM.
Why Serena First?
- Token Efficiency: Serena extracts only relevant code context
- Accuracy: Symbol-level operations vs grep-style searches
- Codebase Awareness: Understands types, references, call hierarchies
- Edit Precision: Applies changes at symbol level, not string matching
Serena MCP Setup
import subprocess
import json
from typing import Any
class SerenaMCP:
"""Serena MCP client for code intelligence."""
def __init__(self, workspace_root: str):
self.workspace = workspace_root
self.process = None
async def start(self):
"""Start Serena MCP server."""
self.process = subprocess.Popen(
["serena", "start-mcp-server", "--workspace", self.workspace],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
async def call(self, method: str, params: dict) -> Any:
"""Call Serena MCP method."""
request = {
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params
}
self.process.stdin.write(json.dumps(request).encode() + b"\n")
self.process.stdin.flush()
response = self.process.stdout.readline()
return json.loads(response)
async def find_symbol(self, name: str) -> dict:
"""Find symbol definition by name."""
return await self.call("find_symbol", {"name": name})
async def get_references(self, file: str, line: int, char: int) -> list:
"""Get all references to symbol at position."""
return await self.call("get_references", {
"file": file,
"line": line,
"character": char
})
async def get_hover_info(self, file: str, line: int, char: int) -> dict:
"""Get type/documentation info at position."""
return await self.call("get_hover_info", {
"file": file,
"line": line,
"character": char
})
async def get_diagnostics(self, file: str) -> list:
"""Get errors/warnings for file."""
return await self.call("get_diagnostics", {"file": file})
async def apply_edit(self, file: str, edits: list) -> bool:
"""Apply code edits to file."""
return await self.call("apply_edit", {"file": file, "edits": edits})
# Serena tools by priority (always use higher priority first)
SERENA_TOOLS = {
# Priority 1: Symbol-level operations (highest)
"find_symbol": {"priority": 1, "use_for": ["navigation", "definition"]},
"get_references": {"priority": 1, "use_for": ["refactoring", "impact analysis"]},
"get_hover_info": {"priority": 1, "use_for": ["type info", "documentation"]},
# Priority 2: Code navigation
"go_to_definition": {"priority": 2, "use_for": ["navigation"]},
"go_to_type_definition": {"priority": 2, "use_for": ["type navigation"]},
"go_to_implementation": {"priority": 2, "use_for": ["interface impl"]},
# Priority 3: Code understanding
"get_document_symbols": {"priority": 3, "use_for": ["file structure"]},
"get_workspace_symbols": {"priority": 3, "use_for": ["codebase search"]},
"get_call_hierarchy": {"priority": 3, "use_for": ["call analysis"]},
# Priority 4: Code modification
"apply_edit": {"priority": 4, "use_for": ["editing"]},
"rename_symbol": {"priority": 4, "use_for": ["refactoring"]},
# Priority 5: Diagnostics
"get_diagnostics": {"priority": 5, "use_for": ["errors", "warnings"]},
"get_code_actions": {"priority": 5, "use_for": ["quick fixes"]},
}
Serena-First Request Handler
async def handle_code_request(
query: str,
file_context: Optional[dict] = None,
serena: SerenaMCP = None,
router: "LLMRouter" = None
):
"""
Handle code request with Serena-first pattern.
CRITICAL: Serena is ALWAYS invoked first for code tasks.
"""
# Step 1: Classify the task
category = classify_task(query)
# Step 2: ALWAYS use Serena for code context (if available)
serena_context = {}
if serena and file_context:
# Gather semantic context from Serena
if file_context.get("file") and file_context.get("position"):
file = file_context["file"]
line = file_context["position"]["line"]
char = file_context["position"]["character"]
# Get hover info (type, docs)
serena_context["hover"] = await serena.get_hover_info(file, line, char)
# For refactoring/analysis, get references
if category in [TaskCategory.ANALYSIS, TaskCategory.CODING]:
if "refactor" in query.lower() or "rename" in query.lower():
serena_context["references"] = await serena.get_references(
file, line, char
)
# Always get diagnostics for the file
serena_context["diagnostics"] = await serena.get_diagnostics(file)
# Step 3: Build enriched prompt with Serena context
enriched_query = build_enriched_query(query, serena_context)
# Step 4: Select and route to appropriate LLM
model = router.select_model(category)
response = await router.execute(enriched_query, model)
# Step 5: If response contains edits, apply via Serena
if serena and contains_code_edit(response):
edits = parse_code_edits(response)
await serena.apply_edit(file_context["file"], edits)
return response
def build_enriched_query(query: str, serena_context: dict) -> str:
"""Build query enriched with Serena context."""
parts = [query]
if serena_context.get("hover"):
hover = serena_context["hover"]
parts.append(f"\n## Type Information\n```\n{hover}\n```")
if serena_context.get("references"):
refs = serena_context["references"]
parts.append(f"\n## References ({len(refs)} found)\n")
for ref in refs[:10]: # Limit to first 10
parts.append(f"- {ref['file']}:{ref['line']}")
if serena_context.get("diagnostics"):
diags = serena_context["diagnostics"]
if diags:
parts.append(f"\n## Current Issues ({len(diags)})\n")
for diag in diags[:5]:
parts.append(f"- Line {diag['line']}: {diag['message']}")
return "\n".join(parts)
Service Discovery
Supported Services
| Service |
Default Endpoint |
Health Check |
Models Endpoint |
Chat Endpoint |
API Style |
| Ollama |
localhost:11434 |
/api/version |
/api/tags |
/api/chat |
Native |
| LM Studio |
localhost:1234 |
/v1/models |
/v1/models |
/v1/chat/completions |
OpenAI |
| Jan |
localhost:1337 |
/v1/models |
/v1/models |
/v1/chat/completions |
OpenAI |
| OpenWebUI |
localhost:3000 |
/api/health |
/api/models |
/api/chat |
Custom |
| LocalAI |
localhost:8080 |
/readyz |
/v1/models |
/v1/chat/completions |
OpenAI |
| vLLM |
localhost:8000 |
/health |
/v1/models |
/v1/chat/completions |
OpenAI |
| llama.cpp |
localhost:8080 |
/health |
/v1/models |
/v1/chat/completions |
OpenAI |
| Kobold.cpp |
localhost:5001 |
/api/v1/info |
/api/v1/models |
/api/v1/generate |
Custom |
| GPT4All |
localhost:4891 |
/v1/models |
/v1/models |
/v1/chat/completions |
OpenAI |
| text-generation-webui |
localhost:5000 |
/api/v1/model |
/api/v1/models |
/api/v1/chat |
Custom |
OS Detection
import sys
import os
import platform
from dataclasses import dataclass
@dataclass
class OSInfo:
platform: str # 'windows', 'linux', 'darwin'
release: str
arch: str # 'x64', 'arm64'
is_wsl: bool
is_container: bool
def detect_os() -> OSInfo:
"""Detect operating system and environment."""
plat = sys.platform
# Normalize platform name
if plat == 'win32':
plat = 'windows'
elif plat == 'darwin':
plat = 'darwin'
else:
plat = 'linux'
# WSL detection
is_wsl = False
if plat == 'linux':
try:
with open('/proc/version', 'r') as f:
is_wsl = 'microsoft' in f.read().lower()
except FileNotFoundError:
pass
is_wsl = is_wsl or os.environ.get('WSL_DISTRO_NAME') is not None
# Container detection
is_container = (
os.path.exists('/.dockerenv') or
os.environ.get('KUBERNETES_SERVICE_HOST') is not None
)
if not is_container and plat == 'linux':
try:
with open('/proc/1/cgroup', 'r') as f:
is_container = 'docker' in f.read() or 'kubepods' in f.read()
except FileNotFoundError:
pass
return OSInfo(
platform=plat,
release=platform.release(),
arch=platform.machine(),
is_wsl=is_wsl,
is_container=is_container
)
def adjust_endpoint_for_os(endpoint: str, os_info: OSInfo) -> str:
"""Adjust endpoint based on OS environment."""
if os_info.is_wsl or os_info.is_container:
# In WSL/containers, localhost services are on the host
return endpoint.replace('localhost', 'host.docker.internal')
return endpoint
Service Discovery Implementation
import httpx
import asyncio
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional
@dataclass
class DiscoveredModel:
id: str
name: str
size: int = 0
family: Optional[str] = None
context_length: int = 4096
quantization: Optional[str] = None
@dataclass
class LLMService:
name: str
type: str # 'ollama', 'lmstudio', 'jan', 'openwebui', 'custom'
endpoint: str
status: str = 'unknown' # 'online', 'offline', 'unknown'
models: list = field(default_factory=list)
last_checked: datetime = None
api_style: str = 'openai' # 'openai', 'native'
# Endpoint paths
health_path: str = '/v1/models'
models_path: str = '/v1/models'
chat_path: str = '/v1/chat/completions'
# Default service configurations
SERVICE_DEFAULTS = {
'ollama': LLMService(
name='Ollama',
type='ollama',
endpoint='http://localhost:11434',
health_path='/api/version',
models_path='/api/tags',
chat_path='/api/chat',
api_style='native'
),
'lmstudio': LLMService(
name='LM Studio',
type='lmstudio',
endpoint='http://localhost:1234',
health_path='/v1/models',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
'jan': LLMService(
name='Jan',
type='jan',
endpoint='http://localhost:1337',
health_path='/v1/models',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
'openwebui': LLMService(
name='Open WebUI',
type='openwebui',
endpoint='http://localhost:3000',
health_path='/api/health',
models_path='/api/models',
chat_path='/api/chat',
api_style='custom'
),
'localai': LLMService(
name='LocalAI',
type='localai',
endpoint='http://localhost:8080',
health_path='/readyz',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
'vllm': LLMService(
name='vLLM',
type='vllm',
endpoint='http://localhost:8000',
health_path='/health',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
'llamacpp': LLMService(
name='llama.cpp',
type='llamacpp',
endpoint='http://localhost:8080',
health_path='/health',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
'koboldcpp': LLMService(
name='Kobold.cpp',
type='koboldcpp',
endpoint='http://localhost:5001',
health_path='/api/v1/info',
models_path='/api/v1/model',
chat_path='/api/v1/generate',
api_style='custom'
),
'gpt4all': LLMService(
name='GPT4All',
type='gpt4all',
endpoint='http://localhost:4891',
health_path='/v1/models',
models_path='/v1/models',
chat_path='/v1/chat/completions',
api_style='openai'
),
}
class ServiceDiscovery:
"""Discover and monitor local LLM services."""
def __init__(self, custom_endpoints: list = None):
self.services: dict[str, LLMService] = {}
self.os_info = detect_os()
self.custom_endpoints = custom_endpoints or []
self._client = httpx.AsyncClient(timeout=5.0)
async def discover_all(self) -> list[LLMService]:
"""Discover all available LLM services."""
discovered = []
# Check default services
tasks = []
for key, default in SERVICE_DEFAULTS.items():
service = LLMService(
name=default.name,
type=default.type,
endpoint=adjust_endpoint_for_os(default.endpoint, self.os_info),
health_path=default.health_path,
models_path=default.models_path,
chat_path=default.chat_path,
api_style=default.api_style
)
tasks.append(self._check_service(service))
# Check custom endpoints
for custom in self.custom_endpoints:
service = LLMService(
name=custom.get('name', 'Custom'),
type='custom',
endpoint=custom['endpoint'],
health_path=custom.get('health_path', '/v1/models'),
models_path=custom.get('models_path', '/v1/models'),
chat_path=custom.get('chat_path', '/v1/chat/completions'),
api_style=custom.get('api_style', 'openai')
)
tasks.append(self._check_service(service))
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, LLMService) and result.status == 'online':
discovered.append(result)
self.services[result.type] = result
return discovered
async def _check_service(self, service: LLMService) -> LLMService:
"""Check if service is online and discover models."""
try:
# Health check
response = await self._client.get(
f"{service.endpoint}{service.health_path}"
)
if response.status_code == 200:
service.status = 'online'
service.last_checked = datetime.now()
# Discover models
service.models = await self._discover_models(service)
else:
service.status = 'offline'
except (httpx.ConnectError, httpx.TimeoutException):
service.status = 'offline'
return service
async def _discover_models(self, service: LLMService) -> list[DiscoveredModel]:
"""Discover available models on service."""
try:
response = await self._client.get(
f"{service.endpoint}{service.models_path}"
)
data = response.json()
# Parse based on service type
if service.type == 'ollama':
return [
DiscoveredModel(
id=m['name'],
name=m['name'],
size=m.get('size', 0),
family=m.get('details', {}).get('family'),
context_length=self._infer_context_length(m['name'])
)
for m in data.get('models', [])
]
else: # OpenAI-style
return [
DiscoveredModel(
id=m['id'],
name=m['id'],
context_length=m.get('context_length', 4096)
)
for m in data.get('data', [])
]
except Exception:
return []
def _infer_context_length(self, model_name: str) -> int:
"""Infer context length from model name."""
name_lower = model_name.lower()
# Check for explicit context markers
if '128k' in name_lower or '131k' in name_lower:
return 131072
if '64k' in name_lower:
return 65536
if '32k' in name_lower:
return 32768
if '16k' in name_lower:
return 16384
# Model family defaults
if 'qwen' in name_lower:
return 131072 # Qwen models typically have 128K+
if 'deepseek' in name_lower:
return 128000
if 'llama-3' in name_lower or 'llama3' in name_lower:
return 128000
if 'codellama' in name_lower:
return 100000
if 'mixtral' in name_lower:
return 65536
return 8192 # Safe default
Task Classification
Classification System
import re
from enum import Enum
from dataclasses import dataclass
class TaskCategory(Enum):
CODING = "coding"
REASONING = "reasoning"
ANALYSIS = "analysis"
DOCUMENTATION = "documentation"
@dataclass
class ClassificationResult:
category: TaskCategory
confidence: float # 0.0 - 1.0
requires_serena: bool
keywords_matched: list[str]
# Task patterns (regex)
TASK_PATTERNS = {
TaskCategory.CODING: [
r"(?:write|create|implement|code|generate)\s+(?:a\s+)?(?:function|class|method|component)",
r"(?:fix|debug|solve)\s+(?:this|the)\s+(?:bug|error|issue)",
r"refactor\s+(?:this|the)",
r"add\s+(?:error\s+handling|validation|logging|tests?)",
r"complete\s+(?:this|the)\s+code",
r"(?:convert|translate)\s+(?:this|the)\s+code",
r"(?:optimize|improve)\s+(?:this|the)\s+(?:function|code|performance)",
],
TaskCategory.REASONING: [
r"(?:design|architect|plan)\s+(?:a|the)\s+(?:system|architecture|solution)",
r"how\s+should\s+(?:I|we)\s+(?:approach|structure|implement)",
r"what\s+(?:is|would\s+be)\s+the\s+best\s+(?:way|approach|pattern)",
r"explain\s+the\s+(?:logic|reasoning|algorithm)",
r"compare\s+(?:and\s+contrast|between)",
r"(?:recommend|suggest)\s+(?:an?\s+)?(?:approach|solution|pattern)",
r"trade-?offs?\s+(?:between|of)",
],
TaskCategory.ANALYSIS: [
r"(?:review|analyze|audit)\s+(?:this|the)\s+code",
r"find\s+(?:potential\s+)?(?:issues|vulnerabilities|bugs|problems)",
r"(?:security|performance)\s+(?:review|analysis|audit)",
r"what\s+(?:could|might)\s+go\s+wrong",
r"identify\s+(?:problems|improvements|issues)",
r"(?:check|scan)\s+for\s+(?:vulnerabilities|issues)",
],
TaskCategory.DOCUMENTATION: [
r"(?:write|create|generate)\s+(?:documentation|docs|docstring)",
r"(?:add|write)\s+(?:comments|jsdoc|docstring|type\s+hints)",
r"(?:document|explain)\s+(?:this|the)\s+(?:code|function|api)",
r"(?:create|write)\s+(?:a\s+)?readme",
r"(?:generate|write)\s+(?:api\s+)?documentation",
r"describe\s+(?:what|how)\s+(?:this|the)",
],
}
# Keyword weights for scoring
KEYWORD_WEIGHTS = {
# Coding
"function": (TaskCategory.CODING, 0.3),
"implement": (TaskCategory.CODING, 0.4),
"code": (TaskCategory.CODING, 0.2),
"debug": (TaskCategory.CODING, 0.5),
"refactor": (TaskCategory.CODING, 0.6),
"fix": (TaskCategory.CODING, 0.4),
"test": (TaskCategory.CODING, 0.3),
"bug": (TaskCategory.CODING, 0.5),
# Reasoning
"architecture": (TaskCategory.REASONING, 0.6),
"design": (TaskCategory.REASONING, 0.4),
"approach": (TaskCategory.REASONING, 0.3),
"strategy": (TaskCategory.REASONING, 0.5),
"tradeoff": (TaskCategory.REASONING, 0.5),
"compare": (TaskCategory.REASONING, 0.4),
"recommend": (TaskCategory.REASONING, 0.4),
# Analysis
"review": (TaskCategory.ANALYSIS, 0.5),
"analyze": (TaskCategory.ANALYSIS, 0.6),
"security": (TaskCategory.ANALYSIS, 0.4),
"vulnerability": (TaskCategory.ANALYSIS, 0.7),
"performance": (TaskCategory.ANALYSIS, 0.3),
"audit": (TaskCategory.ANALYSIS, 0.6),
# Documentation
"document": (TaskCategory.DOCUMENTATION, 0.6),
"readme": (TaskCategory.DOCUMENTATION, 0.8),
"docstring": (TaskCategory.DOCUMENTATION, 0.8),
"comment": (TaskCategory.DOCUMENTATION, 0.4),
"explain": (TaskCategory.DOCUMENTATION, 0.3),
}
def classify_task(query: str) -> ClassificationResult:
"""Classify a query into a task category."""
query_lower = query.lower()
scores = {cat: 0.0 for cat in TaskCategory}
matched_keywords = []
# Pattern matching (weight: 0.5)
for category, patterns in TASK_PATTERNS.items():
for pattern in patterns:
if re.search(pattern, query_lower):
scores[category] += 0.5
# Keyword scoring (weight: 0.5)
words = re.findall(r'\w+', query_lower)
for word in words:
if word in KEYWORD_WEIGHTS:
category, weight = KEYWORD_WEIGHTS[word]
scores[category] += weight * 0.5
matched_keywords.append(word)
# Find highest scoring category
best_category = max(scores, key=scores.get)
confidence = min(scores[best_category], 1.0)
# Default to CODING if no clear match
if confidence < 0.2:
best_category = TaskCategory.CODING
confidence = 0.5
# Determine if Serena is required
requires_serena = (
best_category == TaskCategory.ANALYSIS or
any(kw in query_lower for kw in [
'definition', 'reference', 'symbol', 'rename',
'where is', 'find all', 'go to', 'jump to'
])
)
return ClassificationResult(
category=best_category,
confidence=confidence,
requires_serena=requires_serena,
keywords_matched=matched_keywords
)
Model Selection
Model Capability Matrix
from dataclasses import dataclass
from typing import Optional
@dataclass
class ModelCapability:
id: str
family: str
context_window: int
vram_gb: float
categories: list[TaskCategory]
performance_scores: dict[TaskCategory, int] # 0-100
tier: int # 1=best, 2=good, 3=basic
quantization: Optional[str] = None
# Comprehensive model database (40+ models) - Updated January 2025
MODEL_DATABASE: dict[str, ModelCapability] = {
# === CODING SPECIALISTS (Tier 1) ===
"deepseek-v3": ModelCapability(
id="deepseek-v3",
family="deepseek",
context_window=128000,
vram_gb=48, # MoE: 685B total, 37B active
categories=[TaskCategory.CODING, TaskCategory.REASONING, TaskCategory.ANALYSIS],
performance_scores={
TaskCategory.CODING: 99,
TaskCategory.REASONING: 97,
TaskCategory.ANALYSIS: 96,
TaskCategory.DOCUMENTATION: 92
},
tier=1
),
"qwen2.5-coder-32b": ModelCapability(
id="qwen2.5-coder-32b",
family="qwen",
context_window=131072,
vram_gb=22,
categories=[TaskCategory.CODING, TaskCategory.ANALYSIS],
performance_scores={
TaskCategory.CODING: 96,
TaskCategory.REASONING: 82,
TaskCategory.ANALYSIS: 92,
TaskCategory.DOCUMENTATION: 88
},
tier=1
),
"deepseek-coder-v2": ModelCapability(
id="deepseek-coder-v2",
family="deepseek",
context_window=128000,
vram_gb=48, # MoE: 236B total, 21B active
categories=[TaskCategory.CODING, TaskCategory.ANALYSIS, TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 95,
TaskCategory.REASONING: 88,
TaskCategory.ANALYSIS: 92,
TaskCategory.DOCUMENTATION: 80
},
tier=1
),
"codellama-70b": ModelCapability(
id="codellama-70b",
family="llama",
context_window=100000,
vram_gb=40,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 90,
TaskCategory.REASONING: 70,
TaskCategory.ANALYSIS: 85,
TaskCategory.DOCUMENTATION: 75
},
tier=1
),
"codellama-34b": ModelCapability(
id="codellama-34b",
family="llama",
context_window=100000,
vram_gb=20,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 85,
TaskCategory.REASONING: 65,
TaskCategory.ANALYSIS: 80,
TaskCategory.DOCUMENTATION: 70
},
tier=2
),
"qwen2.5-coder-14b": ModelCapability(
id="qwen2.5-coder-14b",
family="qwen",
context_window=131072,
vram_gb=10,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 82,
TaskCategory.REASONING: 60,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 70
},
tier=2
),
"starcoder2-15b": ModelCapability(
id="starcoder2-15b",
family="starcoder",
context_window=16384,
vram_gb=10,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 80,
TaskCategory.REASONING: 50,
TaskCategory.ANALYSIS: 70,
TaskCategory.DOCUMENTATION: 60
},
tier=2
),
"deepseek-coder-6.7b": ModelCapability(
id="deepseek-coder-6.7b",
family="deepseek",
context_window=16384,
vram_gb=5,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 75,
TaskCategory.REASONING: 50,
TaskCategory.ANALYSIS: 65,
TaskCategory.DOCUMENTATION: 55
},
tier=3
),
"codellama-7b": ModelCapability(
id="codellama-7b",
family="llama",
context_window=16384,
vram_gb=5,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 70,
TaskCategory.REASONING: 45,
TaskCategory.ANALYSIS: 60,
TaskCategory.DOCUMENTATION: 50
},
tier=3
),
# === REASONING SPECIALISTS ===
"deepseek-r1": ModelCapability(
id="deepseek-r1",
family="deepseek",
context_window=128000,
vram_gb=160, # 671B total
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 92,
TaskCategory.REASONING: 99,
TaskCategory.ANALYSIS: 95,
TaskCategory.DOCUMENTATION: 90
},
tier=1
),
"deepseek-r1-distill-70b": ModelCapability(
id="deepseek-r1-distill-70b",
family="deepseek",
context_window=128000,
vram_gb=42,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 88,
TaskCategory.REASONING: 94,
TaskCategory.ANALYSIS: 90,
TaskCategory.DOCUMENTATION: 86
},
tier=1
),
"qwen2.5-72b-instruct": ModelCapability(
id="qwen2.5-72b-instruct",
family="qwen",
context_window=131072,
vram_gb=48,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 88,
TaskCategory.REASONING: 95,
TaskCategory.ANALYSIS: 92,
TaskCategory.DOCUMENTATION: 94
},
tier=1
),
"llama-3.3-70b-instruct": ModelCapability(
id="llama-3.3-70b-instruct",
family="llama",
context_window=128000,
vram_gb=42,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 85,
TaskCategory.REASONING: 92,
TaskCategory.ANALYSIS: 88,
TaskCategory.DOCUMENTATION: 90
},
tier=1
),
"deepseek-r1-distill-32b": ModelCapability(
id="deepseek-r1-distill-32b",
family="deepseek",
context_window=128000,
vram_gb=22,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 82,
TaskCategory.REASONING: 90,
TaskCategory.ANALYSIS: 85,
TaskCategory.DOCUMENTATION: 82
},
tier=2
),
"mistral-small-24b": ModelCapability(
id="mistral-small-24b",
family="mistral",
context_window=32768,
vram_gb=16,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 80,
TaskCategory.REASONING: 85,
TaskCategory.ANALYSIS: 82,
TaskCategory.DOCUMENTATION: 84
},
tier=2
),
"qwen2.5-32b-instruct": ModelCapability(
id="qwen2.5-32b-instruct",
family="qwen",
context_window=131072,
vram_gb=22,
categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 78,
TaskCategory.REASONING: 86,
TaskCategory.ANALYSIS: 82,
TaskCategory.DOCUMENTATION: 88
},
tier=2
),
"phi-4": ModelCapability(
id="phi-4",
family="phi",
context_window=16384,
vram_gb=10,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 82,
TaskCategory.REASONING: 88,
TaskCategory.ANALYSIS: 80,
TaskCategory.DOCUMENTATION: 78
},
tier=2
),
"deepseek-r1-distill-14b": ModelCapability(
id="deepseek-r1-distill-14b",
family="deepseek",
context_window=128000,
vram_gb=10,
categories=[TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 75,
TaskCategory.REASONING: 85,
TaskCategory.ANALYSIS: 78,
TaskCategory.DOCUMENTATION: 76
},
tier=2
),
"llama-3.2-11b-vision": ModelCapability(
id="llama-3.2-11b-vision",
family="llama",
context_window=128000,
vram_gb=8,
categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 68,
TaskCategory.REASONING: 78,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 80
},
tier=2
),
"gemma-2-27b": ModelCapability(
id="gemma-2-27b",
family="gemma",
context_window=8192,
vram_gb=18,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 78,
TaskCategory.REASONING: 82,
TaskCategory.ANALYSIS: 78,
TaskCategory.DOCUMENTATION: 80
},
tier=2
),
"deepseek-r1-distill-8b": ModelCapability(
id="deepseek-r1-distill-8b",
family="deepseek",
context_window=128000,
vram_gb=6,
categories=[TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 68,
TaskCategory.REASONING: 78,
TaskCategory.ANALYSIS: 70,
TaskCategory.DOCUMENTATION: 68
},
tier=3
),
"gemma-2-9b": ModelCapability(
id="gemma-2-9b",
family="gemma",
context_window=8192,
vram_gb=7,
categories=[TaskCategory.REASONING, TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 72,
TaskCategory.REASONING: 75,
TaskCategory.ANALYSIS: 70,
TaskCategory.DOCUMENTATION: 74
},
tier=3
),
"llama-3.2-3b": ModelCapability(
id="llama-3.2-3b",
family="llama",
context_window=128000,
vram_gb=3,
categories=[TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 55,
TaskCategory.REASONING: 65,
TaskCategory.ANALYSIS: 58,
TaskCategory.DOCUMENTATION: 65
},
tier=3
),
# === ANALYSIS SPECIALISTS (Serena Required) ===
"codellama-34b-instruct": ModelCapability(
id="codellama-34b-instruct",
family="llama",
context_window=100000,
vram_gb=20,
categories=[TaskCategory.ANALYSIS],
performance_scores={
TaskCategory.CODING: 80,
TaskCategory.REASONING: 70,
TaskCategory.ANALYSIS: 88,
TaskCategory.DOCUMENTATION: 75
},
tier=2
),
# === DOCUMENTATION SPECIALISTS ===
"mistral-nemo-12b": ModelCapability(
id="mistral-nemo-12b",
family="mistral",
context_window=128000,
vram_gb=8,
categories=[TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 65,
TaskCategory.REASONING: 70,
TaskCategory.ANALYSIS: 65,
TaskCategory.DOCUMENTATION: 82
},
tier=2
),
"mistral-7b": ModelCapability(
id="mistral-7b",
family="mistral",
context_window=32768,
vram_gb=5,
categories=[TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 55,
TaskCategory.REASONING: 60,
TaskCategory.ANALYSIS: 55,
TaskCategory.DOCUMENTATION: 72
},
tier=3
),
# === ADDITIONAL MODELS ===
"phi-3-medium": ModelCapability(
id="phi-3-medium",
family="phi",
context_window=128000,
vram_gb=8,
categories=[TaskCategory.CODING, TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 72,
TaskCategory.REASONING: 75,
TaskCategory.ANALYSIS: 68,
TaskCategory.DOCUMENTATION: 70
},
tier=2
),
"gemma-2-27b": ModelCapability(
id="gemma-2-27b",
family="gemma",
context_window=8192,
vram_gb=18,
categories=[TaskCategory.CODING, TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 78,
TaskCategory.REASONING: 80,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 78
},
tier=2
),
"yi-34b": ModelCapability(
id="yi-34b",
family="yi",
context_window=200000,
vram_gb=20,
categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 72,
TaskCategory.REASONING: 82,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 80
},
tier=2
),
"command-r-plus": ModelCapability(
id="command-r-plus",
family="cohere",
context_window=128000,
vram_gb=48,
categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 70,
TaskCategory.REASONING: 85,
TaskCategory.ANALYSIS: 78,
TaskCategory.DOCUMENTATION: 88
},
tier=1
),
"wizardcoder-33b": ModelCapability(
id="wizardcoder-33b",
family="wizard",
context_window=16384,
vram_gb=20,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 85,
TaskCategory.REASONING: 60,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 65
},
tier=2
),
"magicoder-7b": ModelCapability(
id="magicoder-7b",
family="magicoder",
context_window=16384,
vram_gb=5,
categories=[TaskCategory.CODING],
performance_scores={
TaskCategory.CODING: 78,
TaskCategory.REASONING: 50,
TaskCategory.ANALYSIS: 65,
TaskCategory.DOCUMENTATION: 55
},
tier=3
),
"dolphin-mixtral-8x7b": ModelCapability(
id="dolphin-mixtral-8x7b",
family="dolphin",
context_window=32768,
vram_gb=28,
categories=[TaskCategory.CODING, TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 75,
TaskCategory.REASONING: 78,
TaskCategory.ANALYSIS: 72,
TaskCategory.DOCUMENTATION: 75
},
tier=2
),
"nous-hermes-2-mixtral": ModelCapability(
id="nous-hermes-2-mixtral",
family="nous",
context_window=32768,
vram_gb=28,
categories=[TaskCategory.REASONING],
performance_scores={
TaskCategory.CODING: 72,
TaskCategory.REASONING: 82,
TaskCategory.ANALYSIS: 75,
TaskCategory.DOCUMENTATION: 78
},
tier=2
),
"solar-10.7b": ModelCapability(
id="solar-10.7b",
family="solar",
context_window=4096,
vram_gb=7,
categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],
performance_scores={
TaskCategory.CODING: 60,
TaskCategory.REASONING: 72,
TaskCategory.ANALYSIS: 65,
TaskCategory.DOCUMENT
…(truncated)
1---2name: local-llm-router3description: Route AI coding queries to local LLMs in air-gapped networks. Integrates Serena MCP for semantic code understanding. Use when working offline, with local models (Ollama, LM Studio, Jan, OpenWebUI), or in secure/closed environments. Triggers on local LLM, Ollama, LM Studio, Jan, air-gapped, offline AI, Serena, local inference, closed network, model routing, defense network, secure coding.4metadata:5 source: https://skillmd.com/skills/qhjqhj00/local-llm-router6---78# Local LLM Router for Air-Gapped Networks910Intelligent routing of AI coding queries to local LLMs with Serena LSP integration for secure, offline-capable development environments.1112## Prerequisites (CRITICAL)1314Before using this skill, ensure:15161. **Serena MCP Server** installed and running (PRIMARY TOOL)172. **At least one local LLM service** running (Ollama, LM Studio, Jan, etc.)1819```bash20# Install Serena (required)21pip install serena22# Or via uvx23uvx --from git+https://github.com/oraios/serena serena start-mcp-server2425# Verify local LLM service26curl http://localhost:11434/api/version # Ollama27curl http://localhost:1234/v1/models # LM Studio28curl http://localhost:1337/v1/models # Jan29```3031## Quick Start3233```python34import httpx35import asyncio36from dataclasses import dataclass37from enum import Enum38from typing import Optional3940class TaskCategory(Enum):41 CODING = "coding"42 REASONING = "reasoning"43 ANALYSIS = "analysis"44 DOCUMENTATION = "documentation"4546@dataclass47class RouterConfig:48 """Local LLM Router configuration."""49 ollama_url: str = "http://localhost:11434"50 lmstudio_url: str = "http://localhost:1234"51 jan_url: str = "http://localhost:1337"52 serena_enabled: bool = True53 timeout: int = 305455async def quick_route(query: str, config: RouterConfig = RouterConfig()):56 """Quick routing example - detects services and routes query."""5758 # 1. Detect available services59 services = await discover_services(config)60 if not services:61 raise RuntimeError("No local LLM services available")6263 # 2. Classify task64 category = classify_task(query)6566 # 3. Select best model for task67 model = select_model(category, services)6869 # 4. Execute query70 return await execute_query(query, model, services[0])7172# Example usage73async def main():74 response = await quick_route("Write a function to parse JSON safely")75 print(response)7677asyncio.run(main())78```7980## Serena Integration (PRIMARY TOOL)8182**CRITICAL**: Serena MCP MUST be invoked FIRST for all code-related tasks. This provides semantic understanding of the codebase before routing to an LLM.8384### Why Serena First?85861. **Token Efficiency**: Serena extracts only relevant code context872. **Accuracy**: Symbol-level operations vs grep-style searches883. **Codebase Awareness**: Understands types, references, call hierarchies894. **Edit Precision**: Applies changes at symbol level, not string matching9091### Serena MCP Setup9293```python94import subprocess95import json96from typing import Any9798class SerenaMCP:99 """Serena MCP client for code intelligence."""100101 def __init__(self, workspace_root: str):102 self.workspace = workspace_root103 self.process = None104105 async def start(self):106 """Start Serena MCP server."""107 self.process = subprocess.Popen(108 ["serena", "start-mcp-server", "--workspace", self.workspace],109 stdin=subprocess.PIPE,110 stdout=subprocess.PIPE,111 stderr=subprocess.PIPE112 )113114 async def call(self, method: str, params: dict) -> Any:115 """Call Serena MCP method."""116 request = {117 "jsonrpc": "2.0",118 "id": 1,119 "method": method,120 "params": params121 }122 self.process.stdin.write(json.dumps(request).encode() + b"\n")123 self.process.stdin.flush()124 response = self.process.stdout.readline()125 return json.loads(response)126127 async def find_symbol(self, name: str) -> dict:128 """Find symbol definition by name."""129 return await self.call("find_symbol", {"name": name})130131 async def get_references(self, file: str, line: int, char: int) -> list:132 """Get all references to symbol at position."""133 return await self.call("get_references", {134 "file": file,135 "line": line,136 "character": char137 })138139 async def get_hover_info(self, file: str, line: int, char: int) -> dict:140 """Get type/documentation info at position."""141 return await self.call("get_hover_info", {142 "file": file,143 "line": line,144 "character": char145 })146147 async def get_diagnostics(self, file: str) -> list:148 """Get errors/warnings for file."""149 return await self.call("get_diagnostics", {"file": file})150151 async def apply_edit(self, file: str, edits: list) -> bool:152 """Apply code edits to file."""153 return await self.call("apply_edit", {"file": file, "edits": edits})154155# Serena tools by priority (always use higher priority first)156SERENA_TOOLS = {157 # Priority 1: Symbol-level operations (highest)158 "find_symbol": {"priority": 1, "use_for": ["navigation", "definition"]},159 "get_references": {"priority": 1, "use_for": ["refactoring", "impact analysis"]},160 "get_hover_info": {"priority": 1, "use_for": ["type info", "documentation"]},161162 # Priority 2: Code navigation163 "go_to_definition": {"priority": 2, "use_for": ["navigation"]},164 "go_to_type_definition": {"priority": 2, "use_for": ["type navigation"]},165 "go_to_implementation": {"priority": 2, "use_for": ["interface impl"]},166167 # Priority 3: Code understanding168 "get_document_symbols": {"priority": 3, "use_for": ["file structure"]},169 "get_workspace_symbols": {"priority": 3, "use_for": ["codebase search"]},170 "get_call_hierarchy": {"priority": 3, "use_for": ["call analysis"]},171172 # Priority 4: Code modification173 "apply_edit": {"priority": 4, "use_for": ["editing"]},174 "rename_symbol": {"priority": 4, "use_for": ["refactoring"]},175176 # Priority 5: Diagnostics177 "get_diagnostics": {"priority": 5, "use_for": ["errors", "warnings"]},178 "get_code_actions": {"priority": 5, "use_for": ["quick fixes"]},179}180```181182### Serena-First Request Handler183184```python185async def handle_code_request(186 query: str,187 file_context: Optional[dict] = None,188 serena: SerenaMCP = None,189 router: "LLMRouter" = None190):191 """192 Handle code request with Serena-first pattern.193194 CRITICAL: Serena is ALWAYS invoked first for code tasks.195 """196197 # Step 1: Classify the task198 category = classify_task(query)199200 # Step 2: ALWAYS use Serena for code context (if available)201 serena_context = {}202 if serena and file_context:203 # Gather semantic context from Serena204 if file_context.get("file") and file_context.get("position"):205 file = file_context["file"]206 line = file_context["position"]["line"]207 char = file_context["position"]["character"]208209 # Get hover info (type, docs)210 serena_context["hover"] = await serena.get_hover_info(file, line, char)211212 # For refactoring/analysis, get references213 if category in [TaskCategory.ANALYSIS, TaskCategory.CODING]:214 if "refactor" in query.lower() or "rename" in query.lower():215 serena_context["references"] = await serena.get_references(216 file, line, char217 )218219 # Always get diagnostics for the file220 serena_context["diagnostics"] = await serena.get_diagnostics(file)221222 # Step 3: Build enriched prompt with Serena context223 enriched_query = build_enriched_query(query, serena_context)224225 # Step 4: Select and route to appropriate LLM226 model = router.select_model(category)227 response = await router.execute(enriched_query, model)228229 # Step 5: If response contains edits, apply via Serena230 if serena and contains_code_edit(response):231 edits = parse_code_edits(response)232 await serena.apply_edit(file_context["file"], edits)233234 return response235236def build_enriched_query(query: str, serena_context: dict) -> str:237 """Build query enriched with Serena context."""238 parts = [query]239240 if serena_context.get("hover"):241 hover = serena_context["hover"]242 parts.append(f"\n## Type Information\n```\n{hover}\n```")243244 if serena_context.get("references"):245 refs = serena_context["references"]246 parts.append(f"\n## References ({len(refs)} found)\n")247 for ref in refs[:10]: # Limit to first 10248 parts.append(f"- {ref['file']}:{ref['line']}")249250 if serena_context.get("diagnostics"):251 diags = serena_context["diagnostics"]252 if diags:253 parts.append(f"\n## Current Issues ({len(diags)})\n")254 for diag in diags[:5]:255 parts.append(f"- Line {diag['line']}: {diag['message']}")256257 return "\n".join(parts)258```259260## Service Discovery261262### Supported Services263264| Service | Default Endpoint | Health Check | Models Endpoint | Chat Endpoint | API Style |265|---------|-----------------|--------------|-----------------|---------------|-----------|266| Ollama | `localhost:11434` | `/api/version` | `/api/tags` | `/api/chat` | Native |267| LM Studio | `localhost:1234` | `/v1/models` | `/v1/models` | `/v1/chat/completions` | OpenAI |268| Jan | `localhost:1337` | `/v1/models` | `/v1/models` | `/v1/chat/completions` | OpenAI |269| OpenWebUI | `localhost:3000` | `/api/health` | `/api/models` | `/api/chat` | Custom |270| LocalAI | `localhost:8080` | `/readyz` | `/v1/models` | `/v1/chat/completions` | OpenAI |271| vLLM | `localhost:8000` | `/health` | `/v1/models` | `/v1/chat/completions` | OpenAI |272| llama.cpp | `localhost:8080` | `/health` | `/v1/models` | `/v1/chat/completions` | OpenAI |273| Kobold.cpp | `localhost:5001` | `/api/v1/info` | `/api/v1/models` | `/api/v1/generate` | Custom |274| GPT4All | `localhost:4891` | `/v1/models` | `/v1/models` | `/v1/chat/completions` | OpenAI |275| text-generation-webui | `localhost:5000` | `/api/v1/model` | `/api/v1/models` | `/api/v1/chat` | Custom |276277### OS Detection278279```python280import sys281import os282import platform283from dataclasses import dataclass284285@dataclass286class OSInfo:287 platform: str # 'windows', 'linux', 'darwin'288 release: str289 arch: str # 'x64', 'arm64'290 is_wsl: bool291 is_container: bool292293def detect_os() -> OSInfo:294 """Detect operating system and environment."""295 plat = sys.platform296297 # Normalize platform name298 if plat == 'win32':299 plat = 'windows'300 elif plat == 'darwin':301 plat = 'darwin'302 else:303 plat = 'linux'304305 # WSL detection306 is_wsl = False307 if plat == 'linux':308 try:309 with open('/proc/version', 'r') as f:310 is_wsl = 'microsoft' in f.read().lower()311 except FileNotFoundError:312 pass313 is_wsl = is_wsl or os.environ.get('WSL_DISTRO_NAME') is not None314315 # Container detection316 is_container = (317 os.path.exists('/.dockerenv') or318 os.environ.get('KUBERNETES_SERVICE_HOST') is not None319 )320 if not is_container and plat == 'linux':321 try:322 with open('/proc/1/cgroup', 'r') as f:323 is_container = 'docker' in f.read() or 'kubepods' in f.read()324 except FileNotFoundError:325 pass326327 return OSInfo(328 platform=plat,329 release=platform.release(),330 arch=platform.machine(),331 is_wsl=is_wsl,332 is_container=is_container333 )334335def adjust_endpoint_for_os(endpoint: str, os_info: OSInfo) -> str:336 """Adjust endpoint based on OS environment."""337 if os_info.is_wsl or os_info.is_container:338 # In WSL/containers, localhost services are on the host339 return endpoint.replace('localhost', 'host.docker.internal')340 return endpoint341```342343### Service Discovery Implementation344345```python346import httpx347import asyncio348from dataclasses import dataclass, field349from datetime import datetime350from typing import Optional351352@dataclass353class DiscoveredModel:354 id: str355 name: str356 size: int = 0357 family: Optional[str] = None358 context_length: int = 4096359 quantization: Optional[str] = None360361@dataclass362class LLMService:363 name: str364 type: str # 'ollama', 'lmstudio', 'jan', 'openwebui', 'custom'365 endpoint: str366 status: str = 'unknown' # 'online', 'offline', 'unknown'367 models: list = field(default_factory=list)368 last_checked: datetime = None369 api_style: str = 'openai' # 'openai', 'native'370371 # Endpoint paths372 health_path: str = '/v1/models'373 models_path: str = '/v1/models'374 chat_path: str = '/v1/chat/completions'375376# Default service configurations377SERVICE_DEFAULTS = {378 'ollama': LLMService(379 name='Ollama',380 type='ollama',381 endpoint='http://localhost:11434',382 health_path='/api/version',383 models_path='/api/tags',384 chat_path='/api/chat',385 api_style='native'386 ),387 'lmstudio': LLMService(388 name='LM Studio',389 type='lmstudio',390 endpoint='http://localhost:1234',391 health_path='/v1/models',392 models_path='/v1/models',393 chat_path='/v1/chat/completions',394 api_style='openai'395 ),396 'jan': LLMService(397 name='Jan',398 type='jan',399 endpoint='http://localhost:1337',400 health_path='/v1/models',401 models_path='/v1/models',402 chat_path='/v1/chat/completions',403 api_style='openai'404 ),405 'openwebui': LLMService(406 name='Open WebUI',407 type='openwebui',408 endpoint='http://localhost:3000',409 health_path='/api/health',410 models_path='/api/models',411 chat_path='/api/chat',412 api_style='custom'413 ),414 'localai': LLMService(415 name='LocalAI',416 type='localai',417 endpoint='http://localhost:8080',418 health_path='/readyz',419 models_path='/v1/models',420 chat_path='/v1/chat/completions',421 api_style='openai'422 ),423 'vllm': LLMService(424 name='vLLM',425 type='vllm',426 endpoint='http://localhost:8000',427 health_path='/health',428 models_path='/v1/models',429 chat_path='/v1/chat/completions',430 api_style='openai'431 ),432 'llamacpp': LLMService(433 name='llama.cpp',434 type='llamacpp',435 endpoint='http://localhost:8080',436 health_path='/health',437 models_path='/v1/models',438 chat_path='/v1/chat/completions',439 api_style='openai'440 ),441 'koboldcpp': LLMService(442 name='Kobold.cpp',443 type='koboldcpp',444 endpoint='http://localhost:5001',445 health_path='/api/v1/info',446 models_path='/api/v1/model',447 chat_path='/api/v1/generate',448 api_style='custom'449 ),450 'gpt4all': LLMService(451 name='GPT4All',452 type='gpt4all',453 endpoint='http://localhost:4891',454 health_path='/v1/models',455 models_path='/v1/models',456 chat_path='/v1/chat/completions',457 api_style='openai'458 ),459}460461class ServiceDiscovery:462 """Discover and monitor local LLM services."""463464 def __init__(self, custom_endpoints: list = None):465 self.services: dict[str, LLMService] = {}466 self.os_info = detect_os()467 self.custom_endpoints = custom_endpoints or []468 self._client = httpx.AsyncClient(timeout=5.0)469470 async def discover_all(self) -> list[LLMService]:471 """Discover all available LLM services."""472 discovered = []473474 # Check default services475 tasks = []476 for key, default in SERVICE_DEFAULTS.items():477 service = LLMService(478 name=default.name,479 type=default.type,480 endpoint=adjust_endpoint_for_os(default.endpoint, self.os_info),481 health_path=default.health_path,482 models_path=default.models_path,483 chat_path=default.chat_path,484 api_style=default.api_style485 )486 tasks.append(self._check_service(service))487488 # Check custom endpoints489 for custom in self.custom_endpoints:490 service = LLMService(491 name=custom.get('name', 'Custom'),492 type='custom',493 endpoint=custom['endpoint'],494 health_path=custom.get('health_path', '/v1/models'),495 models_path=custom.get('models_path', '/v1/models'),496 chat_path=custom.get('chat_path', '/v1/chat/completions'),497 api_style=custom.get('api_style', 'openai')498 )499 tasks.append(self._check_service(service))500501 results = await asyncio.gather(*tasks, return_exceptions=True)502503 for result in results:504 if isinstance(result, LLMService) and result.status == 'online':505 discovered.append(result)506 self.services[result.type] = result507508 return discovered509510 async def _check_service(self, service: LLMService) -> LLMService:511 """Check if service is online and discover models."""512 try:513 # Health check514 response = await self._client.get(515 f"{service.endpoint}{service.health_path}"516 )517518 if response.status_code == 200:519 service.status = 'online'520 service.last_checked = datetime.now()521522 # Discover models523 service.models = await self._discover_models(service)524 else:525 service.status = 'offline'526527 except (httpx.ConnectError, httpx.TimeoutException):528 service.status = 'offline'529530 return service531532 async def _discover_models(self, service: LLMService) -> list[DiscoveredModel]:533 """Discover available models on service."""534 try:535 response = await self._client.get(536 f"{service.endpoint}{service.models_path}"537 )538 data = response.json()539540 # Parse based on service type541 if service.type == 'ollama':542 return [543 DiscoveredModel(544 id=m['name'],545 name=m['name'],546 size=m.get('size', 0),547 family=m.get('details', {}).get('family'),548 context_length=self._infer_context_length(m['name'])549 )550 for m in data.get('models', [])551 ]552 else: # OpenAI-style553 return [554 DiscoveredModel(555 id=m['id'],556 name=m['id'],557 context_length=m.get('context_length', 4096)558 )559 for m in data.get('data', [])560 ]561 except Exception:562 return []563564 def _infer_context_length(self, model_name: str) -> int:565 """Infer context length from model name."""566 name_lower = model_name.lower()567568 # Check for explicit context markers569 if '128k' in name_lower or '131k' in name_lower:570 return 131072571 if '64k' in name_lower:572 return 65536573 if '32k' in name_lower:574 return 32768575 if '16k' in name_lower:576 return 16384577578 # Model family defaults579 if 'qwen' in name_lower:580 return 131072 # Qwen models typically have 128K+581 if 'deepseek' in name_lower:582 return 128000583 if 'llama-3' in name_lower or 'llama3' in name_lower:584 return 128000585 if 'codellama' in name_lower:586 return 100000587 if 'mixtral' in name_lower:588 return 65536589590 return 8192 # Safe default591```592593## Task Classification594595### Classification System596597```python598import re599from enum import Enum600from dataclasses import dataclass601602class TaskCategory(Enum):603 CODING = "coding"604 REASONING = "reasoning"605 ANALYSIS = "analysis"606 DOCUMENTATION = "documentation"607608@dataclass609class ClassificationResult:610 category: TaskCategory611 confidence: float # 0.0 - 1.0612 requires_serena: bool613 keywords_matched: list[str]614615# Task patterns (regex)616TASK_PATTERNS = {617 TaskCategory.CODING: [618 r"(?:write|create|implement|code|generate)\s+(?:a\s+)?(?:function|class|method|component)",619 r"(?:fix|debug|solve)\s+(?:this|the)\s+(?:bug|error|issue)",620 r"refactor\s+(?:this|the)",621 r"add\s+(?:error\s+handling|validation|logging|tests?)",622 r"complete\s+(?:this|the)\s+code",623 r"(?:convert|translate)\s+(?:this|the)\s+code",624 r"(?:optimize|improve)\s+(?:this|the)\s+(?:function|code|performance)",625 ],626 TaskCategory.REASONING: [627 r"(?:design|architect|plan)\s+(?:a|the)\s+(?:system|architecture|solution)",628 r"how\s+should\s+(?:I|we)\s+(?:approach|structure|implement)",629 r"what\s+(?:is|would\s+be)\s+the\s+best\s+(?:way|approach|pattern)",630 r"explain\s+the\s+(?:logic|reasoning|algorithm)",631 r"compare\s+(?:and\s+contrast|between)",632 r"(?:recommend|suggest)\s+(?:an?\s+)?(?:approach|solution|pattern)",633 r"trade-?offs?\s+(?:between|of)",634 ],635 TaskCategory.ANALYSIS: [636 r"(?:review|analyze|audit)\s+(?:this|the)\s+code",637 r"find\s+(?:potential\s+)?(?:issues|vulnerabilities|bugs|problems)",638 r"(?:security|performance)\s+(?:review|analysis|audit)",639 r"what\s+(?:could|might)\s+go\s+wrong",640 r"identify\s+(?:problems|improvements|issues)",641 r"(?:check|scan)\s+for\s+(?:vulnerabilities|issues)",642 ],643 TaskCategory.DOCUMENTATION: [644 r"(?:write|create|generate)\s+(?:documentation|docs|docstring)",645 r"(?:add|write)\s+(?:comments|jsdoc|docstring|type\s+hints)",646 r"(?:document|explain)\s+(?:this|the)\s+(?:code|function|api)",647 r"(?:create|write)\s+(?:a\s+)?readme",648 r"(?:generate|write)\s+(?:api\s+)?documentation",649 r"describe\s+(?:what|how)\s+(?:this|the)",650 ],651}652653# Keyword weights for scoring654KEYWORD_WEIGHTS = {655 # Coding656 "function": (TaskCategory.CODING, 0.3),657 "implement": (TaskCategory.CODING, 0.4),658 "code": (TaskCategory.CODING, 0.2),659 "debug": (TaskCategory.CODING, 0.5),660 "refactor": (TaskCategory.CODING, 0.6),661 "fix": (TaskCategory.CODING, 0.4),662 "test": (TaskCategory.CODING, 0.3),663 "bug": (TaskCategory.CODING, 0.5),664665 # Reasoning666 "architecture": (TaskCategory.REASONING, 0.6),667 "design": (TaskCategory.REASONING, 0.4),668 "approach": (TaskCategory.REASONING, 0.3),669 "strategy": (TaskCategory.REASONING, 0.5),670 "tradeoff": (TaskCategory.REASONING, 0.5),671 "compare": (TaskCategory.REASONING, 0.4),672 "recommend": (TaskCategory.REASONING, 0.4),673674 # Analysis675 "review": (TaskCategory.ANALYSIS, 0.5),676 "analyze": (TaskCategory.ANALYSIS, 0.6),677 "security": (TaskCategory.ANALYSIS, 0.4),678 "vulnerability": (TaskCategory.ANALYSIS, 0.7),679 "performance": (TaskCategory.ANALYSIS, 0.3),680 "audit": (TaskCategory.ANALYSIS, 0.6),681682 # Documentation683 "document": (TaskCategory.DOCUMENTATION, 0.6),684 "readme": (TaskCategory.DOCUMENTATION, 0.8),685 "docstring": (TaskCategory.DOCUMENTATION, 0.8),686 "comment": (TaskCategory.DOCUMENTATION, 0.4),687 "explain": (TaskCategory.DOCUMENTATION, 0.3),688}689690def classify_task(query: str) -> ClassificationResult:691 """Classify a query into a task category."""692 query_lower = query.lower()693 scores = {cat: 0.0 for cat in TaskCategory}694 matched_keywords = []695696 # Pattern matching (weight: 0.5)697 for category, patterns in TASK_PATTERNS.items():698 for pattern in patterns:699 if re.search(pattern, query_lower):700 scores[category] += 0.5701702 # Keyword scoring (weight: 0.5)703 words = re.findall(r'\w+', query_lower)704 for word in words:705 if word in KEYWORD_WEIGHTS:706 category, weight = KEYWORD_WEIGHTS[word]707 scores[category] += weight * 0.5708 matched_keywords.append(word)709710 # Find highest scoring category711 best_category = max(scores, key=scores.get)712 confidence = min(scores[best_category], 1.0)713714 # Default to CODING if no clear match715 if confidence < 0.2:716 best_category = TaskCategory.CODING717 confidence = 0.5718719 # Determine if Serena is required720 requires_serena = (721 best_category == TaskCategory.ANALYSIS or722 any(kw in query_lower for kw in [723 'definition', 'reference', 'symbol', 'rename',724 'where is', 'find all', 'go to', 'jump to'725 ])726 )727728 return ClassificationResult(729 category=best_category,730 confidence=confidence,731 requires_serena=requires_serena,732 keywords_matched=matched_keywords733 )734```735736## Model Selection737738### Model Capability Matrix739740```python741from dataclasses import dataclass742from typing import Optional743744@dataclass745class ModelCapability:746 id: str747 family: str748 context_window: int749 vram_gb: float750 categories: list[TaskCategory]751 performance_scores: dict[TaskCategory, int] # 0-100752 tier: int # 1=best, 2=good, 3=basic753 quantization: Optional[str] = None754755# Comprehensive model database (40+ models) - Updated January 2025756MODEL_DATABASE: dict[str, ModelCapability] = {757 # === CODING SPECIALISTS (Tier 1) ===758 "deepseek-v3": ModelCapability(759 id="deepseek-v3",760 family="deepseek",761 context_window=128000,762 vram_gb=48, # MoE: 685B total, 37B active763 categories=[TaskCategory.CODING, TaskCategory.REASONING, TaskCategory.ANALYSIS],764 performance_scores={765 TaskCategory.CODING: 99,766 TaskCategory.REASONING: 97,767 TaskCategory.ANALYSIS: 96,768 TaskCategory.DOCUMENTATION: 92769 },770 tier=1771 ),772 "qwen2.5-coder-32b": ModelCapability(773 id="qwen2.5-coder-32b",774 family="qwen",775 context_window=131072,776 vram_gb=22,777 categories=[TaskCategory.CODING, TaskCategory.ANALYSIS],778 performance_scores={779 TaskCategory.CODING: 96,780 TaskCategory.REASONING: 82,781 TaskCategory.ANALYSIS: 92,782 TaskCategory.DOCUMENTATION: 88783 },784 tier=1785 ),786 "deepseek-coder-v2": ModelCapability(787 id="deepseek-coder-v2",788 family="deepseek",789 context_window=128000,790 vram_gb=48, # MoE: 236B total, 21B active791 categories=[TaskCategory.CODING, TaskCategory.ANALYSIS, TaskCategory.REASONING],792 performance_scores={793 TaskCategory.CODING: 95,794 TaskCategory.REASONING: 88,795 TaskCategory.ANALYSIS: 92,796 TaskCategory.DOCUMENTATION: 80797 },798 tier=1799 ),800 "codellama-70b": ModelCapability(801 id="codellama-70b",802 family="llama",803 context_window=100000,804 vram_gb=40,805 categories=[TaskCategory.CODING],806 performance_scores={807 TaskCategory.CODING: 90,808 TaskCategory.REASONING: 70,809 TaskCategory.ANALYSIS: 85,810 TaskCategory.DOCUMENTATION: 75811 },812 tier=1813 ),814 "codellama-34b": ModelCapability(815 id="codellama-34b",816 family="llama",817 context_window=100000,818 vram_gb=20,819 categories=[TaskCategory.CODING],820 performance_scores={821 TaskCategory.CODING: 85,822 TaskCategory.REASONING: 65,823 TaskCategory.ANALYSIS: 80,824 TaskCategory.DOCUMENTATION: 70825 },826 tier=2827 ),828 "qwen2.5-coder-14b": ModelCapability(829 id="qwen2.5-coder-14b",830 family="qwen",831 context_window=131072,832 vram_gb=10,833 categories=[TaskCategory.CODING],834 performance_scores={835 TaskCategory.CODING: 82,836 TaskCategory.REASONING: 60,837 TaskCategory.ANALYSIS: 75,838 TaskCategory.DOCUMENTATION: 70839 },840 tier=2841 ),842 "starcoder2-15b": ModelCapability(843 id="starcoder2-15b",844 family="starcoder",845 context_window=16384,846 vram_gb=10,847 categories=[TaskCategory.CODING],848 performance_scores={849 TaskCategory.CODING: 80,850 TaskCategory.REASONING: 50,851 TaskCategory.ANALYSIS: 70,852 TaskCategory.DOCUMENTATION: 60853 },854 tier=2855 ),856 "deepseek-coder-6.7b": ModelCapability(857 id="deepseek-coder-6.7b",858 family="deepseek",859 context_window=16384,860 vram_gb=5,861 categories=[TaskCategory.CODING],862 performance_scores={863 TaskCategory.CODING: 75,864 TaskCategory.REASONING: 50,865 TaskCategory.ANALYSIS: 65,866 TaskCategory.DOCUMENTATION: 55867 },868 tier=3869 ),870 "codellama-7b": ModelCapability(871 id="codellama-7b",872 family="llama",873 context_window=16384,874 vram_gb=5,875 categories=[TaskCategory.CODING],876 performance_scores={877 TaskCategory.CODING: 70,878 TaskCategory.REASONING: 45,879 TaskCategory.ANALYSIS: 60,880 TaskCategory.DOCUMENTATION: 50881 },882 tier=3883 ),884885 # === REASONING SPECIALISTS ===886 "deepseek-r1": ModelCapability(887 id="deepseek-r1",888 family="deepseek",889 context_window=128000,890 vram_gb=160, # 671B total891 categories=[TaskCategory.REASONING, TaskCategory.CODING],892 performance_scores={893 TaskCategory.CODING: 92,894 TaskCategory.REASONING: 99,895 TaskCategory.ANALYSIS: 95,896 TaskCategory.DOCUMENTATION: 90897 },898 tier=1899 ),900 "deepseek-r1-distill-70b": ModelCapability(901 id="deepseek-r1-distill-70b",902 family="deepseek",903 context_window=128000,904 vram_gb=42,905 categories=[TaskCategory.REASONING, TaskCategory.CODING],906 performance_scores={907 TaskCategory.CODING: 88,908 TaskCategory.REASONING: 94,909 TaskCategory.ANALYSIS: 90,910 TaskCategory.DOCUMENTATION: 86911 },912 tier=1913 ),914 "qwen2.5-72b-instruct": ModelCapability(915 id="qwen2.5-72b-instruct",916 family="qwen",917 context_window=131072,918 vram_gb=48,919 categories=[TaskCategory.REASONING, TaskCategory.CODING],920 performance_scores={921 TaskCategory.CODING: 88,922 TaskCategory.REASONING: 95,923 TaskCategory.ANALYSIS: 92,924 TaskCategory.DOCUMENTATION: 94925 },926 tier=1927 ),928 "llama-3.3-70b-instruct": ModelCapability(929 id="llama-3.3-70b-instruct",930 family="llama",931 context_window=128000,932 vram_gb=42,933 categories=[TaskCategory.REASONING, TaskCategory.CODING],934 performance_scores={935 TaskCategory.CODING: 85,936 TaskCategory.REASONING: 92,937 TaskCategory.ANALYSIS: 88,938 TaskCategory.DOCUMENTATION: 90939 },940 tier=1941 ),942 "deepseek-r1-distill-32b": ModelCapability(943 id="deepseek-r1-distill-32b",944 family="deepseek",945 context_window=128000,946 vram_gb=22,947 categories=[TaskCategory.REASONING, TaskCategory.CODING],948 performance_scores={949 TaskCategory.CODING: 82,950 TaskCategory.REASONING: 90,951 TaskCategory.ANALYSIS: 85,952 TaskCategory.DOCUMENTATION: 82953 },954 tier=2955 ),956 "mistral-small-24b": ModelCapability(957 id="mistral-small-24b",958 family="mistral",959 context_window=32768,960 vram_gb=16,961 categories=[TaskCategory.REASONING, TaskCategory.CODING],962 performance_scores={963 TaskCategory.CODING: 80,964 TaskCategory.REASONING: 85,965 TaskCategory.ANALYSIS: 82,966 TaskCategory.DOCUMENTATION: 84967 },968 tier=2969 ),970 "qwen2.5-32b-instruct": ModelCapability(971 id="qwen2.5-32b-instruct",972 family="qwen",973 context_window=131072,974 vram_gb=22,975 categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],976 performance_scores={977 TaskCategory.CODING: 78,978 TaskCategory.REASONING: 86,979 TaskCategory.ANALYSIS: 82,980 TaskCategory.DOCUMENTATION: 88981 },982 tier=2983 ),984 "phi-4": ModelCapability(985 id="phi-4",986 family="phi",987 context_window=16384,988 vram_gb=10,989 categories=[TaskCategory.REASONING, TaskCategory.CODING],990 performance_scores={991 TaskCategory.CODING: 82,992 TaskCategory.REASONING: 88,993 TaskCategory.ANALYSIS: 80,994 TaskCategory.DOCUMENTATION: 78995 },996 tier=2997 ),998 "deepseek-r1-distill-14b": ModelCapability(999 id="deepseek-r1-distill-14b",1000 family="deepseek",1001 context_window=128000,1002 vram_gb=10,1003 categories=[TaskCategory.REASONING],1004 performance_scores={1005 TaskCategory.CODING: 75,1006 TaskCategory.REASONING: 85,1007 TaskCategory.ANALYSIS: 78,1008 TaskCategory.DOCUMENTATION: 761009 },1010 tier=21011 ),1012 "llama-3.2-11b-vision": ModelCapability(1013 id="llama-3.2-11b-vision",1014 family="llama",1015 context_window=128000,1016 vram_gb=8,1017 categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],1018 performance_scores={1019 TaskCategory.CODING: 68,1020 TaskCategory.REASONING: 78,1021 TaskCategory.ANALYSIS: 75,1022 TaskCategory.DOCUMENTATION: 801023 },1024 tier=21025 ),1026 "gemma-2-27b": ModelCapability(1027 id="gemma-2-27b",1028 family="gemma",1029 context_window=8192,1030 vram_gb=18,1031 categories=[TaskCategory.REASONING, TaskCategory.CODING],1032 performance_scores={1033 TaskCategory.CODING: 78,1034 TaskCategory.REASONING: 82,1035 TaskCategory.ANALYSIS: 78,1036 TaskCategory.DOCUMENTATION: 801037 },1038 tier=21039 ),1040 "deepseek-r1-distill-8b": ModelCapability(1041 id="deepseek-r1-distill-8b",1042 family="deepseek",1043 context_window=128000,1044 vram_gb=6,1045 categories=[TaskCategory.REASONING],1046 performance_scores={1047 TaskCategory.CODING: 68,1048 TaskCategory.REASONING: 78,1049 TaskCategory.ANALYSIS: 70,1050 TaskCategory.DOCUMENTATION: 681051 },1052 tier=31053 ),1054 "gemma-2-9b": ModelCapability(1055 id="gemma-2-9b",1056 family="gemma",1057 context_window=8192,1058 vram_gb=7,1059 categories=[TaskCategory.REASONING, TaskCategory.CODING],1060 performance_scores={1061 TaskCategory.CODING: 72,1062 TaskCategory.REASONING: 75,1063 TaskCategory.ANALYSIS: 70,1064 TaskCategory.DOCUMENTATION: 741065 },1066 tier=31067 ),1068 "llama-3.2-3b": ModelCapability(1069 id="llama-3.2-3b",1070 family="llama",1071 context_window=128000,1072 vram_gb=3,1073 categories=[TaskCategory.REASONING],1074 performance_scores={1075 TaskCategory.CODING: 55,1076 TaskCategory.REASONING: 65,1077 TaskCategory.ANALYSIS: 58,1078 TaskCategory.DOCUMENTATION: 651079 },1080 tier=31081 ),10821083 # === ANALYSIS SPECIALISTS (Serena Required) ===1084 "codellama-34b-instruct": ModelCapability(1085 id="codellama-34b-instruct",1086 family="llama",1087 context_window=100000,1088 vram_gb=20,1089 categories=[TaskCategory.ANALYSIS],1090 performance_scores={1091 TaskCategory.CODING: 80,1092 TaskCategory.REASONING: 70,1093 TaskCategory.ANALYSIS: 88,1094 TaskCategory.DOCUMENTATION: 751095 },1096 tier=21097 ),10981099 # === DOCUMENTATION SPECIALISTS ===1100 "mistral-nemo-12b": ModelCapability(1101 id="mistral-nemo-12b",1102 family="mistral",1103 context_window=128000,1104 vram_gb=8,1105 categories=[TaskCategory.DOCUMENTATION],1106 performance_scores={1107 TaskCategory.CODING: 65,1108 TaskCategory.REASONING: 70,1109 TaskCategory.ANALYSIS: 65,1110 TaskCategory.DOCUMENTATION: 821111 },1112 tier=21113 ),1114 "mistral-7b": ModelCapability(1115 id="mistral-7b",1116 family="mistral",1117 context_window=32768,1118 vram_gb=5,1119 categories=[TaskCategory.DOCUMENTATION],1120 performance_scores={1121 TaskCategory.CODING: 55,1122 TaskCategory.REASONING: 60,1123 TaskCategory.ANALYSIS: 55,1124 TaskCategory.DOCUMENTATION: 721125 },1126 tier=31127 ),11281129 # === ADDITIONAL MODELS ===1130 "phi-3-medium": ModelCapability(1131 id="phi-3-medium",1132 family="phi",1133 context_window=128000,1134 vram_gb=8,1135 categories=[TaskCategory.CODING, TaskCategory.REASONING],1136 performance_scores={1137 TaskCategory.CODING: 72,1138 TaskCategory.REASONING: 75,1139 TaskCategory.ANALYSIS: 68,1140 TaskCategory.DOCUMENTATION: 701141 },1142 tier=21143 ),1144 "gemma-2-27b": ModelCapability(1145 id="gemma-2-27b",1146 family="gemma",1147 context_window=8192,1148 vram_gb=18,1149 categories=[TaskCategory.CODING, TaskCategory.REASONING],1150 performance_scores={1151 TaskCategory.CODING: 78,1152 TaskCategory.REASONING: 80,1153 TaskCategory.ANALYSIS: 75,1154 TaskCategory.DOCUMENTATION: 781155 },1156 tier=21157 ),1158 "yi-34b": ModelCapability(1159 id="yi-34b",1160 family="yi",1161 context_window=200000,1162 vram_gb=20,1163 categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],1164 performance_scores={1165 TaskCategory.CODING: 72,1166 TaskCategory.REASONING: 82,1167 TaskCategory.ANALYSIS: 75,1168 TaskCategory.DOCUMENTATION: 801169 },1170 tier=21171 ),1172 "command-r-plus": ModelCapability(1173 id="command-r-plus",1174 family="cohere",1175 context_window=128000,1176 vram_gb=48,1177 categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],1178 performance_scores={1179 TaskCategory.CODING: 70,1180 TaskCategory.REASONING: 85,1181 TaskCategory.ANALYSIS: 78,1182 TaskCategory.DOCUMENTATION: 881183 },1184 tier=11185 ),1186 "wizardcoder-33b": ModelCapability(1187 id="wizardcoder-33b",1188 family="wizard",1189 context_window=16384,1190 vram_gb=20,1191 categories=[TaskCategory.CODING],1192 performance_scores={1193 TaskCategory.CODING: 85,1194 TaskCategory.REASONING: 60,1195 TaskCategory.ANALYSIS: 75,1196 TaskCategory.DOCUMENTATION: 651197 },1198 tier=21199 ),1200 "magicoder-7b": ModelCapability(1201 id="magicoder-7b",1202 family="magicoder",1203 context_window=16384,1204 vram_gb=5,1205 categories=[TaskCategory.CODING],1206 performance_scores={1207 TaskCategory.CODING: 78,1208 TaskCategory.REASONING: 50,1209 TaskCategory.ANALYSIS: 65,1210 TaskCategory.DOCUMENTATION: 551211 },1212 tier=31213 ),1214 "dolphin-mixtral-8x7b": ModelCapability(1215 id="dolphin-mixtral-8x7b",1216 family="dolphin",1217 context_window=32768,1218 vram_gb=28,1219 categories=[TaskCategory.CODING, TaskCategory.REASONING],1220 performance_scores={1221 TaskCategory.CODING: 75,1222 TaskCategory.REASONING: 78,1223 TaskCategory.ANALYSIS: 72,1224 TaskCategory.DOCUMENTATION: 751225 },1226 tier=21227 ),1228 "nous-hermes-2-mixtral": ModelCapability(1229 id="nous-hermes-2-mixtral",1230 family="nous",1231 context_window=32768,1232 vram_gb=28,1233 categories=[TaskCategory.REASONING],1234 performance_scores={1235 TaskCategory.CODING: 72,1236 TaskCategory.REASONING: 82,1237 TaskCategory.ANALYSIS: 75,1238 TaskCategory.DOCUMENTATION: 781239 },1240 tier=21241 ),1242 "solar-10.7b": ModelCapability(1243 id="solar-10.7b",1244 family="solar",1245 context_window=4096,1246 vram_gb=7,1247 categories=[TaskCategory.REASONING, TaskCategory.DOCUMENTATION],1248 performance_scores={1249 TaskCategory.CODING: 60,1250 TaskCategory.REASONING: 72,1251 TaskCategory.ANALYSIS: 65,1252 TaskCategory.DOCUMENTATION: 751253 },1254 tier=31255 ),1256}12571258# Task-to-model priority mapping (Updated January 2025)1259TASK_MODEL_PRIORITY = {1260 TaskCategory.CODING: [1261 # Tier 1 - Best1262 "deepseek-v3", "qwen2.5-coder-32b", "deepseek-coder-v2",1263 # Tier 2 - Good1264 "codellama-70b", "qwen2.5-coder-14b", "codellama-34b",1265 "starcoder2-15b", "phi-4",1266 # Tier 3 - Basic1267 "qwen2.5-coder-7b", "codellama-7b", "deepseek-coder-6.7b"1268 ],1269 TaskCategory.REASONING: [1270 # Tier 1 - Best1271 "deepseek-r1", "deepseek-v3", "deepseek-r1-distill-70b",1272 "qwen2.5-72b-instruct", "llama-3.3-70b-instruct",1273 # Tier 2 - Good1274 "deepseek-r1-distill-32b", "mistral-small-24b", "qwen2.5-32b-instruct",1275 "phi-4", "gemma-2-27b",1276 # Tier 3 - Basic1277 "deepseek-r1-distill-14b", "deepseek-r1-distill-8b", "gemma-2-9b"1278 ],1279 TaskCategory.ANALYSIS: [1280 # Requires Serena LSP1281 "deepseek-v3", "qwen2.5-coder-32b", "deepseek-coder-v2",1282 "codellama-34b-instruct", "qwen2.5-72b-instruct"1283 ],1284 TaskCategory.DOCUMENTATION: [1285 "qwen2.5-72b-instruct", "llama-3.3-70b-instruct", "qwen2.5-32b-instruct",1286 "mistral-small-24b", "mistral-nemo-12b", "gemma-2-27b"1287 ],1288}1289```12901291### Model Selection Logic12921293```python1294from typing import Optional12951296class ModelSelector:1297 """Select optimal model for task based on availability and requirements."""12981299 def __init__(self, available_models: list[str]):1300 self.available = set(m.lower() for m in available_models)13011302 def select(1303 self,1304 category: TaskCategory,1305 required_context: int = 0,1306 max_vram_gb: Optional[float] = None1307 ) -> Optional[str]:1308 """Select best available model for task category."""13091310 # Get priority list for category1311 priority_list = TASK_MODEL_PRIORITY.get(category, [])13121313 for model_id in priority_list:1314 # Check if model is available1315 if not self._is_available(model_id):1316 continue13171318 # Check model capability1319 capability = MODEL_DATABASE.get(model_id)1320 if not capability:1321 continue13221323 # Check context window requirement1324 if required_context > 0 and capability.context_window < required_context:1325 continue13261327 # Check VRAM constraint1328 if max_vram_gb and capability.vram_gb > max_vram_gb:1329 continue13301331 return model_id13321333 # Fallback: return any available model1334 for model_id, capability in MODEL_DATABASE.items():1335 if self._is_available(model_id):1336 return model_id13371338 return None13391340 def _is_available(self, model_id: str) -> bool:1341 """Check if model is available (fuzzy matching)."""1342 model_lower = model_id.lower()13431344 # Exact match1345 if model_lower in self.available:1346 return True13471348 # Partial match (model name contained in available)1349 for avail in self.available:1350 if model_lower in avail or avail in model_lower:1351 return True13521353 return False13541355 def get_fallback_models(self, category: TaskCategory) -> list[str]:1356 """Get list of fallback models for category."""1357 priority_list = TASK_MODEL_PRIORITY.get(category, [])13581359 available_in_priority = [1360 m for m in priority_list if self._is_available(m)1361 ]13621363 # Return tier 2 and 3 models as fallbacks1364 fallbacks = []1365 for model_id in available_in_priority:1366 capability = MODEL_DATABASE.get(model_id)1367 if capability and capability.tier >= 2:1368 fallbacks.append(model_id)13691370 return fallbacks1371```13721373## Context Management13741375### Token Counting13761377```python1378from abc import ABC, abstractmethod1379import re13801381class TokenCounter(ABC):1382 """Base class for token counting."""13831384 @abstractmethod1385 def count(self, text: str) -> int:1386 pass13871388class EstimationCounter(TokenCounter):1389 """Estimation-based token counter (no external dependencies)."""13901391 def __init__(self, chars_per_token: float = 4.0):1392 self.chars_per_token = chars_per_token13931394 def count(self, text: str) -> int:1395 return int(len(text) / self.chars_per_token)13961397class QwenCounter(TokenCounter):1398 """Token counter for Qwen models."""13991400 def count(self, text: str) -> int:1401 # Qwen uses slightly different tokenization1402 return int(len(text) / 3.5)14031404class LlamaCounter(TokenCounter):1405 """Token counter for Llama models."""14061407 def count(self, text: str) -> int:1408 # Llama uses SentencePiece1409 return int(len(text) / 3.8)14101411# Model family to counter mapping1412TOKEN_COUNTERS = {1413 "qwen": QwenCounter(),1414 "deepseek": EstimationCounter(4.0),1415 "llama": LlamaCounter(),1416 "mistral": EstimationCounter(4.0),1417 "mixtral": EstimationCounter(4.0),1418 "default": EstimationCounter(4.0),1419}14201421def get_token_counter(model_id: str) -> TokenCounter:1422 """Get appropriate token counter for model."""1423 capability = MODEL_DATABASE.get(model_id)1424 if capability:1425 return TOKEN_COUNTERS.get(capability.family, TOKEN_COUNTERS["default"])1426 return TOKEN_COUNTERS["default"]1427```14281429### Context Manager14301431```python1432from dataclasses import dataclass, field1433from datetime import datetime1434from typing import Optional14351436@dataclass1437class Message:1438 role: str # 'system', 'user', 'assistant', 'tool'1439 content: str1440 timestamp: datetime = field(default_factory=datetime.now)1441 token_count: int = 01442 metadata: dict = field(default_factory=dict)14431444@dataclass1445class ConversationContext:1446 session_id: str1447 messages: list[Message] = field(default_factory=list)1448 total_tokens: int = 01449 system_prompt: str = ""1450 system_prompt_tokens: int = 01451 active_model: str = ""1452 model_history: list[str] = field(default_factory=list)1453 compaction_count: int = 014541455class ContextManager:1456 """Manage conversation context with compaction support."""14571458 def __init__(1459 self,1460 session_id: str,1461 system_prompt: str = "",1462 compaction_threshold: float = 0.8, # 80% of context window1463 compaction_target: float = 0.5, # Compact to 50%1464 preserve_recent: int = 10 # Keep last N messages1465 ):1466 self.context = ConversationContext(1467 session_id=session_id,1468 system_prompt=system_prompt1469 )1470 self.compaction_threshold = compaction_threshold1471 self.compaction_target = compaction_target1472 self.preserve_recent = preserve_recent1473 self._counter: Optional[TokenCounter] = None14741475 def set_model(self, model_id: str):1476 """Set active model and update token counter."""1477 if self.context.active_model:1478 self.context.model_history.append(self.context.active_model)1479 self.context.active_model = model_id1480 self._counter = get_token_counter(model_id)14811482 # Recount all tokens with new counter1483 self._recount_tokens()14841485 def add_message(self, role: str, content: str, metadata: dict = None):1486 """Add message to context."""1487 token_count = self._counter.count(content) if self._counter else 014881489 message = Message(1490 role=role,1491 content=content,1492 token_count=token_count,1493 metadata=metadata or {}1494 )14951496 self.context.messages.append(message)1497 self.context.total_tokens += token_count14981499 def check_and_compact(self, max_tokens: int) -> bool:1500 """Check if compaction needed and perform if so."""1501 threshold = int(max_tokens * self.compaction_threshold)15021503 if self.context.total_tokens > threshold:1504 self._compact(max_tokens)1505 return True1506 return False15071508 def _compact(self, max_tokens: int):1509 """Compact context to target size."""1510 target = int(max_tokens * self.compaction_target)15111512 # Step 1: Truncate large tool outputs1513 for msg in self.context.messages:1514 if msg.role == 'tool' and msg.token_count > 500:1515 original = msg.token_count1516 msg.content = f"[Tool output truncated - {msg.metadata.get('tool_name', 'unknown')}]"1517 msg.token_count = self._counter.count(msg.content)1518 msg.metadata['truncated'] = True1519 msg.metadata['original_tokens'] = original15201521 self._recalculate_total()15221523 if self.context.total_tokens <= target:1524 return15251526 # Step 2: Summarize older messages1527 if len(self.context.messages) > self.preserve_recent:1528 older = self.context.messages[:-self.preserve_recent]1529 recent = self.context.messages[-self.preserve_recent:]15301531 # Create summary of older messages1532 summary = self._create_summary(older)1533 summary_msg = Message(1534 role='system',1535 content=f"[Previous conversation summary]\n{summary}",1536 token_count=self._counter.count(summary),1537 metadata={'compacted': True}1538 )15391540 self.context.messages = [summary_msg] + recent1541 self.context.compaction_count += 115421543 self._recalculate_total()15441545 def _create_summary(self, messages: list[Message]) -> str:1546 """Create summary of messages (simple implementation)."""1547 # In production, this would use a lightweight LLM1548 key_points = []15491550 for msg in messages:1551 if msg.role == 'user':1552 # Extract first sentence of user queries1553 first_sentence = msg.content.split('.')[0][:100]1554 key_points.append(f"- User asked: {first_sentence}")1555 elif msg.role == 'assistant' and len(key_points) < 10:1556 # Extract key decisions/results1557 if 'created' in msg.content.lower() or 'implemented' in msg.content.lower():1558 first_sentence = msg.content.split('.')[0][:100]1559 key_points.append(f"- Assistant: {first_sentence}")15601561 return "\n".join(key_points[:10])15621563 def _recount_tokens(self):1564 """Recount all tokens with current counter."""1565 if not self._counter:1566 return15671568 self.context.system_prompt_tokens = self._counter.count(self.context.system_prompt)1569 for msg in self.context.messages:1570 msg.token_count = self._counter.count(msg.content)1571 self._recalculate_total()15721573 def _recalculate_total(self):1574 """Recalculate total token count."""1575 self.context.total_tokens = (1576 self.context.system_prompt_tokens +1577 sum(m.token_count for m in self.context.messages)1578 )15791580 def export_for_api(self) -> list[dict]:1581 """Export messages in API format."""1582 messages = []15831584 if self.context.system_prompt:1585 messages.append({1586 "role": "system",1587 "content": self.context.system_prompt1588 })15891590 for msg in self.context.messages:1591 messages.append({1592 "role": msg.role,1593 "content": msg.content1594 })15951596 return messages15971598 def prepare_handoff(self, new_model: str) -> "ContextManager":1599 """Prepare context for model switch."""1600 self.set_model(new_model)1601 return self1602```16031604## Configuration16051606### Inline Configuration Schema16071608```python1609from dataclasses import dataclass, field1610from typing import Optional16111612@dataclass1613class ServiceConfig:1614 """Configuration for a single LLM service."""1615 enabled: bool = True1616 endpoint: str = ""1617 priority: int = 11618 timeout: int = 300001619 max_retries: int = 31620 api_style: str = "openai"16211622@dataclass1623class TaskRoutingConfig:1624 """Configuration for task routing."""1625 primary_models: list[str] = field(default_factory=list)1626 fallback_models: list[str] = field(default_factory=list)1627 min_context: int = 81921628 require_serena: bool = False16291630@dataclass1631class SecurityConfig:1632 """Security configuration for air-gapped networks."""1633 allow_external: bool = False1634 allowed_hosts: list[str] = field(default_factory=lambda: [1635 "localhost", "127.0.0.1", "host.docker.internal"1636 ])1637 allowed_cidrs: list[str] = field(default_factory=lambda: [1638 "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12"1639 ])1640 audit_enabled: bool = True1641 audit_log_path: str = "./audit.log"1642 log_queries: bool = True1643 log_responses: bool = False # Don't log sensitive responses1644 verify_checksums: bool = True16451646@dataclass1647class ContextConfig:1648 """Context management configuration."""1649 compaction_threshold: float = 0.81650 compaction_target: float = 0.51651 preserve_recent_messages: int = 101652 preserve_recent_tool_calls: int = 51653 max_tool_output_tokens: int = 50016541655@dataclass1656class RouterConfig:1657 """Complete router configuration."""1658 # Services1659 ollama: ServiceConfig = field(default_factory=lambda: ServiceConfig(1660 endpoint="http://localhost:11434",1661 priority=11662 ))1663 lmstudio: ServiceConfig = field(default_factory=lambda: ServiceConfig(1664 endpoint="http://localhost:1234",1665 priority=21666 ))1667 jan: ServiceConfig = field(default_factory=lambda: ServiceConfig(1668 endpoint="http://localhost:1337",1669 priority=31670 ))1671 custom_endpoints: list[dict] = field(default_factory=list)16721673 # Task routing (Updated January 2025)1674 coding: TaskRoutingConfig = field(default_factory=lambda: TaskRoutingConfig(1675 primary_models=["deepseek-v3", "qwen2.5-coder-32b", "deepseek-coder-v2"],1676 fallback_models=["codellama-34b", "qwen2.5-coder-14b", "phi-4"],1677 min_context=81921678 ))1679 reasoning: TaskRoutingConfig = field(default_factory=lambda: TaskRoutingConfig(1680 primary_models=["deepseek-r1", "deepseek-v3", "qwen2.5-72b-instruct"],1681 fallback_models=["deepseek-r1-distill-32b", "mistral-small-24b"],1682 min_context=163841683 ))1684 analysis: TaskRoutingConfig = field(default_factory=lambda: TaskRoutingConfig(1685 primary_models=["deepseek-v3", "qwen2.5-coder-32b"],1686 fallback_models=["codellama-34b-instruct", "qwen2.5-72b-instruct"],1687 min_context=16384,1688 require_serena=True1689 ))1690 documentation: TaskRoutingConfig = field(default_factory=lambda: TaskRoutingConfig(1691 primary_models=["qwen2.5-72b-instruct", "llama-3.3-70b-instruct"],1692 fallback_models=["qwen2.5-32b-instruct", "mistral-nemo-12b"],1693 min_context=81921694 ))16951696 # Serena1697 serena_enabled: bool = True1698 serena_priority: str = "always_first"16991700 # Context1701 context: ContextConfig = field(default_factory=ContextConfig)17021703 # Security1704 security: SecurityConfig = field(default_factory=SecurityConfig)17051706# Default configuration instance1707DEFAULT_CONFIG = RouterConfig()17081709def load_config_from_dict(data: dict) -> RouterConfig:1710 """Load configuration from dictionary (e.g., parsed YAML)."""1711 config = RouterConfig()17121713 # Update services1714 if 'services' in data:1715 for service_name, service_data in data['services'].items():1716 if hasattr(config, service_name):1717 setattr(config, service_name, ServiceConfig(**service_data))17181719 # Update task routing1720 for category in ['coding', 'reasoning', 'analysis', 'documentation']:1721 if category in data.get('task_routing', {}):1722 setattr(config, category, TaskRoutingConfig(**data['task_routing'][category]))17231724 # Update security1725 if 'security' in data:1726 config.security = SecurityConfig(**data['security'])17271728 return config1729```17301731### Example YAML Configuration (for reference)17321733```yaml1734# local-llm-router.yaml1735# Copy this to your project and customize17361737version: "1.0"1738environment: "air-gapped"17391740services:1741 ollama:1742 enabled: true1743 endpoint: "http://localhost:11434"1744 priority: 11745 timeout: 3000017461747 lmstudio:1748 enabled: true1749 endpoint: "http://localhost:1234"1750 priority: 217511752 jan:1753 enabled: false1754 endpoint: "http://localhost:1337"1755 priority: 317561757 custom_endpoints:1758 - name: "internal-gpu-server"1759 endpoint: "http://192.168.1.100:8000"1760 priority: 01761 api_style: "openai"17621763task_routing:1764 coding:1765 primary_models:1766 - "deepseek-v3"1767 - "qwen2.5-coder-32b"1768 - "deepseek-coder-v2"1769 fallback_models:1770 - "codellama-34b"1771 - "qwen2.5-coder-14b"1772 - "phi-4"1773 min_context: 819217741775 reasoning:1776 primary_models:1777 - "deepseek-r1"1778 - "deepseek-v3"1779 - "qwen2.5-72b-instruct"1780 fallback_models:1781 - "deepseek-r1-distill-32b"1782 - "mistral-small-24b"1783 min_context: 1638417841785 analysis:1786 primary_models:1787 - "deepseek-v3"1788 - "qwen2.5-coder-32b"1789 require_serena: true17901791 documentation:1792 primary_models:1793 - "qwen2.5-72b-instruct"1794 - "llama-3.3-70b-instruct"1795 fallback_models:1796 - "mistral-nemo-12b"17971798serena:1799 enabled: true1800 priority: "always_first"1801 workspace: "${WORKSPACE_ROOT}"18021803context:1804 compaction_threshold: 0.81805 preserve_recent_messages: 1018061807security:1808 allow_external: false1809 allowed_hosts:1810 - "localhost"1811 - "127.0.0.1"1812 - "192.168.0.0/16"1813 audit_enabled: true1814 audit_log_path: "./llm-router-audit.log"1815```18161817## Fallback Strategy18181819### Graceful Degradation18201821```python1822from enum import IntEnum1823from dataclasses import dataclass1824from typing import Optional, Any18251826class FallbackLevel(IntEnum):1827 PRIMARY = 01828 FALLBACK_MODELS = 11829 REDUCED_CONTEXT = 21830 SMALLEST_MODEL = 31831 FAILED = 418321833@dataclass1834class ExecutionResult:1835 success: bool1836 model: Optional[str] = None1837 service: Optional[str] = None1838 response: Any = None1839 fallback_level: FallbackLevel = FallbackLevel.PRIMARY1840 error: Optional[str] = None18411842class FallbackExecutor:1843 """Execute queries with multi-level fallback."""18441845 def __init__(1846 self,1847 discovery: ServiceDiscovery,1848 context_manager: ContextManager,1849 config: RouterConfig1850 ):1851 self.discovery = discovery1852 self.context = context_manager1853 self.config = config18541855 async def execute_with_fallback(1856 self,1857 query: str,1858 category: TaskCategory1859 ) -> ExecutionResult:1860 """Execute query with fallback strategy."""18611862 # Get model lists1863 task_config = getattr(self.config, category.value)1864 primary_models = task_config.primary_models1865 fallback_models = task_config.fallback_models18661867 # Level 0: Try primary models1868 for model in primary_models:1869 result = await self._try_model(model, query)1870 if result.success:1871 result.fallback_level = FallbackLevel.PRIMARY1872 return result18731874 # Level 1: Try fallback models1875 for model in fallback_models:1876 result = await self._try_model(model, query)1877 if result.success:1878 result.fallback_level = FallbackLevel.FALLBACK_MODELS1879 return result18801881 # Level 2: Reduce context and retry1882 self.context._compact(task_config.min_context)1883 for model in primary_models + fallback_models:1884 result = await self._try_model(model, query)1885 if result.success:1886 result.fallback_level = FallbackLevel.REDUCED_CONTEXT1887 return result18881889 # Level 3: Use smallest available model1890 smallest = await self._find_smallest_model()1891 if smallest:1892 result = await self._try_model(smallest, query)1893 if result.success:1894 result.fallback_level = FallbackLevel.SMALLEST_MODEL1895 return result18961897 # Level 4: All failed1898 return ExecutionResult(1899 success=False,1900 fallback_level=FallbackLevel.FAILED,1901 error="All fallback strategies exhausted"1902 )19031904 async def _try_model(self, model_id: str, query: str) -> ExecutionResult:1905 """Try executing query on specific model."""1906 # Find service with this model1907 service = await self._find_service_with_model(model_id)1908 if not service:1909 return ExecutionResult(1910 success=False,1911 error=f"Model {model_id} not available"1912 )19131914 try:1915 response = await self._execute_on_service(service, model_id, query)1916 return ExecutionResult(1917 success=True,1918 model=model_id,1919 service=service.name,1920 response=response1921 )1922 except Exception as e:1923 return ExecutionResult(1924 success=False,1925 error=str(e)1926 )19271928 async def _find_service_with_model(self, model_id: str) -> Optional[LLMService]:1929 """Find service that has the specified model."""1930 services = list(self.discovery.services.values())19311932 # Sort by priority1933 services.sort(key=lambda s: getattr(self.config, s.type, ServiceConfig()).priority)19341935 for service in services:1936 for model in service.models:1937 if model_id.lower() in model.id.lower() or model.id.lower() in model_id.lower():1938 return service19391940 return None19411942 async def _find_smallest_model(self) -> Optional[str]:1943 """Find smallest available model by VRAM requirement."""1944 smallest = None1945 smallest_vram = float('inf')19461947 for service in self.discovery.services.values():1948 for model in service.models:1949 capability = MODEL_DATABASE.get(model.id)1950 if capability and capability.vram_gb < smallest_vram:1951 smallest = model.id1952 smallest_vram = capability.vram_gb19531954 return smallest19551956 async def _execute_on_service(1957 self,1958 service: LLMService,1959 model_id: str,1960 query: str1961 ) -> str:1962 """Execute query on specific service."""1963 import httpx19641965 messages = self.context.export_for_api()1966 messages.append({"role": "user", "content": query})19671968 async with httpx.AsyncClient() as client:1969 if service.api_style == 'native' and service.type == 'ollama':1970 # Ollama native API1971 response = await client.post(1972 f"{service.endpoint}{service.chat_path}",1973 json={1974 "model": model_id,1975 "messages": messages,1976 "stream": False1977 },1978 timeout=self.config.ollama.timeout / 10001979 )1980 data = response.json()1981 return data.get('message', {}).get('content', '')19821983 else:1984 # OpenAI-compatible API1985 response = await client.post(1986 f"{service.endpoint}{service.chat_path}",1987 json={1988 "model": model_id,1989 "messages": messages,1990 "stream": False1991 },1992 timeout=301993 )1994 data = response.json()1995 return data.get('choices', [{}])[0].get('message', {}).get('content', '')1996```19971998## Security (Air-Gapped)19992000### Network Isolation20012002```python2003import hashlib2004import json2005from datetime import datetime2006from dataclasses import dataclass2007from typing import Optional2008import ipaddress2009import logging20102011@dataclass2012class AuditLogEntry:2013 timestamp: str2014 event_type: str2015 session_id: Optional[str] = None2016 model: Optional[str] = None2017 service: Optional[str] = None2018 query_hash: Optional[str] = None # Hashed, not plaintext2019 tokens_in: int = 02020 tokens_out: int = 02021 success: bool = True2022 error: Optional[str] = None20232024class SecurityModule:2025 """Security enforcement for air-gapped networks."""20262027 def __init__(self, config: SecurityConfig):2028 self.config = config2029 self._allowed_ips = self._parse_allowed_networks()2030 self._logger = self._setup_audit_logger()20312032 def _parse_allowed_networks(self) -> list:2033 """Parse allowed hosts and CIDRs."""2034 networks = []20352036 for host in self.config.allowed_hosts:2037 if '/' in host:2038 # CIDR notation2039 networks.append(ipaddress.ip_network(host, strict=False))2040 else:2041 # Single host2042 try:2043 ip = ipaddress.ip_address(host)2044 networks.append(ipaddress.ip_network(f"{ip}/32"))2045 except ValueError:2046 # Hostname like 'localhost'2047 if host == 'localhost':2048 networks.append(ipaddress.ip_network("127.0.0.0/8"))2049 elif host == 'host.docker.internal':2050 # Allow common Docker host IPs2051 networks.append(ipaddress.ip_network("172.17.0.0/16"))20522053 for cidr in self.config.allowed_cidrs:2054 networks.append(ipaddress.ip_network(cidr, strict=False))20552056 return networks20572058 def _setup_audit_logger(self) -> logging.Logger:2059 """Setup audit logger."""2060 logger = logging.getLogger('llm-router-audit')2061 logger.setLevel(logging.INFO)20622063 if self.config.audit_enabled:2064 handler = logging.FileHandler(self.config.audit_log_path)2065 handler.setFormatter(logging.Formatter('%(message)s'))2066 logger.addHandler(handler)20672068 return logger20692070 def validate_endpoint(self, url: str) -> bool:2071 """Validate that endpoint is in allowed network."""2072 if self.config.allow_external:2073 return True20742075 try:2076 from urllib.parse import urlparse2077 parsed = urlparse(url)2078 host = parsed.hostname20792080 # Check for localhost2081 if host in ['localhost', '127.0.0.1', '::1']:2082 return True20832084 # Check against allowed networks2085 try:2086 ip = ipaddress.ip_address(host)2087 for network in self._allowed_ips:2088 if ip in network:2089 return True2090 except ValueError:2091 # Hostname - only allow specific ones2092 return host in ['localhost', 'host.docker.internal']20932094 return False20952096 except Exception:2097 return False20982099 def log_query(2100 self,2101 session_id: str,2102 model: str,2103 service: str,2104 query: str,2105 tokens_in: int,2106 tokens_out: int,2107 success: bool,2108 error: Optional[str] = None2109 ):2110 """Log query for audit trail."""2111 if not self.config.audit_enabled:2112 return21132114 entry = AuditLogEntry(2115 timestamp=datetime.now().isoformat(),2116 event_type='query',2117 session_id=session_id,2118 model=model,2119 service=service,2120 query_hash=self._hash_content(query) if self.config.log_queries else None,2121 tokens_in=tokens_in,2122 tokens_out=tokens_out,2123 success=success,2124 error=error2125 )21262127 self._logger.info(json.dumps(entry.__dict__))21282129 def log_security_event(self, event_type: str, details: dict):2130 """Log security-related event."""2131 if not self.config.audit_enabled:2132 return21332134 entry = {2135 'timestamp': datetime.now().isoformat(),2136 'event_type': f'security:{event_type}',2137 **details2138 }21392140 self._logger.warning(json.dumps(entry))21412142 def _hash_content(self, content: str) -> str:2143 """Hash content for audit logging (privacy)."""2144 return hashlib.sha256(content.encode()).hexdigest()[:16]21452146# Security checklist for air-gapped deployment2147AIR_GAPPED_CHECKLIST = """2148## Air-Gapped Deployment Checklist21492150### Network2151- [ ] Verify no external DNS resolution2152- [ ] Block all egress traffic at firewall2153- [ ] Whitelist only internal IP ranges2154- [ ] Disable IPv6 if not needed21552156### Model Verification2157- [ ] Pre-download all required models2158- [ ] Generate SHA256 checksums for all models2159- [ ] Store checksums in tamper-evident location2160- [ ] Verify checksums before loading models21612162### Access Control2163- [ ] Implement role-based access to LLM services2164- [ ] Require authentication for all endpoints2165- [ ] Use short-lived tokens for API access2166- [ ] Log all access attempts21672168### Audit2169- [ ] Enable comprehensive audit logging2170- [ ] Log queries (hashed, not plaintext)2171- [ ] Log model usage patterns2172- [ ] Log all security events2173- [ ] Implement log rotation and retention2174"""2175```21762177## Coding Agent Detection21782179### Detect Active Coding Agent21802181```python2182import os2183import sys2184from dataclasses import dataclass2185from typing import Optional21862187@dataclass2188class CodingAgentInfo:2189 name: str2190 type: str2191 version: Optional[str] = None2192 config_path: Optional[str] = None21932194# Environment variable markers for different agents2195AGENT_ENV_MARKERS = {2196 # CLI-based agents2197 'QWEN_CLI_VERSION': ('qwen-cli', 'cli'),2198 'OPENCODE_SESSION': ('opencode', 'cli'),2199 'AIDER_SESSION': ('aider', 'cli'),2200 'CODEX_SESSION': ('codex', 'cli'),2201 'GEMINI_CLI_SESSION': ('gemini-cli', 'cli'),22022203 # IDE extensions2204 'CONTINUE_SESSION': ('continue', 'ide'),2205 'CLINE_SESSION': ('cline', 'ide'),2206 'ROO_CODE_SESSION': ('roo-code', 'ide'),2207 'CURSOR_SESSION': ('cursor', 'ide'),22082209 # Local GUI apps2210 'OPENWEBUI_SESSION': ('openwebui', 'gui'),2211 'JAN_SESSION': ('jan', 'gui'),2212 'AGNO_SESSION': ('agno', 'gui'),22132214 # Generic markers2215 'LLM_AGENT': ('generic', 'unknown'),2216}22172218def detect_coding_agent() -> CodingAgentInfo:2219 """Detect which coding agent is invoking the router."""22202221 # Check environment variables2222 for env_var, (name, agent_type) in AGENT_ENV_MARKERS.items():2223 value = os.environ.get(env_var)2224 if value:2225 return CodingAgentInfo(2226 name=name,2227 type=agent_type,2228 version=value if value != '1' else None2229 )22302231 # Check process name / parent process2232 try:2233 import psutil2234 parent = psutil.Process(os.getppid())2235 parent_name = parent.name().lower()22362237 agent_process_names = {2238 'qwen': 'qwen-cli',2239 'aider': 'aider',2240 'codex': 'codex',2241 'continue': 'continue',2242 'cursor': 'cursor',2243 }22442245 for proc_name, agent_name in agent_process_names.items():2246 if proc_name in parent_name:2247 return CodingAgentInfo(name=agent_name, type='detected')22482249 except ImportError:2250 pass # psutil not available22512252 # Check for MCP client markers2253 if os.environ.get('MCP_CLIENT'):2254 return CodingAgentInfo(2255 name=os.environ.get('MCP_CLIENT', 'mcp-client'),2256 type='mcp'2257 )22582259 # Default: unknown2260 return CodingAgentInfo(name='unknown', type='unknown')22612262def get_agent_specific_config(agent: CodingAgentInfo) -> dict:2263 """Get agent-specific configuration overrides."""22642265 configs = {2266 'qwen-cli': {2267 'default_model_preference': 'qwen',2268 'context_format': 'qwen',2269 },2270 'aider': {2271 'default_model_preference': 'gpt',2272 'context_format': 'openai',2273 },2274 'cursor': {2275 'default_model_preference': 'claude',2276 'context_format': 'anthropic',2277 },2278 'continue': {2279 'supports_streaming': True,2280 'context_format': 'openai',2281 },2282 }22832284 return configs.get(agent.name, {})2285```22862287## Complete Router Implementation22882289```python2290class LocalLLMRouter:2291 """2292 Complete Local LLM Router with Serena integration.22932294 Usage:2295 router = LocalLLMRouter(workspace="/path/to/project")2296 await router.initialize()22972298 response = await router.route("Implement a binary search function")2299 print(response)2300 """23012302 def __init__(2303 self,2304 workspace: str,2305 config: RouterConfig = None,2306 session_id: str = None2307 ):2308 self.workspace = workspace2309 self.config = config or DEFAULT_CONFIG2310 self.session_id = session_id or self._generate_session_id()23112312 # Components2313 self.serena: Optional[SerenaMCP] = None2314 self.discovery: Optional[ServiceDiscovery] = None2315 self.context: Optional[ContextManager] = None2316 self.security: Optional[SecurityModule] = None2317 self.selector: Optional[ModelSelector] = None2318 self.fallback: Optional[FallbackExecutor] = None23192320 # State2321 self.os_info = detect_os()2322 self.coding_agent = detect_coding_agent()2323 self._initialized = False23242325 async def initialize(self):2326 """Initialize all router components."""23272328 # Security module2329 self.security = SecurityModule(self.config.security)23302331 # Service discovery2332 self.discovery = ServiceDiscovery(self.config.custom_endpoints)2333 services = await self.discovery.discover_all()23342335 if not services:2336 raise RuntimeError("No local LLM services available")23372338 # Model selector2339 all_models = []2340 for service in services:2341 all_models.extend(m.id for m in service.models)2342 self.selector = ModelSelector(all_models)23432344 # Context manager2345 self.context = ContextManager(2346 session_id=self.session_id,2347 system_prompt=self._build_system_prompt(),2348 compaction_threshold=self.config.context.compaction_threshold,2349 compaction_target=self.config.context.compaction_target,2350 preserve_recent=self.config.context.preserve_recent_messages2351 )23522353 # Serena MCP (if enabled)2354 if self.config.serena_enabled:2355 self.serena = SerenaMCP(self.workspace)2356 try:2357 await self.serena.start()2358 except Exception as e:2359 logging.warning(f"Serena MCP failed to start: {e}")2360 self.serena = None23612362 # Fallback executor2363 self.fallback = FallbackExecutor(2364 self.discovery,2365 self.context,2366 self.config2367 )23682369 self._initialized = True23702371 async def route(2372 self,2373 query: str,2374 file_context: dict = None2375 ) -> str:2376 """2377 Route query to appropriate LLM.23782379 Args:2380 query: The user's query2381 file_context: Optional dict with 'file', 'position' for code context23822383 Returns:2384 LLM response string2385 """2386 if not self._initialized:2387 await self.initialize()23882389 # Step 1: Classify task2390 classification = classify_task(query)23912392 # Step 2: Serena first (if code-related)2393 serena_context = {}2394 if self.serena and (classification.requires_serena or file_context):2395 serena_context = await self._gather_serena_context(2396 query, file_context, classification2397 )23982399 # Step 3: Build enriched query2400 enriched_query = self._build_enriched_query(query, serena_context)24012402 # Step 4: Select model2403 model = self.selector.select(2404 classification.category,2405 required_context=self.context.context.total_tokens + len(query) // 42406 )24072408 if not model:2409 raise RuntimeError("No suitable model available")24102411 # Step 5: Update context manager with selected model2412 self.context.set_model(model)24132414 # Step 6: Check context and compact if needed2415 model_capability = MODEL_DATABASE.get(model)2416 if model_capability:2417 self.context.check_and_compact(model_capability.context_window)24182419 # Step 7: Execute with fallback2420 result = await self.fallback.execute_with_fallback(2421 enriched_query,2422 classification.category2423 )24242425 # Step 8: Log for audit2426 self.security.log_query(2427 session_id=self.session_id,2428 model=result.model or model,2429 service=result.service or 'unknown',2430 query=query,2431 tokens_in=len(query) // 4,2432 tokens_out=len(result.response or '') // 4,2433 success=result.success,2434 error=result.error2435 )24362437 if not result.success:2438 raise RuntimeError(f"Query failed: {result.error}")24392440 # Step 9: Update context with response2441 self.context.add_message('user', query)2442 self.context.add_message('assistant', result.response)24432444 # Step 10: Apply edits via Serena if needed2445 if self.serena and file_context and contains_code_edit(result.response):2446 await self._apply_serena_edits(result.response, file_context)24472448 return result.response24492450 async def _gather_serena_context(2451 self,2452 query: str,2453 file_context: dict,2454 classification: ClassificationResult2455 ) -> dict:2456 """Gather code context from Serena."""2457 context = {}24582459 if not file_context:2460 return context24612462 file = file_context.get('file')2463 position = file_context.get('position', {})2464 line = position.get('line', 0)2465 char = position.get('character', 0)24662467 try:2468 # Always get hover info2469 context['hover'] = await self.serena.get_hover_info(file, line, char)24702471 # Get references for refactoring tasks2472 if 'refactor' in query.lower() or 'rename' in query.lower():2473 context['references'] = await self.serena.get_references(file, line, char)24742475 # Get diagnostics for analysis2476 if classification.category == TaskCategory.ANALYSIS:2477 context['diagnostics'] = await self.serena.get_diagnostics(file)24782479 except Exception as e:2480 logging.warning(f"Serena context gathering failed: {e}")24812482 return context24832484 def _build_enriched_query(self, query: str, serena_context: dict) -> str:2485 """Build query enriched with Serena context."""2486 return build_enriched_query(query, serena_context)24872488 async def _apply_serena_edits(self, response: str, file_context: dict):2489 """Apply code edits from response via Serena."""2490 edits = parse_code_edits(response)2491 if edits:2492 await self.serena.apply_edit(file_context['file'], edits)24932494 def _build_system_prompt(self) -> str:2495 """Build system prompt with router context."""2496 return f"""You are a coding assistant running in a local, air-gapped environment.24972498Environment:2499- OS: {self.os_info.platform} ({self.os_info.arch})2500- Coding Agent: {self.coding_agent.name}2501- Serena LSP: {'enabled' if self.config.serena_enabled else 'disabled'}25022503Guidelines:2504- Provide concise, accurate code2505- Use Serena's semantic information when provided2506- Respect security constraints (no external calls)2507- Focus on the specific task at hand2508"""25092510 def _generate_session_id(self) -> str:2511 """Generate unique session ID."""2512 import uuid2513 return str(uuid.uuid4())[:8]25142515# Utility functions2516def contains_code_edit(response: str) -> bool:2517 """Check if response contains code edits."""2518 markers = ['```', 'def ', 'class ', 'function ', 'const ', 'let ', 'var ']2519 return any(marker in response for marker in markers)25202521def parse_code_edits(response: str) -> list:2522 """Parse code edits from response."""2523 # Simple implementation - extract code blocks2524 import re2525 code_blocks = re.findall(r'```(?:\w+)?\n(.*?)```', response, re.DOTALL)2526 return [{'content': block.strip()} for block in code_blocks]2527```25282529## Resources25302531- **Serena MCP**: https://github.com/oraios/serena2532- **Serena Documentation**: https://github.com/oraios/serena#user-guide2533- **Ollama API**: https://github.com/ollama/ollama/blob/main/docs/api.md2534- **LM Studio**: https://lmstudio.ai/docs/developer2535- **Jan AI**: https://jan.ai/docs/desktop/api-server2536- **OpenWebUI**: https://docs.openwebui.com/2537- **LocalAI**: https://localai.io/basics/getting_started/