Architecture
django-ai-validator is designed with modularity and extensibility in mind. It uses several design patterns to ensure flexibility and testability.
Core Components
1. Validators (validators.py)
- Pattern: Template Method
- Role:
BaseAIValidatordefines the validation workflow (prepare -> validate -> handle error). Subclasses likeAISemanticValidatorimplement specific logic.
2. Fields (fields.py)
- Role:
AICleanedFieldis a custom model field that interceptspre_savesignals to clean data. It supports both synchronous and asynchronous modes.
3. Facade (facade.py)
- Pattern: Facade
- Role:
AICleaningFacadeprovides a simplified interface for the rest of the system to interact with LLMs. It handles provider selection, caching, and error handling.
4. LLM Adapters (llm/adapters.py)
- Pattern: Adapter
- Role: Standardizes the interface for different LLM providers (OpenAI, Anthropic, etc.). Each adapter implements
validateandcleanmethods.
5. Factory (llm/factory.py)
- Pattern: Abstract Factory / Registry
- Role:
LLMFactorycreates instances of adapters based on configuration. It allows registration of custom providers.
6. Proxy (llm/proxy.py)
- Pattern: Proxy
- Role:
CachingLLMProxywraps adapters to add caching behavior without modifying the adapter code.
7. Cache Manager (cache.py)
- Pattern: Singleton
- Role:
LLMCacheManagerhandles generating cache keys and interacting with Django's cache framework.
Data Flow
- Input: User submits data (e.g., via Form or Admin).
- Validator/Field: The validator or field intercepts the data.
- Facade: The request is passed to the
AICleaningFacade. - Factory: The facade asks the factory for the configured LLM adapter.
- Proxy: The factory returns a proxy (if caching is enabled) wrapping the adapter.
- Cache Check: The proxy checks if the result is in the cache.
- LLM Call: If not cached, the adapter calls the external LLM API.
- Result: The result is returned, cached, and passed back to the validator/field.
- Action: The validator raises
ValidationErroror the field updates the model instance.