|
| 1 | +# api/routes/validation.py |
| 2 | +import importlib |
| 3 | +from typing import Any, Dict, List, Optional |
| 4 | + |
| 5 | +from autogen_core import ComponentModel, is_component_class |
| 6 | +from fastapi import APIRouter, HTTPException |
| 7 | +from pydantic import BaseModel |
| 8 | + |
| 9 | +router = APIRouter() |
| 10 | + |
| 11 | + |
| 12 | +class ValidationRequest(BaseModel): |
| 13 | + component: Dict[str, Any] |
| 14 | + |
| 15 | + |
| 16 | +class ValidationError(BaseModel): |
| 17 | + field: str |
| 18 | + error: str |
| 19 | + suggestion: Optional[str] = None |
| 20 | + |
| 21 | + |
| 22 | +class ValidationResponse(BaseModel): |
| 23 | + is_valid: bool |
| 24 | + errors: List[ValidationError] = [] |
| 25 | + warnings: List[ValidationError] = [] |
| 26 | + |
| 27 | + |
| 28 | +class ValidationService: |
| 29 | + @staticmethod |
| 30 | + def validate_provider(provider: str) -> Optional[ValidationError]: |
| 31 | + """Validate that the provider exists and can be imported""" |
| 32 | + try: |
| 33 | + if provider in ["azure_openai_chat_completion_client", "AzureOpenAIChatCompletionClient"]: |
| 34 | + provider = "autogen_ext.models.openai.AzureOpenAIChatCompletionClient" |
| 35 | + elif provider in ["openai_chat_completion_client", "OpenAIChatCompletionClient"]: |
| 36 | + provider = "autogen_ext.models.openai.OpenAIChatCompletionClient" |
| 37 | + |
| 38 | + module_path, class_name = provider.rsplit(".", maxsplit=1) |
| 39 | + module = importlib.import_module(module_path) |
| 40 | + component_class = getattr(module, class_name) |
| 41 | + |
| 42 | + if not is_component_class(component_class): |
| 43 | + return ValidationError( |
| 44 | + field="provider", |
| 45 | + error=f"Class {provider} is not a valid component class", |
| 46 | + suggestion="Ensure the class inherits from Component and implements required methods", |
| 47 | + ) |
| 48 | + return None |
| 49 | + except ImportError: |
| 50 | + return ValidationError( |
| 51 | + field="provider", |
| 52 | + error=f"Could not import provider {provider}", |
| 53 | + suggestion="Check that the provider module is installed and the path is correct", |
| 54 | + ) |
| 55 | + except Exception as e: |
| 56 | + return ValidationError( |
| 57 | + field="provider", |
| 58 | + error=f"Error validating provider: {str(e)}", |
| 59 | + suggestion="Check the provider string format and class implementation", |
| 60 | + ) |
| 61 | + |
| 62 | + @staticmethod |
| 63 | + def validate_component_type(component: Dict[str, Any]) -> Optional[ValidationError]: |
| 64 | + """Validate the component type""" |
| 65 | + if "component_type" not in component: |
| 66 | + return ValidationError( |
| 67 | + field="component_type", |
| 68 | + error="Component type is missing", |
| 69 | + suggestion="Add a component_type field to the component configuration", |
| 70 | + ) |
| 71 | + return None |
| 72 | + |
| 73 | + @staticmethod |
| 74 | + def validate_config_schema(component: Dict[str, Any]) -> List[ValidationError]: |
| 75 | + """Validate the component configuration against its schema""" |
| 76 | + errors = [] |
| 77 | + try: |
| 78 | + # Convert to ComponentModel for initial validation |
| 79 | + model = ComponentModel(**component) |
| 80 | + |
| 81 | + # Get the component class |
| 82 | + provider = model.provider |
| 83 | + module_path, class_name = provider.rsplit(".", maxsplit=1) |
| 84 | + module = importlib.import_module(module_path) |
| 85 | + component_class = getattr(module, class_name) |
| 86 | + |
| 87 | + # Validate against component's schema |
| 88 | + if hasattr(component_class, "component_config_schema"): |
| 89 | + try: |
| 90 | + component_class.component_config_schema.model_validate(model.config) |
| 91 | + except Exception as e: |
| 92 | + errors.append( |
| 93 | + ValidationError( |
| 94 | + field="config", |
| 95 | + error=f"Config validation failed: {str(e)}", |
| 96 | + suggestion="Check that the config matches the component's schema", |
| 97 | + ) |
| 98 | + ) |
| 99 | + else: |
| 100 | + errors.append( |
| 101 | + ValidationError( |
| 102 | + field="config", |
| 103 | + error="Component class missing config schema", |
| 104 | + suggestion="Implement component_config_schema in the component class", |
| 105 | + ) |
| 106 | + ) |
| 107 | + except Exception as e: |
| 108 | + errors.append( |
| 109 | + ValidationError( |
| 110 | + field="config", |
| 111 | + error=f"Schema validation error: {str(e)}", |
| 112 | + suggestion="Check the component configuration format", |
| 113 | + ) |
| 114 | + ) |
| 115 | + return errors |
| 116 | + |
| 117 | + @staticmethod |
| 118 | + def validate_instantiation(component: Dict[str, Any]) -> Optional[ValidationError]: |
| 119 | + """Validate that the component can be instantiated""" |
| 120 | + try: |
| 121 | + model = ComponentModel(**component) |
| 122 | + # Attempt to load the component |
| 123 | + module_path, class_name = model.provider.rsplit(".", maxsplit=1) |
| 124 | + module = importlib.import_module(module_path) |
| 125 | + component_class = getattr(module, class_name) |
| 126 | + component_class.load_component(model) |
| 127 | + return None |
| 128 | + except Exception as e: |
| 129 | + return ValidationError( |
| 130 | + field="instantiation", |
| 131 | + error=f"Failed to instantiate component: {str(e)}", |
| 132 | + suggestion="Check that the component can be properly instantiated with the given config", |
| 133 | + ) |
| 134 | + |
| 135 | + @classmethod |
| 136 | + def validate(cls, component: Dict[str, Any]) -> ValidationResponse: |
| 137 | + """Validate a component configuration""" |
| 138 | + errors = [] |
| 139 | + warnings = [] |
| 140 | + |
| 141 | + # Check provider |
| 142 | + if provider_error := cls.validate_provider(component.get("provider", "")): |
| 143 | + errors.append(provider_error) |
| 144 | + |
| 145 | + # Check component type |
| 146 | + if type_error := cls.validate_component_type(component): |
| 147 | + errors.append(type_error) |
| 148 | + |
| 149 | + # Validate schema |
| 150 | + schema_errors = cls.validate_config_schema(component) |
| 151 | + errors.extend(schema_errors) |
| 152 | + |
| 153 | + # Only attempt instantiation if no errors so far |
| 154 | + if not errors: |
| 155 | + if inst_error := cls.validate_instantiation(component): |
| 156 | + errors.append(inst_error) |
| 157 | + |
| 158 | + # Check for version warnings |
| 159 | + if "version" not in component: |
| 160 | + warnings.append( |
| 161 | + ValidationError( |
| 162 | + field="version", |
| 163 | + error="Component version not specified", |
| 164 | + suggestion="Consider adding a version to ensure compatibility", |
| 165 | + ) |
| 166 | + ) |
| 167 | + |
| 168 | + return ValidationResponse(is_valid=len(errors) == 0, errors=errors, warnings=warnings) |
| 169 | + |
| 170 | + |
| 171 | +@router.post("/") |
| 172 | +async def validate_component(request: ValidationRequest) -> ValidationResponse: |
| 173 | + """Validate a component configuration""" |
| 174 | + return ValidationService.validate(request.component) |
0 commit comments