Buckets:

download
raw
28.8 kB
"""
Configuration validator using JSON schemas.
Provides validation for:
- Model configurations
- Tool configurations
- Prompt configurations
- API key configurations
- Agent configurations
Features:
- JSON Schema validation
- Cross-reference validation
- Semantic validation
- Security checks
- Custom validation rules
"""
from __future__ import annotations
import importlib.util as _importlib_util
import logging
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from effgen.errors import quote_for_message, with_next_step
# jsonschema is heavy to import (it pulls rfc3987 / referencing). We only probe
# availability here via find_spec — which does not execute the module — and
# import Draft7Validator lazily at the single call site below. This keeps the
# config layer (and the CLI, which loads config on startup) cheap to import.
JSONSCHEMA_AVAILABLE = _importlib_util.find_spec("jsonschema") is not None
logger = logging.getLogger(__name__)
class ValidationError(ValueError):
"""Configuration validation error.
Derives from :class:`ValueError` because that is what the loader's
``validate_config`` has always documented itself as raising; code catching
either name keeps working.
"""
def __init__(self, message: str, errors: list[str] | None = None) -> None:
"""
Initialize validation error.
Args:
message: Error message
errors: List of specific validation errors
"""
super().__init__(message)
self.errors = errors or []
_FOLLOW_ON = (
"Correct the keys named above in the configuration file, then re-run; "
"`effgen config show` prints the merged configuration effGen reads."
)
def __str__(self) -> str:
"""Format the message, each specific error, and how to fix them."""
head = quote_for_message(super().__str__())
if not self.errors:
return with_next_step(head, self._FOLLOW_ON)
error_list = "\n - ".join(quote_for_message(e) for e in self.errors)
return f"{head}\n - {error_list}\n\n{self._FOLLOW_ON}"
@dataclass
class ValidationResult:
"""Result of configuration validation."""
valid: bool
errors: list[str] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
def add_error(self, error: str) -> None:
"""Add an error."""
self.errors.append(error)
self.valid = False
def add_warning(self, warning: str) -> None:
"""Add a warning."""
self.warnings.append(warning)
#: Sections that only a tool-registry document (configs/tools.yaml) carries.
#: Their presence is what separates it from the application config, which uses
#: the same ``tools:`` key for feature switches.
_TOOL_REGISTRY_MARKERS = ("mcp_servers", "custom_tools", "tool_selection")
def _is_tool_registry(document: dict[str, Any]) -> bool:
"""Whether *document* is a tool registry rather than an application config.
Args:
document: The whole configuration document.
Returns:
True when the document carries a section only a tool registry has.
"""
return any(marker in document for marker in _TOOL_REGISTRY_MARKERS)
def _document(config: Any, label: str, result: ValidationResult) -> dict[str, Any]:
"""Return *config* when it is a mapping, else record an error and return {}.
A config document is whatever a file on disk held, so a section may be any
type. Validation reports a wrong-typed document as a validation error — that
is what validation is for — rather than raising out of the check.
"""
if isinstance(config, dict):
return config
result.add_error(
f"{label} must be a mapping of settings, got {type(config).__name__}"
)
return {}
def _section(
config: dict[str, Any], key: str, result: ValidationResult
) -> dict[str, Any]:
"""Return the ``key`` section of *config* when it is a mapping, else {}."""
if key not in config:
return {}
return _document(config[key], f"'{key}'", result)
def _entry(value: Any, label: str, result: ValidationResult) -> dict[str, Any]:
"""Return one section entry when it is a mapping, else record an error."""
if isinstance(value, dict):
return value
result.add_error(f"{label} must be a mapping, got {type(value).__name__}")
return {}
class ConfigValidator:
"""
Configuration validator with JSON Schema support.
Validates:
- Syntax (via JSON schema)
- Semantics (cross-references, constraints)
- Security (no plaintext secrets in non-key files)
"""
def __init__(self, schema_dir: Path | None = None) -> None:
"""
Initialize validator.
Args:
schema_dir: Directory containing JSON schemas
"""
if not JSONSCHEMA_AVAILABLE:
logger.warning("jsonschema not installed. Validation will be limited.")
self.schema_dir = schema_dir or Path(__file__).parent / "schemas"
self._schemas: dict[str, dict] = {}
self._load_schemas()
def _load_schemas(self) -> None:
"""Load JSON schemas from schema directory."""
if not self.schema_dir.exists():
logger.warning(f"Schema directory not found: {self.schema_dir}")
return
import json
for schema_file in self.schema_dir.glob("*.json"):
try:
with open(schema_file) as f:
schema = json.load(f)
schema_name = schema_file.stem
self._schemas[schema_name] = schema
logger.debug(f"Loaded schema: {schema_name}")
except Exception as e:
logger.error(f"Failed to load schema {schema_file}: {e}")
def validate_models(self, models_config: dict[str, Any]) -> ValidationResult:
"""
Validate models configuration.
Args:
models_config: Models configuration dictionary
Returns:
Validation result
"""
result = ValidationResult(valid=True)
models_config = _document(models_config, "models config", result)
# JSON Schema validation
if JSONSCHEMA_AVAILABLE and "model_config" in self._schemas:
schema_errors = self._validate_with_schema(
models_config,
self._schemas["model_config"]
)
for error in schema_errors:
result.add_error(f"Schema validation: {error}")
# Semantic validation
models = _section(models_config, "models", result)
if models:
for model_name, raw_config in models.items():
model_config = _entry(raw_config, f"Model '{model_name}'", result)
if not model_config:
continue
# Validate model type
model_type = model_config.get("type")
if not model_type:
result.add_error(f"Model '{model_name}' missing 'type' field")
continue
# Validate based on type
if model_type == "huggingface":
self._validate_huggingface_model(model_name, model_config, result)
elif model_type == "openai":
self._validate_openai_model(model_name, model_config, result)
elif model_type == "anthropic":
self._validate_anthropic_model(model_name, model_config, result)
elif model_type == "google":
self._validate_google_model(model_name, model_config, result)
else:
result.add_warning(f"Unknown model type for '{model_name}': {model_type}")
# Validate default model exists
if "default_model" in models_config:
default = models_config["default_model"]
if models and not isinstance(default, list | dict) and default not in models:
result.add_error(f"Default model '{default}' not found in models")
# Validate fallback chain
if "fallback_chain" in models_config:
chain = models_config["fallback_chain"]
if not isinstance(chain, list):
result.add_error(
f"'fallback_chain' must be a list of model names, got "
f"{type(chain).__name__}"
)
else:
for model_name in chain:
if models and not isinstance(model_name, list | dict) \
and model_name not in models:
result.add_error(
f"Fallback model '{model_name}' not found in models"
)
return result
def _validate_huggingface_model(
self,
model_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate HuggingFace model configuration."""
# Required fields
if "model_id" not in config:
result.add_error(f"Model '{model_name}' missing 'model_id' field")
# Validate inference engine
inference_engine = config.get("inference_engine", "transformers")
valid_engines = ["transformers", "vllm", "tgi", "ctransformers", "mlx", "mlx_vlm"]
if inference_engine not in valid_engines:
result.add_error(
f"Model '{model_name}' has invalid inference_engine. "
f"Must be one of: {valid_engines}"
)
# Validate quantization
quantization = config.get("quantization")
if quantization:
valid_quant = ["none", "4bit", "8bit", "awq", "gptq"]
if quantization not in valid_quant:
result.add_warning(
f"Model '{model_name}' has unknown quantization: {quantization}"
)
# Validate GPU devices
gpu_devices = config.get("gpu_devices", [])
if gpu_devices and not isinstance(gpu_devices, list):
result.add_error(f"Model '{model_name}' gpu_devices must be a list")
# Check tensor parallel consistency
tensor_parallel = config.get("tensor_parallel_size")
if tensor_parallel:
if not gpu_devices:
result.add_error(
f"Model '{model_name}' has tensor_parallel_size but no gpu_devices"
)
elif len(gpu_devices) != tensor_parallel:
result.add_warning(
f"Model '{model_name}' tensor_parallel_size ({tensor_parallel}) "
f"doesn't match gpu_devices length ({len(gpu_devices)})"
)
def _validate_openai_model(
self,
model_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate OpenAI model configuration."""
if "model_name" not in config:
result.add_error(f"Model '{model_name}' missing 'model_name' field")
# Validate temperature range
temp = config.get("temperature")
if temp is not None and not (0 <= temp <= 2):
result.add_warning(
f"Model '{model_name}' temperature ({temp}) outside typical range [0, 2]"
)
def _validate_anthropic_model(
self,
model_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate Anthropic model configuration."""
if "model_name" not in config:
result.add_error(f"Model '{model_name}' missing 'model_name' field")
# Validate temperature range
temp = config.get("temperature")
if temp is not None and not (0 <= temp <= 1):
result.add_warning(
f"Model '{model_name}' temperature ({temp}) outside typical range [0, 1]"
)
def _validate_google_model(
self,
model_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate Google model configuration."""
if "model_name" not in config:
result.add_error(f"Model '{model_name}' missing 'model_name' field")
def validate_tools(self, tools_config: dict[str, Any]) -> ValidationResult:
"""
Validate tools configuration.
Args:
tools_config: Tools configuration dictionary
Returns:
Validation result
"""
result = ValidationResult(valid=True)
tools_config = _document(tools_config, "tools config", result)
# JSON Schema validation
if JSONSCHEMA_AVAILABLE and "tool_config" in self._schemas:
schema_errors = self._validate_with_schema(
tools_config,
self._schemas["tool_config"]
)
for error in schema_errors:
result.add_error(f"Schema validation: {error}")
# Validate built-in tools.
#
# A `tools:` section has two shapes in the configs effGen ships, and
# both are correct. In a tool registry (configs/tools.yaml) each entry
# is one tool's settings, so a non-mapping entry is a mistake. In the
# application config (configs/config.yaml) the same key holds feature
# switches — `enable_web_search: true`, `sandbox_timeout: 30` — where a
# scalar is exactly right. Which document this is decides which rule
# applies; judging by the entries alone would reject one of the two
# files effGen itself ships.
tools = _section(tools_config, "tools", result)
registry = _is_tool_registry(tools_config)
for tool_name, tool_config in tools.items():
if not isinstance(tool_config, dict):
if registry:
result.add_error(
f"Tool '{tool_name}' config must be a dictionary"
)
continue
# Check enabled flag
if "enabled" not in tool_config:
result.add_warning(f"Tool '{tool_name}' missing 'enabled' field")
# Validate MCP servers
servers = _section(tools_config, "mcp_servers", result)
for server_name, server_config in servers.items():
entry = _entry(server_config, f"MCP server '{server_name}'", result)
if entry:
self._validate_mcp_server(server_name, entry, result)
# Validate tool selection
selection = _section(tools_config, "tool_selection", result)
if selection:
# Validate mode
mode = selection.get("mode")
if mode and mode not in ["auto", "manual", "hybrid"]:
result.add_error(f"Invalid tool_selection mode: {mode}")
# Validate recommendations reference existing tools
recommendations = _section(selection, "recommendations", result)
if recommendations and tools:
available_tools = set(tools.keys())
available_tools.update(servers.keys())
for task_type, names in recommendations.items():
if not isinstance(names, list | tuple | set):
result.add_error(
f"Recommended tools for task '{task_type}' must be a "
f"list, got {type(names).__name__}"
)
continue
for tool_name in names:
if isinstance(tool_name, list | dict) \
or tool_name not in available_tools:
result.add_warning(
f"Recommended tool '{tool_name}' for task '{task_type}' "
f"not found in available tools"
)
return result
def _validate_mcp_server(
self,
server_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate MCP server configuration."""
# Check required fields
if "command" not in config:
result.add_error(f"MCP server '{server_name}' missing 'command' field")
# Validate type
server_type = config.get("type", "mcp")
if server_type != "mcp":
result.add_warning(
f"MCP server '{server_name}' has unexpected type: {server_type}"
)
# Check environment variables are in correct format
env = config.get("env", {})
if env and not isinstance(env, dict):
result.add_error(f"MCP server '{server_name}' env must be a dictionary")
def validate_prompts(self, prompts_config: dict[str, Any]) -> ValidationResult:
"""
Validate prompts configuration.
Args:
prompts_config: Prompts configuration dictionary
Returns:
Validation result
"""
result = ValidationResult(valid=True)
prompts_config = _document(prompts_config, "prompts config", result)
# Validate system prompts
for prompt_name, prompt_config in _section(
prompts_config, "system_prompts", result
).items():
entry = _entry(prompt_config, f"System prompt '{prompt_name}'", result)
if entry and "template" not in entry:
result.add_error(
f"System prompt '{prompt_name}' missing 'template' field"
)
# Validate prompt chains
for chain_name, chain_config in _section(
prompts_config, "chains", result
).items():
entry = _entry(chain_config, f"Chain '{chain_name}'", result)
if entry:
self._validate_chain(chain_name, entry, result)
# Validate few-shot examples
for example_type, example_config in _section(
prompts_config, "few_shot_examples", result
).items():
entry = _entry(
example_config, f"Few-shot example type '{example_type}'", result
)
if entry and "examples" not in entry:
result.add_error(
f"Few-shot example type '{example_type}' missing 'examples' field"
)
# Validate SLM optimization settings
slm_opt = _section(prompts_config, "slm_optimization", result)
if slm_opt:
# Check reasonable values
max_examples = slm_opt.get("max_few_shot_examples")
if isinstance(max_examples, bool) or not isinstance(
max_examples, int | float
):
if max_examples is not None:
result.add_error(
f"max_few_shot_examples must be a number, got "
f"{type(max_examples).__name__}"
)
elif max_examples > 10:
result.add_warning(
f"max_few_shot_examples ({max_examples}) is quite high. "
f"Consider reducing for SLMs."
)
return result
def _validate_chain(
self,
chain_name: str,
config: dict[str, Any],
result: ValidationResult
) -> None:
"""Validate a prompt chain configuration."""
if "steps" not in config:
result.add_error(f"Chain '{chain_name}' missing 'steps' field")
return
steps = config["steps"]
if not isinstance(steps, list):
result.add_error(f"Chain '{chain_name}' steps must be a list")
return
step_names = set()
output_vars = set()
for i, step in enumerate(steps):
if not isinstance(step, dict):
result.add_error(f"Chain '{chain_name}' step {i} must be a dictionary")
continue
# Check required fields
if "name" not in step:
result.add_error(f"Chain '{chain_name}' step {i} missing 'name' field")
continue
step_name = step["name"]
# Check for duplicate step names
if step_name in step_names:
result.add_error(
f"Chain '{chain_name}' has duplicate step name: {step_name}"
)
step_names.add(step_name)
# Validate step type
step_type = step.get("type", "prompt")
valid_types = ["prompt", "tool", "conditional", "iterative"]
if step_type not in valid_types:
result.add_error(
f"Chain '{chain_name}' step '{step_name}' has invalid type: {step_type}"
)
# Track output variables
if "output_var" in step:
output_vars.add(step["output_var"])
# Validate variable references in prompts
if "prompt" in step:
self._validate_template_vars(
step["prompt"],
output_vars,
f"Chain '{chain_name}' step '{step_name}'",
result
)
def _validate_template_vars(
self,
template: str,
available_vars: set[str],
context: str,
result: ValidationResult
) -> None:
"""Validate that template variables are available."""
# Find all {variable} references
var_pattern = re.compile(r"\{(\w+)\}")
referenced_vars = set(var_pattern.findall(template))
# Check if all referenced variables are available
for var in referenced_vars:
if var not in available_vars:
result.add_warning(
f"{context} references undefined variable: {var}"
)
def validate_api_keys(self, api_keys_config: dict[str, Any]) -> ValidationResult:
"""
Validate API keys configuration.
Checks for:
- Proper structure
- Environment variable format
- No plaintext secrets
Args:
api_keys_config: API keys configuration dictionary
Returns:
Validation result
"""
result = ValidationResult(valid=True)
# Check for plaintext secrets (should use env vars)
self._check_plaintext_secrets(api_keys_config, "", result)
return result
def _check_plaintext_secrets(
self,
config: Any,
path: str,
result: ValidationResult
) -> None:
"""
Recursively check for plaintext secrets.
Args:
config: Configuration to check
path: Current path in config
result: Validation result to update
"""
if isinstance(config, dict):
for key, value in config.items():
current_path = f"{path}.{key}" if path else key
# Check if this looks like a sensitive field
sensitive_keys = [
"key", "token", "password", "secret", "credential",
"api_key", "access_key", "private_key"
]
is_sensitive = any(
sensitive in key.lower() for sensitive in sensitive_keys
)
if is_sensitive and isinstance(value, str):
# Check if it's an environment variable reference
if not (value.startswith("${") and value.endswith("}")):
# Could be a plaintext secret
if len(value) > 10 and not value.startswith("http"):
result.add_error(
f"Possible plaintext secret at '{current_path}'. "
f"Use environment variables: ${{VAR_NAME}}"
)
# Recurse
self._check_plaintext_secrets(value, current_path, result)
elif isinstance(config, list):
for i, item in enumerate(config):
current_path = f"{path}[{i}]"
self._check_plaintext_secrets(item, current_path, result)
def validate_agent(self, agent_config: dict[str, Any]) -> ValidationResult:
"""
Validate agent configuration.
Args:
agent_config: Agent configuration dictionary
Returns:
Validation result
"""
result = ValidationResult(valid=True)
# JSON Schema validation
if JSONSCHEMA_AVAILABLE and "agent_config" in self._schemas:
schema_errors = self._validate_with_schema(
agent_config,
self._schemas["agent_config"]
)
for error in schema_errors:
result.add_error(f"Schema validation: {error}")
# Validate required fields
required_fields = ["name", "model"]
for req_field in required_fields:
if req_field not in agent_config:
result.add_error(f"Agent config missing required field: {req_field}")
return result
def _validate_with_schema(
self,
config: dict[str, Any],
schema: dict[str, Any]
) -> list[str]:
"""
Validate configuration against JSON schema.
Args:
config: Configuration to validate
schema: JSON schema
Returns:
List of validation errors
"""
if not JSONSCHEMA_AVAILABLE:
return []
errors = []
from jsonschema import Draft7Validator
try:
validator = Draft7Validator(schema)
for error in validator.iter_errors(config):
# Format error message
path = ".".join(str(p) for p in error.path) if error.path else "root"
errors.append(f"At '{path}': {error.message}")
except Exception as e:
logger.error(f"Schema validation failed: {e}")
errors.append(f"Schema validation error: {e}")
return errors
def validate_all(
self,
config: dict[str, Any],
config_type: str | None = None
) -> ValidationResult:
"""
Validate a complete configuration.
Args:
config: Configuration dictionary
config_type: Type of config (models, tools, prompts, api_keys, agent)
Returns:
Combined validation result
"""
result = ValidationResult(valid=True)
# Auto-detect config type if not specified
if not config_type:
if "models" in config:
config_type = "models"
elif "tools" in config or "mcp_servers" in config:
config_type = "tools"
elif "system_prompts" in config or "chains" in config:
config_type = "prompts"
# Validate based on type
if config_type == "models":
models_result = self.validate_models(config)
result.errors.extend(models_result.errors)
result.warnings.extend(models_result.warnings)
if not models_result.valid:
result.valid = False
elif config_type == "tools":
tools_result = self.validate_tools(config)
result.errors.extend(tools_result.errors)
result.warnings.extend(tools_result.warnings)
if not tools_result.valid:
result.valid = False
elif config_type == "prompts":
prompts_result = self.validate_prompts(config)
result.errors.extend(prompts_result.errors)
result.warnings.extend(prompts_result.warnings)
if not prompts_result.valid:
result.valid = False
elif config_type == "api_keys":
api_result = self.validate_api_keys(config)
result.errors.extend(api_result.errors)
result.warnings.extend(api_result.warnings)
if not api_result.valid:
result.valid = False
elif config_type == "agent":
agent_result = self.validate_agent(config)
result.errors.extend(agent_result.errors)
result.warnings.extend(agent_result.warnings)
if not agent_result.valid:
result.valid = False
# Raise exception if validation failed
if not result.valid:
raise ValidationError(
f"Configuration validation failed with {len(result.errors)} error(s)",
result.errors
)
# Log warnings
for warning in result.warnings:
logger.warning(warning)
return result

Xet Storage Details

Size:
28.8 kB
·
Xet hash:
b5b9acb2a411ae93dd7f6772acf141f44a38ba3614955c76dce5763f414055d0

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.