Chameleon

AI Generator

Using the AI Generator feature

AI Generator

The AI Generator is a built-in feature that allows users to create AI-generated images and videos through a simple web interface.

Overview

Location: /ai-generator (User Center)

Features:

  • ✅ Image generation (OpenAI DALL-E, Replicate Flux, Kling)
  • ✅ Video generation (Seedance, Kling)
  • ✅ Real-time generation status
  • ✅ Generation history with previews
  • ✅ One-click download
  • ✅ Credit-based usage

Accessing AI Generator

  1. Sign in to your account
  2. Navigate to User Center
  3. Click AI Generator in the sidebar
  4. Or visit directly: /ai-generator

Generating Content

Step 1: Select AI Type

Choose between:

  • Video Generation (default)
  • Image Generation

Step 2: Select Provider

For Video:

  • Seedance (recommended) - High quality, fast
  • Kling - Alternative option

For Image:

  • OpenAI - DALL-E 3, DALL-E 2
  • Replicate - Flux Schnell
  • Kling - Kling v1

Step 3: Select Model

Models are auto-populated based on your provider choice.

Video Models:

  • Seedance: doubao-seedance-1-0-pro-250528
  • Kling: kling-v1, kling-v1-6

Image Models:

  • OpenAI: dall-e-3, dall-e-2
  • Replicate: black-forest-labs/flux-schnell
  • Kling: kling-v1

Step 4: Enter Prompt

Describe what you want to generate.

Good prompts:

  • "A futuristic city at sunset with flying cars"
  • "A professional product photo of a smartphone"
  • "An anime-style character dancing in cherry blossoms"

Tips:

  • Be specific and descriptive
  • Include style, lighting, mood
  • Mention camera angles for video
  • Use aspect ratio hints: --ratio 16:9

Step 5: Click Generate

The system will:

  1. Check your credit balance
  2. Create a generation task
  3. Start processing in background
  4. Poll for results automatically

Wait Time:

  • Images: 10-30 seconds
  • Videos: 1-5 minutes

Generation Results

Viewing Results

Once complete, results appear in the Generated Result section:

For Images:

  • Preview thumbnail
  • Full-size image on click
  • Download button

For Videos:

  • Inline video player
  • Play controls
  • Download button

Downloading

Click the Download button to save the file to your device.

File Formats:

  • Images: PNG or JPEG
  • Videos: MP4

Result URLs are temporary and expire after 24 hours. Download important results immediately.

Generation History

View all your past generations in the Generation History section.

Displayed Information:

  • AI type badge (image/video)
  • Provider name
  • Status (completed, failed, processing)
  • Prompt text
  • Credits cost
  • Creation timestamp

Features:

  • Preview completed results
  • Download from history
  • Filter by status
  • Sort by date

Accessing Full History

The history section shows recent generations. For complete history, results are paginated.

Credit Management

Viewing Credits

Your current credit balance is displayed at the top of the page:

Credits Left: 850

Credit Costs

Before generating, you'll see the cost:

Cost: 10 credits

Insufficient Credits

If you don't have enough credits:

  • Generate button is disabled
  • Warning message appears
  • "Recharge" link to pricing page

Advanced Options (Future)

The AI Generator can be extended with advanced options:

Image Generation:

  • Aspect ratio
  • Style presets
  • Number of variants
  • Negative prompts

Video Generation:

  • Duration (5s, 10s, 15s)
  • Resolution (720p, 1080p, 4K)
  • Frame rate
  • Camera movement

For Administrators

Configuring AI Providers

Admins can manage AI provider API keys at /admin/ai-config:

  1. Login as admin

  2. Visit /admin/ai-config

  3. Add provider:

    • Select provider (openai, seedance, etc.)
    • Enter API key
    • Enable provider
    • Save
  4. Keys are stored in database

  5. Auto-cached for 5 minutes

  6. Falls back to environment variables if not configured

Monitoring Usage

Track AI generation usage:

-- Total generations by provider
SELECT provider, COUNT(*) as total, 
       SUM(credits_cost) as total_credits
FROM generations
WHERE status = 'completed'
GROUP BY provider;

-- Recent generations
SELECT gen_id, ai_type, provider, status, created_at
FROM generations
ORDER BY created_at DESC
LIMIT 20;

-- Failed generations (debugging)
SELECT gen_id, provider, model, error_message, created_at
FROM generations
WHERE status = 'failed'
ORDER BY created_at DESC;

Adjusting Credit Costs

Edit src/services/constant.ts:

export const AI_GENERATION_CREDITS = {
  image: { 
    openai: 5,      // DALL-E 3
    replicate: 3,   // Flux Schnell
    kling: 4 
  },
  video: { 
    kling: 10,      // Kling video
    seedance: 10    // Seedance video
  },
};

Technical Details

Architecture

Frontend (React)
  ↓ POST /api/generator/generate
Backend API
  ↓ Creates DB record (pending)
  ↓ Starts background task
  ↓ Returns gen_id
Background Worker
  ↓ Calls AI SDK
  ↓ Polls for results
  ↓ Updates DB (completed)
  ↓ Deducts credits
Frontend
  ↓ Polls /api/generator/query
  ↓ Shows results

Database

Table: generations

Stores all generation tasks and results:

  • gen_id: Unique identifier
  • user_uuid: Who created it
  • ai_type, provider, model: Configuration
  • prompt: User input
  • result_urls: JSON array of result URLs
  • status: Current state
  • credits_cost: Credits consumed
  • created_at, completed_at: Timing
  • error_message: If failed

File Structure

src/
├── app/api/generator/
│   ├── generate/route.ts   - Create generation
│   ├── query/route.ts      - Query status
│   └── history/route.ts    - Get history
├── components/console/ai-generator/
│   ├── AITypeSelector.tsx  - Type selection
│   ├── ModelSelector.tsx   - Provider/model selection
│   ├── PromptInput.tsx     - Prompt input
│   ├── GenerationResult.tsx - Result display
│   └── GenerationHistory.tsx - History list
├── services/
│   ├── generation.ts       - Business logic
│   └── constant.ts         - Credit costs
├── models/
│   └── generation.ts       - Database operations
└── types/
    └── generation.d.ts     - TypeScript types

Customization

Add New Provider

  1. Add SDK in src/aisdk/:

    // src/aisdk/newprovider/
    export const newprovider = createProvider({
      id: "newprovider",
      // ...
    });
    
  2. Update ModelSelector:

    // src/components/console/ai-generator/ModelSelector.tsx
    const MODEL_OPTIONS = {
      video: [
        { provider: "newprovider", models: ["model-1"] },
      ],
    };
    
  3. Update Generation Service:

    // src/services/generation.ts
    case "newprovider":
      videoModel = newprovider.video(model);
      break;
    
  4. Update Credit Costs:

    // src/services/constant.ts
    video: { 
      newprovider: 15  // Set cost
    }
    

Disable Text Generation

Text generation has been removed from the UI. To re-enable:

  1. Update AITypeSelector to include "text"
  2. Update ModelSelector to include text providers
  3. Add text generation logic back to processTextGeneration

Troubleshooting

Generation Stuck in Processing

Possible Causes:

  • AI provider API timeout
  • Network issues
  • Invalid API key

Solution:

  1. Check Vercel logs for errors
  2. Verify API keys in /admin/ai-config
  3. Test API keys with demo endpoints
  4. Check provider status pages

Credits Not Deducted

Check:

  1. Vercel logs for credit deduction messages
  2. Database credits_trans table for new records
  3. Generation status is "completed" not "failed"

Debug logs to look for:

💰 [VIDEO] Deducting credits: { user_uuid: '...', credits_cost: 10 }
✅ [VIDEO] Credits deduction result: ...

Result URLs Not Showing

Check:

  1. result_urls field in database (should be JSON array)
  2. Frontend parsing of result_urls
  3. URL expiration (24 hours for most providers)

Solution:

  • Check logs: "Processed videoUrls:", "Final result_urls to save:"
  • Verify URLs are extracted from AI SDK response correctly

Provider Not Available

If provider is grayed out:

  1. API key not configured
  2. Provider disabled in /admin/ai-config
  3. Environment variable missing

Solution:

  • Add API key in admin AI config
  • Or set environment variable
  • Redeploy if using env vars

Best Practices

For Users

  1. Write clear prompts - Be specific
  2. Monitor credits - Check balance before generating
  3. Download results quickly - URLs expire
  4. Review history - Learn from past generations

For Developers

  1. Handle timeouts - Set reasonable limits
  2. Log errors - Help debugging
  3. Cache results - Avoid re-generating
  4. Queue system - For high traffic (future enhancement)

Next Steps