diff --git a/CHANGELOG.md b/CHANGELOG.md index 29662967..29ba0d44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,15 @@ # IGNY8 Change Log -**Current Version:** 1.3.2 -**Last Updated:** January 3, 2026 +**Current Version:** 1.4.0 +**Last Updated:** January 5, 2026 --- -Restored + ## Version History | Version | Date | Summary | |---------|------|---------| +| 1.4.0 | Jan 5, 2026 | **Major** - AI Model Architecture Overhaul, IntegrationProvider Model, AIModelConfig with Credit System, SystemAISettings, Django Admin Reorganization | | 1.3.2 | Jan 3, 2026 | **Major** - Publishing Scheduler, Onboarding Wizard, Content Calendar, Design System Consolidation, Site Dashboard redesign | | 1.3.1 | Jan 2, 2026 | **Design System Consolidation** - Updated .rules with comprehensive design system & component rules, ESLint enforcement | | 1.3.0 | Jan 1, 2026 | **Major** - Automation overhaul, AI provider integrations (Anthropic/Bria), Model Registry, Global Progress tracking, CSS globalization | @@ -34,6 +35,174 @@ Restored --- +## v1.4.0 - January 5, 2026 + +### Major Release: AI Architecture Overhaul & Model Configuration System + +This release introduces a comprehensive refactoring of the AI system architecture, centralizing all AI model configurations, provider API keys, and credit-based billing into a unified, database-driven system. Key improvements include the new `IntegrationProvider`, `AIModelConfig`, and `SystemAISettings` models, along with Django Admin reorganization and enhanced frontend settings pages. + +--- + +### πŸ€– AI Model Architecture Overhaul (MAJOR) + +**New Model: IntegrationProvider** (`modules/system/models.py`) +- Centralized storage for ALL external service API keys +- Supports providers: `openai`, `anthropic`, `runware`, `stripe`, `paypal`, `resend` +- Fields: `provider_id` (PK), `display_name`, `provider_type` (ai/payment/email/storage) +- API key management: `api_key`, `api_secret`, `webhook_secret`, `api_endpoint` +- Configuration: `config` (JSONField), `is_active`, `is_sandbox` +- Audit trail: `updated_by`, `created_at`, `updated_at` + +**New Model: AIModelConfig** (`business/billing/models.py`) +- Single Source of Truth for all AI models (text + image) with pricing +- Fields: `model_name` (unique), `model_type` (text/image), `provider`, `display_name` +- Status: `is_default` (one per type), `is_active` +- Text Model Pricing: `cost_per_1k_input`, `cost_per_1k_output`, `tokens_per_credit` +- Image Model Pricing: `credits_per_image`, `quality_tier` (basic/quality/premium) +- Model Limits: `max_tokens`, `context_window`, `capabilities` (JSONField) +- History tracking via `simple_history` + +**New Model: SystemAISettings** (`modules/system/ai_settings.py`) +- System-wide AI defaults (Singleton pattern, pk=1) +- AI Parameters: `temperature` (0.0-2.0), `max_tokens` +- Image Settings: `image_style`, `image_quality`, `max_images_per_article`, `image_size` +- Helper methods: `get_effective_*` for account-specific overrides via `AccountSettings` +- Image Style Choices: photorealistic, illustration, 3d_render, minimal_flat, artistic, cartoon + +**Model Registry Service** (`ai/model_registry.py`) +- Central registry with database-driven model configuration +- Caching layer for performance (5-minute TTL) +- Methods: `get_model()`, `get_rate()`, `calculate_cost()`, `get_default_model()` +- Provider methods: `get_provider()`, `get_api_key()`, `get_api_secret()`, `get_webhook_secret()` +- List and validation: `list_models()`, `validate_model()`, `clear_cache()` + +--- + +### πŸ’° Credit System Integration + +**AIModelConfig Credit Fields:** +- `tokens_per_credit` - Text models: tokens per 1 credit (e.g., 1000 for GPT-4, 10000 for GPT-4o-mini) +- `credits_per_image` - Image models: credits per image (1=basic, 5=quality, 15=premium) +- `quality_tier` - Image quality tier for UI display + +**Credit Cost Configuration:** +- Per `final-model-schemas.md`: Simplified to `operation_type`, `display_name`, `base_credits`, `is_active` +- Removed `tokens_per_credit` from CreditCostConfig (moved to AIModelConfig) + +**New Migrations:** +- `0025_add_aimodel_credit_fields.py` - Add credit fields to AIModelConfig +- `0026_populate_aimodel_credits.py` - Populate default credit values +- `0027_model_schema_update.py` - Schema updates for final model architecture + +--- + +### πŸ”§ Django Admin Reorganization + +**Admin Group Structure:** +- Consolidated admin panels with logical grouping +- AI Configuration: AIModelConfig, IntegrationProvider, SystemAISettings +- Billing: CreditCostConfig, BillingConfiguration, Invoices, Payments, Credit Packages +- Custom logo support via `staticfiles/admin/img/` + +**AIModelConfig Admin:** +- List display: model_name, model_type, provider, is_default, is_active +- Bulk actions: activate/deactivate, set as default +- Fieldsets: Basic Info, Pricing (Text), Pricing (Image), Model Limits, Capabilities +- Import/Export support + +**IntegrationProvider Admin:** +- List display: provider_id, display_name, provider_type, is_active, is_sandbox +- Secure API key display (masked in list view) +- Fieldsets: Provider Info, Authentication, Configuration, Status + +--- + +### 🎨 Frontend Settings Updates + +**Site Settings Page Refactoring** (`pages/Sites/Settings.tsx`) +- Tab restructure: General β†’ AI Settings β†’ Integrations β†’ Publishing β†’ Content Types +- Image settings merged into AI Settings tab (previously separate) +- Quality tier picker with credit display +- Temperature and max_tokens controls +- Image style selection with previews + +**AI Settings Tab Features:** +- Content Generation Settings: append_to_prompt, default_tone, default_length +- AI Parameters: temperature slider (0.0-2.0), max_tokens dropdown +- Image Generation: quality tier selector (Basic/Quality/Premium with credit costs) +- Image style dropdown with 6 style options +- Max images per article control (1-8) + +**Removed Pages:** +- `frontend/src/pages/Settings/AI.tsx` - Merged into Site Settings AI tab + +--- + +### πŸ“Š System Migrations + +**System Module Migrations:** +- `0015_add_integration_provider.py` - Create IntegrationProvider model +- `0016_populate_integration_providers.py` - Seed default providers (openai, runware, anthropic, stripe, paypal, resend) +- `0017_create_ai_settings.py` - Create AISettings model +- `0018_create_ai_settings_table.py` - Create SystemAISettings table +- `0019_model_schema_update.py` - Final schema updates + +**Billing Module Migrations:** +- `0024_update_image_models_v2.py` - Update image model configurations +- `0025_add_aimodel_credit_fields.py` - Add credit fields +- `0026_populate_aimodel_credits.py` - Populate credit values +- `0027_model_schema_update.py` - Schema finalization + +--- + +### πŸ”„ AI Core Updates + +**AI Core Service** (`ai/ai_core.py`) +- Refactored to use ModelRegistry for model configuration +- Dynamic API key retrieval from IntegrationProvider +- Improved error handling and logging +- Cost calculation using AIModelConfig rates + +**AI Tasks** (`ai/tasks.py`) +- Updated to use new model configuration system +- Credit deduction via AIModelConfig settings +- Quality tier support for image generation + +**AI Settings** (`ai/settings.py`) +- Simplified to use SystemAISettings singleton +- Removed hardcoded API keys (now in IntegrationProvider) +- Helper functions for getting effective settings with account overrides + +**Generate Images** (`ai/functions/generate_images.py`) +- Quality tier-based model selection +- Credits deducted based on `credits_per_image` from AIModelConfig +- Style parameter support from SystemAISettings + +--- + +### πŸ“ Documentation Updates + +**New Documentation:** +- `docs/plans/4th-jan-refactor/final-model-schemas.md` - Complete model schema specification +- `docs/plans/4th-jan-refactor/django-plan.md` - Django admin reorganization plan + +**Model Architecture:** +- Total Models: 5 (IntegrationProvider, AIModelConfig, AISettings, AccountSettings, CreditCostConfig) +- Removed: IntegrationSettings merged into AISettings/AccountSettings +- Simplified: CreditCostConfig.tokens_per_credit moved to AIModelConfig + +--- + +### πŸ› Bug Fixes & Improvements + +- Fixed image generation model selection for different quality tiers +- Improved API key security (no longer stored in GlobalIntegrationSettings) +- Fixed admin panel navigation for billing and AI configuration +- Corrected credit calculation for token-based text models +- Fixed singleton pattern enforcement for SystemAISettings + +--- + ## v1.3.2 - January 3, 2026 ### Major Release: Publishing Scheduler, Onboarding Wizard & Content Calendar diff --git a/docs/10-MODULES/BILLING.md b/docs/10-MODULES/BILLING.md index 63ad08b1..2d041517 100644 --- a/docs/10-MODULES/BILLING.md +++ b/docs/10-MODULES/BILLING.md @@ -1,6 +1,6 @@ # Billing Module -**Last Verified:** December 25, 2025 +**Last Verified:** January 5, 2026 **Status:** βœ… Active **Backend Path:** `backend/igny8_core/modules/billing/` + `backend/igny8_core/business/billing/` **Frontend Path:** `frontend/src/pages/Billing/` + `frontend/src/pages/Account/` @@ -11,7 +11,7 @@ | What | File | Key Items | |------|------|-----------| -| Models | `business/billing/models.py` | `CreditTransaction`, `CreditUsageLog`, `CreditCostConfig` | +| Models | `business/billing/models.py` | `CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `AIModelConfig` | | Service | `business/billing/services/credit_service.py` | `CreditService` | | Views | `modules/billing/views.py` | `CreditBalanceViewSet`, `CreditUsageViewSet` | | Frontend | `pages/Account/PlansAndBillingPage.tsx` | Plans, credits, billing history | @@ -23,6 +23,7 @@ The Billing module manages: - Credit balance and transactions +- AI model pricing and credit configuration (v1.4.0) - Usage tracking and limits - Plan enforcement - Payment processing @@ -31,6 +32,37 @@ The Billing module manages: ## Data Models +### AIModelConfig (NEW v1.4.0) + +Single Source of Truth for all AI models with pricing. + +| Field | Type | Purpose | +|-------|------|---------| +| model_name | CharField(100) | Model identifier (gpt-4o-mini, dall-e-3) | +| model_type | CharField(20) | text / image | +| provider | CharField(50) | openai, anthropic, runware | +| display_name | CharField(200) | Human-readable name | +| is_default | BooleanField | One default per type | +| is_active | BooleanField | Enable/disable | +| cost_per_1k_input | DecimalField | USD cost per 1K input tokens (text) | +| cost_per_1k_output | DecimalField | USD cost per 1K output tokens (text) | +| tokens_per_credit | IntegerField | Text: tokens per 1 credit (e.g., 1000) | +| credits_per_image | IntegerField | Image: credits per image (1, 5, 15) | +| quality_tier | CharField(20) | basic / quality / premium | +| max_tokens | IntegerField | Model token limit | +| context_window | IntegerField | Model context size | +| capabilities | JSONField | vision, function_calling, etc. | + +**Credit Examples:** + +| Model | tokens_per_credit | credits_per_image | quality_tier | +|-------|-------------------|-------------------|--------------| +| gpt-4o | 1000 | - | - | +| gpt-4o-mini | 10000 | - | - | +| runware:97@1 | - | 1 | basic | +| dall-e-3 | - | 5 | quality | +| google:4@2 | - | 15 | premium | + ### CreditTransaction (Ledger) | Field | Type | Purpose | @@ -41,7 +73,8 @@ The Billing module manages: | balance_after | Decimal | Balance after transaction | | description | CharField | Transaction description | | metadata | JSON | Additional data | -| reference_id | CharField | External reference | +| payment | FK(Payment) | Payment that triggered this (v1.4.0) | +| reference_id | CharField | DEPRECATED: Use payment FK | | created_at | DateTime | Transaction time | ### CreditUsageLog (Analytics) @@ -60,24 +93,23 @@ The Billing module manages: | metadata | JSON | Additional data | | created_at | DateTime | Usage time | -### CreditCostConfig +### CreditCostConfig (Updated v1.4.0) | Field | Type | Purpose | |-------|------|---------| -| operation_type | CharField | Operation name | -| credits_cost | Decimal | Credits per unit | -| unit | CharField | per_request/per_100_words/per_200_words/per_item/per_image | -| display_name | CharField | UI display name | -| description | TextField | Description | -| is_active | Boolean | Enable/disable | -| previous_cost | Decimal | Previous cost (audit) | -| updated_by | FK | Last updater | +| operation_type | CharField(50) PK | Unique operation ID | +| display_name | CharField(100) | Human-readable name | +| base_credits | IntegerField | Fixed credits per operation | +| is_active | BooleanField | Enable/disable | +| description | TextField | Admin notes | + +**Note:** `tokens_per_credit` moved to AIModelConfig in v1.4.0. --- ## Credit Calculation Methods -### Method 1: Token-Based (Text Models) +### Method 1: Token-Based (Text Models) - Updated v1.4.0 Used for: Clustering, Ideas, Content Generation, Optimization @@ -85,19 +117,30 @@ Used for: Clustering, Ideas, Content Generation, Optimization 1. AI call completes 2. OpenAI returns actual token usage 3. Calculate: `total_tokens = input_tokens + output_tokens` -4. Look up `CreditCostConfig` for operation -5. Apply formula based on unit: - - `per_100_words`: `credits = ceil(words / 100) * cost` - - `per_item`: `credits = items * cost` -6. Apply minimum credits -7. Deduct from balance +4. Look up `AIModelConfig.tokens_per_credit` for the model used +5. Calculate: `credits = ceil(total_tokens / tokens_per_credit)` +6. Deduct from balance -### Method 2: Fixed Cost (Image Models) +**Example:** +- Model: `gpt-4o-mini` (tokens_per_credit = 10000) +- Tokens used: 15000 +- Credits: `ceil(15000 / 10000)` = 2 credits + +### Method 2: Fixed Cost (Image Models) - Updated v1.4.0 Used for: Image Generation **Flow:** -1. Before AI call +1. User selects quality tier (basic/quality/premium) +2. Look up `AIModelConfig.credits_per_image` for selected tier +3. Check balance sufficient: `balance >= num_images * credits_per_image` +4. Deduct credits +5. Make AI call + +**Example:** +- Quality Tier: "quality" (dall-e-3, credits_per_image = 5) +- Images: 3 +- Credits: 3 Γ— 5 = 15 credits 2. Calculate: `credits = num_images * cost_per_image` 3. Check balance sufficient 4. Deduct credits @@ -188,18 +231,31 @@ Displays: --- -## Credit Costs Reference +## Credit Costs Reference (Updated v1.4.0) -Current costs (from `CreditCostConfig`): +**Text Model Credits** (from `AIModelConfig.tokens_per_credit`): -| Operation | Unit | Default Cost | -|-----------|------|--------------| -| Clustering | per_request | 10 credits | -| Idea Generation | per_item | 2 credits | -| Content Generation | per_100_words | 5 credits | -| Image Generation (Basic) | per_image | 3 credits | -| Image Generation (Premium) | per_image | 5 credits | -| Content Optimization | per_200_words | 3 credits | +| Model | tokens_per_credit | Cost/Credit | Notes | +|-------|-------------------|-------------|-------| +| gpt-4o | 1000 | ~$0.015 | High quality, lower throughput | +| gpt-4o-mini | 10000 | ~$0.001 | Fast, cost-effective | +| gpt-4.5-preview | 500 | ~$0.05 | Highest quality | + +**Image Model Credits** (from `AIModelConfig.credits_per_image`): + +| Quality Tier | credits_per_image | Model Example | Notes | +|--------------|-------------------|---------------|-------| +| Basic | 1 | runware:97@1 | Fast generation | +| Quality | 5 | dall-e-3 | Balanced | +| Premium | 15 | google:4@2 | Best quality | + +**Operation Base Costs** (from `CreditCostConfig.base_credits`): + +| Operation | Base Credits | Notes | +|-----------|--------------|-------| +| Clustering | 10 | Per clustering request | +| Idea Generation | 2 | Per idea generated | +| Content Optimization | 5 | Per optimization run | --- @@ -248,7 +304,4 @@ Current costs (from `CreditCostConfig`): | Feature | Status | Description | |---------|--------|-------------| -| AI Model Config database | πŸ”œ Planned | Move model pricing to database | -| Budget alerts | πŸ”œ Planned | Email when approaching limits | -| Usage forecasting | πŸ”œ Planned | Predict credit usage | -| Overage billing | πŸ”œ Planned | Charge for overages instead of blocking | +| ~~AI Model Config database~~ | βœ… v1.4.0 | Model pricing moved to AIModelConfig | diff --git a/docs/90-REFERENCE/AI-FUNCTIONS.md b/docs/90-REFERENCE/AI-FUNCTIONS.md index 45a57c04..4d9a6bd0 100644 --- a/docs/90-REFERENCE/AI-FUNCTIONS.md +++ b/docs/90-REFERENCE/AI-FUNCTIONS.md @@ -1,6 +1,6 @@ # AI Functions Reference -**Last Verified:** December 25, 2025 +**Last Verified:** January 5, 2026 --- @@ -8,13 +8,20 @@ IGNY8's AI engine provides functions for content planning and generation. Located in `backend/igny8_core/ai/`. -**Providers:** -- **OpenAI** - GPT-4 for text, DALL-E 3 for images -- **Runware** - Alternative image generation +**Providers (v1.4.0):** +- **OpenAI** - GPT-4 for text, DALL-E 3 for images (via `IntegrationProvider`) +- **Anthropic** - Claude models for text (via `IntegrationProvider`) +- **Runware** - Alternative image generation (via `IntegrationProvider`) + +**New in v1.4.0:** +- Provider API keys stored in `IntegrationProvider` model +- Model configurations stored in `AIModelConfig` model +- System defaults stored in `SystemAISettings` singleton +- Credit-based pricing per model via `AIModelConfig.tokens_per_credit` / `credits_per_image` --- -## Architecture +## Architecture (Updated v1.4.0) ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” @@ -25,12 +32,20 @@ IGNY8's AI engine provides functions for content planning and generation. Locate β”‚ β”‚ AIEngine │───►│ Function │───►│ Provider β”‚ β”‚ β”‚ β”‚ (router) β”‚ β”‚ (logic) β”‚ β”‚ (API) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β–² β”‚ +β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ModelRegistry │───►│AIModelConfig │───►│Integration β”‚ β”‚ +β”‚ β”‚ (service) β”‚ β”‚ (database) β”‚ β”‚ Provider β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ Functions: β”‚ β”‚ β€’ AutoClusterKeywords β”‚ β”‚ β€’ GenerateContentIdeas β”‚ β”‚ β€’ GenerateContent β”‚ β”‚ β€’ GenerateImages β”‚ +β”‚ β€’ GenerateImagePrompts β”‚ β”‚ β€’ OptimizeContent (pending) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ @@ -38,6 +53,38 @@ IGNY8's AI engine provides functions for content planning and generation. Locate --- +## Model Registry (NEW v1.4.0) + +**Location:** `backend/igny8_core/ai/model_registry.py` + +Central registry for AI model configurations with caching. + +```python +from igny8_core.ai.model_registry import ModelRegistry + +# Get model configuration +model = ModelRegistry.get_model('gpt-4o-mini') + +# Get pricing rate +input_rate = ModelRegistry.get_rate('gpt-4o-mini', 'input') + +# Calculate cost +cost = ModelRegistry.calculate_cost('gpt-4o-mini', input_tokens=1000, output_tokens=500) + +# Get API key for provider +api_key = ModelRegistry.get_api_key('openai') + +# Get default model +default_text = ModelRegistry.get_default_model('text') +default_image = ModelRegistry.get_default_model('image') + +# List available models +text_models = ModelRegistry.list_models(model_type='text') +image_models = ModelRegistry.list_models(model_type='image', provider='runware') +``` + +--- + ## AIEngine **Location:** `backend/igny8_core/ai/engine.py` @@ -48,9 +95,9 @@ Main orchestrator for AI operations. class AIEngine: def __init__(self, account: Account): self.account = account - self.settings = self._load_settings() - self.text_provider = self._init_text_provider() - self.image_provider = self._init_image_provider() + self.settings = self._load_settings() # Uses SystemAISettings + AccountSettings + self.text_provider = self._init_text_provider() # Uses ModelRegistry + self.image_provider = self._init_image_provider() # Uses ModelRegistry def auto_cluster(self, keywords: List[Keyword]) -> List[Cluster]: """Cluster keywords by topic""" @@ -61,8 +108,8 @@ class AIEngine: def generate_content(self, task: Task) -> Content: """Generate full article content""" - def generate_images(self, content: Content, count: int = 1) -> List[ContentImage]: - """Generate images for content""" + def generate_images(self, content: Content, count: int = 1, quality_tier: str = 'quality') -> List[ContentImage]: + """Generate images for content with quality tier selection (v1.4.0)""" ``` --- @@ -103,9 +150,9 @@ class AIEngine: **Prompt Template:** `auto_cluster` -**Model:** GPT-4 +**Model:** Default text model (from `AIModelConfig.is_default`) -**Credit Cost:** 1 idea credit per operation +**Credit Cost:** Based on `AIModelConfig.tokens_per_credit` for model used --- @@ -146,9 +193,9 @@ class AIEngine: **Prompt Template:** `generate_ideas` -**Model:** GPT-4 +**Model:** Default text model (from `AIModelConfig.is_default`) -**Credit Cost:** 1 idea credit per idea generated +**Credit Cost:** Based on `AIModelConfig.tokens_per_credit` for model used --- @@ -174,7 +221,9 @@ class AIEngine: "target_word_count": 2000, "include_headings": True, "include_lists": True, - "include_code_blocks": True + "include_code_blocks": True, + "temperature": 0.7, # From SystemAISettings or AccountSettings override + "max_tokens": 8192 # From SystemAISettings or AccountSettings override } } ``` @@ -193,15 +242,15 @@ class AIEngine: **Prompt Template:** `generate_content` -**Model:** GPT-4 +**Model:** Default text model (from `AIModelConfig.is_default`) -**Credit Cost:** 1 content credit per generation +**Credit Cost:** Based on `AIModelConfig.tokens_per_credit` for model used --- -## Function: GenerateImages +## Function: GenerateImages (Updated v1.4.0) -**Purpose:** Create images for article content +**Purpose:** Create images for article content with quality tier selection **Input:** ```python @@ -213,17 +262,27 @@ class AIEngine: }, "options": { "count": 3, - "style": "photorealistic", # photorealistic, illustration, diagram - "size": "1024x1024" + "quality_tier": "quality", # basic (1 credit), quality (5 credits), premium (15 credits) + "style": "photorealistic", # From SystemAISettings or override + "size": "1024x1024" # From SystemAISettings or override } } ``` +**Quality Tiers (v1.4.0):** + +| Tier | Model Example | credits_per_image | Description | +|------|---------------|-------------------|-------------| +| basic | runware:97@1 | 1 | Fast generation, simple images | +| quality | dall-e-3 | 5 | Balanced quality and speed | +| premium | google:4@2 | 15 | Best quality, slower | + **Process:** -1. Analyze content to identify image opportunities -2. Generate prompts for each image -3. Call image provider API -4. Store images and generate thumbnails +1. Get quality tier model from `AIModelConfig.get_image_models_by_tier()` +2. Analyze content to identify image opportunities +3. Generate prompts for each image (via `GenerateImagePrompts`) +4. Call image provider API (using `IntegrationProvider.get_api_key()`) +5. Store images and generate thumbnails **Output:** ```python @@ -235,7 +294,10 @@ class AIEngine: "alt_text": "Python code example showing...", "caption": "Example of Python list comprehension", "prompt": "A clean code editor showing Python syntax...", - "is_featured": True + "is_featured": True, + "model_used": "dall-e-3", + "quality_tier": "quality", + "credits_used": 5 }, ... ] @@ -244,9 +306,9 @@ class AIEngine: **Prompt Template:** `generate_image_prompts` -**Model:** DALL-E 3 or Runware +**Model:** Selected by quality tier from `AIModelConfig` -**Credit Cost:** 1 image credit per image +**Credit Cost:** `AIModelConfig.credits_per_image` for selected model --- diff --git a/docs/90-REFERENCE/MODELS.md b/docs/90-REFERENCE/MODELS.md index 49a288b1..394e16f8 100644 --- a/docs/90-REFERENCE/MODELS.md +++ b/docs/90-REFERENCE/MODELS.md @@ -1,6 +1,6 @@ # Database Models Reference -**Last Verified:** January 3, 2026 +**Last Verified:** January 5, 2026 --- @@ -8,37 +8,219 @@ | Scope | Models | Base Class | Filter By | |-------|--------|------------|-----------| -| **Global** | `GlobalIntegrationSettings`, `GlobalAIPrompt`, `GlobalAuthorProfile`, `GlobalStrategy`, `GlobalModuleSettings`, `Industry`, `SeedKeyword` | `models.Model` | None (platform-wide) | -| **Account** | `Account`, `User`, `Plan`, `IntegrationSettings`, `ModuleEnableSettings`, `AISettings`, `AIPrompt`, `AuthorProfile`, `CreditBalance` | `AccountBaseModel` | `account` | +| **Global** | `IntegrationProvider`, `AIModelConfig`, `SystemAISettings`, `GlobalAIPrompt`, `GlobalAuthorProfile`, `GlobalStrategy`, `GlobalModuleSettings`, `Industry`, `SeedKeyword` | `models.Model` | None (platform-wide) | +| **Account** | `Account`, `User`, `Plan`, `AccountSettings`, `ModuleEnableSettings`, `AISettings`, `AIPrompt`, `AuthorProfile`, `CreditBalance` | `AccountBaseModel` | `account` | | **Site** | `Site`, `PublishingSettings`, `AutomationConfig`, `SiteIntegration` | `AccountBaseModel` | `account`, `site` | | **Site+Sector** | `Keywords`, `Clusters`, `ContentIdeas`, `Tasks`, `Content`, `Images` | `SiteSectorBaseModel` | `site`, `sector` | --- -## Global Models (`igny8_core/modules/system/global_settings_models.py`) +## System Models (v1.4.0) (`igny8_core/modules/system/`) -**Purpose:** Platform-wide defaults and API keys. Admin-only. NOT account-scoped. +**Purpose:** Centralized AI configuration, provider API keys, and system-wide defaults. -### GlobalIntegrationSettings (Singleton) +### IntegrationProvider (NEW v1.4.0) + +Centralized storage for ALL external service API keys. Admin-only. ```python -class GlobalIntegrationSettings(models.Model): - # OpenAI (used by ALL accounts) - openai_api_key = CharField(max_length=500) - openai_model = CharField(default='gpt-4o-mini') - openai_temperature = FloatField(default=0.7) - openai_max_tokens = IntegerField(default=8192) +class IntegrationProvider(models.Model): + """Per final-model-schemas.md - Centralized API key storage""" + provider_id = CharField(max_length=50, primary_key=True) # openai, runware, stripe, etc. + display_name = CharField(max_length=100) + provider_type = CharField(max_length=20) # ai, payment, email, storage - # DALL-E / Image Generation - dalle_api_key = CharField(max_length=500) - dalle_model = CharField(default='dall-e-3') - dalle_size = CharField(default='1024x1024') + # Authentication + api_key = CharField(max_length=500, blank=True) + api_secret = CharField(max_length=500, blank=True) + webhook_secret = CharField(max_length=500, blank=True) + api_endpoint = URLField(blank=True) - # Runware - runware_api_key = CharField(max_length=500) + # Configuration + config = JSONField(default=dict) + is_active = BooleanField(default=True) + is_sandbox = BooleanField(default=False) + + # Audit + updated_by = ForeignKey(User, null=True) + created_at = DateTimeField(auto_now_add=True) + updated_at = DateTimeField(auto_now=True) ``` -**Critical:** Singleton (pk=1). API keys here are used by ALL accounts. +**Seeded Providers:** +- `openai` - AI (text + DALL-E) +- `runware` - AI (images) +- `anthropic` - AI (future) +- `stripe` - Payment +- `paypal` - Payment +- `resend` - Email + +**Helper Methods:** +- `IntegrationProvider.get_provider(provider_id)` - Get active provider +- `IntegrationProvider.get_api_key(provider_id)` - Get API key for provider +- `IntegrationProvider.get_providers_by_type(type)` - List providers by type + +--- + +### AIModelConfig (NEW v1.4.0) + +Single Source of Truth for all AI models with pricing and credit configuration. + +```python +class AIModelConfig(models.Model): + """Per final-model-schemas.md - Model definitions + pricing""" + model_name = CharField(max_length=100, unique=True) # gpt-4o-mini, dall-e-3, runware:97@1 + model_type = CharField(max_length=20) # text, image + provider = CharField(max_length=50) # Links to IntegrationProvider + display_name = CharField(max_length=200) + + is_default = BooleanField(default=False) # One default per type + is_active = BooleanField(default=True) + + # Text Model Pricing (per 1K tokens) + cost_per_1k_input = DecimalField(max_digits=10, decimal_places=6, null=True) + cost_per_1k_output = DecimalField(max_digits=10, decimal_places=6, null=True) + tokens_per_credit = IntegerField(null=True) # e.g., 1000, 10000 + + # Image Model Pricing + credits_per_image = IntegerField(null=True) # e.g., 1, 5, 15 + quality_tier = CharField(max_length=20, null=True) # basic, quality, premium + + # Model Limits + max_tokens = IntegerField(null=True) + context_window = IntegerField(null=True) + capabilities = JSONField(default=dict) # vision, function_calling, etc. + + created_at = DateTimeField(auto_now_add=True) + updated_at = DateTimeField(auto_now=True) +``` + +**Credit Configuration Examples:** + +| Model | Type | tokens_per_credit | credits_per_image | quality_tier | +|-------|------|-------------------|-------------------|--------------| +| gpt-4o | text | 1000 | - | - | +| gpt-4o-mini | text | 10000 | - | - | +| runware:97@1 | image | - | 1 | basic | +| dall-e-3 | image | - | 5 | quality | +| google:4@2 | image | - | 15 | premium | + +**Helper Methods:** +- `AIModelConfig.get_default_text_model()` - Get default text model +- `AIModelConfig.get_default_image_model()` - Get default image model +- `AIModelConfig.get_image_models_by_tier()` - List image models by quality tier + +--- + +### SystemAISettings (NEW v1.4.0) + +System-wide AI defaults. Singleton (pk=1). + +```python +class SystemAISettings(models.Model): + """Per final-model-schemas.md - Renamed from GlobalIntegrationSettings""" + # AI Parameters + temperature = FloatField(default=0.7) # 0.0-2.0 + max_tokens = IntegerField(default=8192) + + # Image Generation Settings + image_style = CharField(max_length=30, default='photorealistic') + image_quality = CharField(max_length=20, default='standard') # standard, hd + max_images_per_article = IntegerField(default=4) # 1-8 + image_size = CharField(max_length=20, default='1024x1024') + + # Audit + updated_by = ForeignKey(User, null=True) + updated_at = DateTimeField(auto_now=True) +``` + +**Image Style Choices:** +- `photorealistic` - Ultra realistic photography +- `illustration` - Digital illustration +- `3d_render` - Computer generated 3D +- `minimal_flat` - Minimal / Flat Design +- `artistic` - Artistic / Painterly +- `cartoon` - Cartoon / Stylized + +**Image Size Choices:** +- `1024x1024` - Square +- `1792x1024` - Landscape +- `1024x1792` - Portrait + +**Helper Methods:** +- `SystemAISettings.get_instance()` - Get singleton instance +- `SystemAISettings.get_effective_temperature(account)` - Get with account override +- `SystemAISettings.get_effective_image_style(account)` - Get with account override + +--- + +### AccountSettings (Per-Account Overrides) + +Generic key-value store for account-specific settings. + +```python +class AccountSettings(AccountBaseModel): + """Per final-model-schemas.md - Account overrides""" + key = CharField(max_length=100) # Setting key + value = JSONField(default=dict) # Setting value + + created_at = DateTimeField(auto_now_add=True) + updated_at = DateTimeField(auto_now=True) +``` + +**AI-Related Keys** (override SystemAISettings defaults): + +| Key | Type | Example | Notes | +|-----|------|---------|-------| +| `ai.temperature` | float | 0.8 | Override system default | +| `ai.max_tokens` | int | 8192 | Override system default | +| `ai.image_style` | string | "illustration" | Override system default | +| `ai.image_quality` | string | "hd" | Override system default | +| `ai.max_images` | int | 6 | Override system default | +| `ai.image_quality_tier` | string | "premium" | User's preferred tier | + +--- + +### CreditCostConfig (Operation-Level Pricing) + +Fixed credit costs per operation type. + +```python +class CreditCostConfig(models.Model): + """Per final-model-schemas.md - Operation pricing""" + operation_type = CharField(max_length=50, primary_key=True) # Unique operation ID + display_name = CharField(max_length=100) + base_credits = IntegerField(default=1) # Fixed credits per operation + is_active = BooleanField(default=True) + description = TextField(blank=True) +``` + +**Note:** `tokens_per_credit` moved to AIModelConfig as of v1.4.0. + +--- + +## DEPRECATED Models + +### GlobalIntegrationSettings (DEPRECATED in v1.4.0) + +**Replaced by:** `IntegrationProvider` (API keys) + `AIModelConfig` (model configs) + `SystemAISettings` (defaults) + +```python +# DEPRECATED - Do not use +class GlobalIntegrationSettings(models.Model): + # API keys now in IntegrationProvider + openai_api_key = CharField(max_length=500) # β†’ IntegrationProvider.get_api_key('openai') + runware_api_key = CharField(max_length=500) # β†’ IntegrationProvider.get_api_key('runware') + + # Models now in AIModelConfig + openai_model = CharField(default='gpt-4o-mini') # β†’ AIModelConfig.is_default + + # Settings now in SystemAISettings + openai_temperature = FloatField(default=0.7) # β†’ SystemAISettings.temperature + openai_max_tokens = IntegerField(default=8192) # β†’ SystemAISettings.max_tokens +``` + +--- ### GlobalAIPrompt