# AI Magicx API Documentation This file contains the complete AI Magicx API documentation for LLM consumption. Website: https://www.aimagicx.com API Base URL: https://www.aimagicx.com/api/v1 --- ## Authentication URL: https://www.aimagicx.com/docs/authentication Description: Secure your API requests with API keys and scopes import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Authentication All AI Magicx API requests require authentication using Bearer tokens. This guide covers API key management, scopes, and security best practices. ## API Key Format AI Magicx API keys follow this format: ``` sk_<64_hexadecimal_characters> ``` Example: `sk_a1b2c3d4e5f6...` (64 hex characters total) Your API key is shown only once when created. Store it securely - we cannot retrieve it later as we only store a SHA-256 hash. ## Making Authenticated Requests Include your API key in the `Authorization` header: ```bash curl -X POST https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{"messages": [{"role": "user", "content": "Hello"}]}' ``` ```python import requests import os response = requests.post( "https://www.aimagicx.com/api/v1/chat/completions", headers={ "Authorization": f"Bearer {os.environ['AI_MAGICX_API_KEY']}", "Content-Type": "application/json" }, json={"messages": [{"role": "user", "content": "Hello"}]} ) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${process.env.AI_MAGICX_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ messages: [{ role: "user", content: "Hello" }] }), } ); ``` ## API Key Scopes Each API key can be limited to specific capabilities using scopes. This allows you to create restricted keys for different applications. | Scope | Description | Endpoints | |-------|-------------|-----------| | `chat` | Chat completions | `POST /chat/completions` | | `image` | Image generation | `POST /images/generations` | | `image_edit` | Image editing | `POST /images/edits` | | `video` | Video generation | `POST /videos/generations` | | `music` | Music generation | `POST /music/generations` | | `tts` | Text-to-speech | `POST /audio/speech` | | `stt` | Speech-to-text | `POST /audio/transcriptions` | | `usage` | View usage stats | `GET /quota` | | `jobs` | Access async jobs | `GET /jobs`, `GET /jobs/{id}` | When creating an API key, you can select specific scopes or grant all scopes. Keys without required scopes will receive a `403 Forbidden` error. ## Creating API Keys 1. Go to **Dashboard → Settings → API Keys** 2. Click **Create New Key** 3. Enter a name to identify the key 4. Select the scopes you need 5. Optionally set an expiration date 6. Click **Create** and copy your key immediately ## Key Expiration API keys can be configured with an expiration date: - **No expiration** - Key works indefinitely until revoked - **Custom date** - Key automatically stops working after the set date Expired keys return a `401 Unauthorized` error with the message "API key has expired". ## Revoking Keys To revoke an API key: 1. Go to **Dashboard → Settings → API Keys** 2. Find the key you want to revoke 3. Click the **Revoke** button 4. Confirm the action Revoking a key is immediate and permanent. Any applications using that key will immediately lose access. ## Error Responses ### Missing or Invalid Key ```json { "error": "Invalid or missing API key" } ``` **Status:** `401 Unauthorized` ### Expired Key ```json { "error": "API key has expired" } ``` **Status:** `401 Unauthorized` ### Missing Scope ```json { "error": "API key does not have required scope: chat" } ``` **Status:** `403 Forbidden` ### Quota Exceeded ```json { "error": "Quota exceeded for chat_tokens" } ``` **Status:** `402 Payment Required` ## Security Best Practices ### Do's - Store API keys in environment variables - Use different keys for development and production - Create keys with minimum required scopes - Set expiration dates for temporary access - Rotate keys periodically - Monitor key usage in the dashboard ### Don'ts - Never commit API keys to version control - Don't share keys in public forums or chat - Don't embed keys in client-side code - Don't use a single key across all applications ## Environment Variables We recommend storing your API key in environment variables: ```bash # .env.local (never commit this file) AI_MAGICX_API_KEY=sk_your_api_key ``` Then access it in your code: ```python import os api_key = os.environ.get("AI_MAGICX_API_KEY") ``` ```javascript const apiKey = process.env.AI_MAGICX_API_KEY; ``` ```go apiKey := os.Getenv("AI_MAGICX_API_KEY") ``` ## OpenAI SDK Compatibility AI Magicx is compatible with the OpenAI SDK. Just change the base URL: ```python from openai import OpenAI client = OpenAI( api_key="sk_your_aimagicx_key", base_url="https://www.aimagicx.com/api/v1" ) ``` ## Client Identification You can identify your application in requests for better analytics: ```bash curl -X POST https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "X-Client-Name: my-app" \ -H "Content-Type: application/json" \ -d '...' ``` Supported headers: - `X-AI Magicx-Client` - Client identifier - `X-Client-Name` - Application name - `User-Agent` - Detected automatically (e.g., `aimagicx-cli/1.0`) --- ## Changelog URL: https://www.aimagicx.com/docs/changelog Description: Latest updates and changes to the AI Magicx API import { Callout } from 'fumadocs-ui/components/callout' # Changelog All notable changes to the AI Magicx API are documented here. Subscribe to our [status page](https://status.aimagicx.com) for real-time updates and incident notifications. --- ## v1.4.0 - January 6, 2026 ### AI App Builder - **Natural Language to Code** - Describe your app in plain English and get production-ready code - **8 Framework Support** - React + Vite, Next.js, Vue, Svelte, Astro, HTML/CSS/JS, Python Flask/FastAPI, Laravel - **Live Preview** - See your app running instantly in a sandboxed environment with hot reload - **Infinite Canvas** - Visual workspace to view and compare multiple design variants side by side - **Design Variants** - Generate 5+ unique design variations in one click (Modern Minimal, Bold Vibrant, Classic Professional, Playful Creative, Dark Elegant, and more) - **Code Editor** - Full-featured editor with syntax highlighting, file tree, and version history - **Device Presets** - Preview on Mobile (375×667), Tablet (768×1024), Laptop (1366×768), Desktop (1920×1080) - **One-Click Deploy** - Deploy directly to Vercel or Netlify with zero configuration - **Export to ZIP** - Download complete source code with no vendor lock-in - **Iteration History** - Full version history with undo/redo and restore capabilities - **Project Templates** - Start from blank or pre-built templates (dashboards, landing pages, etc.) ### Builder API - **Projects Endpoint** - `POST /api/builder/projects` for creating and managing projects - **Generate Endpoint** - `POST /api/builder/generate` for AI code generation with streaming - **Variants Endpoint** - `POST /api/builder/generate-variants` for batch design variant generation - **Deploy Endpoint** - `POST /api/builder/deploy` for Vercel/Netlify deployments - **Export Endpoint** - `POST /api/builder/export` for ZIP downloads ### Billing - App Builder available on Pro and higher plans - Code generation uses chat_tokens quota based on model tier - Variant generation counted separately (limits by plan) --- ## v1.3.0 - January 1, 2026 ### Document Chat - **Multi-Source Import** - Upload files, paste URLs, import YouTube videos, or paste text directly - **Supported File Types** - PDF, DOCX, Markdown, TXT, and CSV files up to 10MB - **URL Content Extraction** - Automatic content extraction from any public web page - **YouTube Transcripts** - Import video transcripts with timestamp support - **Semantic Search** - Vector embeddings for intelligent content retrieval - **Smart Citations** - Every AI response includes numbered citations to source passages - **Multi-Document Chat** - Chat across multiple documents simultaneously - **Collections** - Organize documents into collections for project-based workflows - **Processing Progress** - Real-time progress tracking with stage indicators - **Retry Failed Imports** - Retry failed URL and YouTube imports with one click ### Document API - **Upload Endpoint** - `POST /api/v1/documents/upload` for file uploads - **Import Endpoint** - `POST /api/v1/documents/import` for URLs, YouTube, and text - **Chat Endpoint** - `POST /api/v1/documents/chat` for RAG-powered conversations - **Collections API** - Full CRUD for document collections - **Streaming Responses** - Server-sent events for real-time chat responses ### Billing - Documents feature gated to Pro and higher plans - Embedding costs charged from chat_tokens quota - Chat queries use standard model pricing --- ## v1.2.1 - December 31, 2025 ### Sharing & Collaboration - **Three Visibility Levels** - Share resources as Private (only you), Team (org members), or Public (anyone with link) - **Shareable Resources** - Share conversations, AI agents, and agent runs - **Fork Functionality** - Fork shared resources to your own account for customization - **Secure Share Tokens** - 128-bit entropy tokens for public links - **Team Shared Views** - Browse team-shared conversations and agents in dedicated tabs - **Public Share Pages** - Read-only views for publicly shared resources - **Share API** - Programmatic sharing via `/api/v1/share` and `/api/v1/fork` endpoints --- ## v1.2.0 - December 30, 2025 ### AI Agents - **New Agents API** - Build autonomous AI agents that use tools to complete complex tasks - **7 Built-in Tools** - web_search, web_fetch, generate_text, generate_image, analyze_image, generate_chart, create_document - **Streaming Execution** - Real-time SSE streaming of agent reasoning and tool calls - **Persistent Memory** - Enable memory to remember user preferences across sessions - **Knowledge Base** - Upload documents (PDF, Markdown, TXT, CSV, DOCX) for RAG retrieval - **Sessions** - Maintain conversation context across multiple agent runs - **Agent Templates** - Pre-built agents for research, content, coding, analysis, and support ### Webhooks & Integrations - **Outgoing Webhooks** - 17 event types across 5 categories (generations, agents, billing, team, system) - **Incoming Webhooks** - Trigger agent runs and generations from external services - **Slack Integration** - OAuth-based real-time notifications - **Discord Integration** - Webhook notifications with rich embeds - **Zapier Integration** - Connect to 5,000+ apps - **Make Integration** - Complex multi-step workflows - **n8n Integration** - Self-hosted automation support ### Image Editing - **Inpainting** - Fill masked regions with AI-generated content - **Outpainting** - Extend images beyond original boundaries - **Background Removal** - Remove backgrounds with transparency - **Background Replace** - Replace backgrounds with text prompts - **Object Removal** - Remove objects and fill naturally - **Super Resolution** - 2x and 4x AI upscaling - **Face Enhancement** - Restore and enhance faces - **Colorization** - Colorize black and white images - **Style Transfer** - Apply artistic styles ### Credits & Quotas - **Unified Credit System** - 1 credit = 1,000 tokens across all plans - **Quota Buckets** - Separate quotas for chat, images, video, audio, music, and agents - **Model Tier Multipliers** - Basic (1x), Standard (1.5-2x), Powerful (2-3x) - **Top-up Bundles** - Creator Boost, Media Boost, API Chat Packs, Video Packs, Music Packs - **Low Credit Alerts** - Automatic notifications at 20%, 10%, and 0% remaining ### New Plans - **CLI Pro** - 2,000 credits/month for API-heavy workflows - **CLI Team** - 10,000 credits/month with 3 team members ### API Improvements - **Long-polling** - Use `?poll=true` on job status for efficient polling (up to 30s wait) - **Enhanced Error Responses** - Quota errors now include remaining/needed units and multipliers - **Model Tier Access** - Plan-based access to Basic, Standard, and Powerful model tiers ### Documentation - **Interactive Playgrounds** - Test all endpoints directly in the browser - **Comprehensive SDK Examples** - Python and TypeScript with agents support - **Updated Guides** - Streaming, async jobs, error handling, best practices --- ## v1.1.0 - December 15, 2025 ### New Features - **200+ Chat Models** - Added OpenRouter integration for access to models from OpenAI, Anthropic, Google, Meta, Mistral, and more - **Vision Support** - Send images in chat messages for multimodal analysis - **Kling Video Models** - Added Kling v1.5 Standard and Pro for video generation - **Voice Cloning** - Clone any voice with F5-TTS using reference audio ### Model Updates - Added `anthropic/claude-3.5-sonnet` and `anthropic/claude-3.5-haiku` - Added `google/gemini-2.0-flash-exp` - Added `meta-llama/llama-3.1-405b-instruct` - Added `openai/o1-preview` and `openai/o1-mini` ### API Improvements - **Scoped API Keys** - Create keys with specific scopes (chat, image, video, tts, stt, music, agents, usage) - **Usage Tracking** - Every response includes detailed usage information - **Quota Endpoint** - Check remaining quota via `/quota` endpoint --- ## v1.0.0 - December 2025 ### New Features - **Chat Completions API** - OpenAI-compatible chat endpoint with streaming support - **Image Generation** - Flux and Stable Diffusion models for text-to-image - **Video Generation** - MiniMax and Luma models for text-to-video and image-to-video - **Text-to-Speech** - Multiple voice presets with voice cloning support - **Speech-to-Text** - Whisper-based transcription with speaker diarization - **Music Generation** - Stable Audio for AI music creation - **Embeddings** - Text embedding models for semantic search ### API Improvements - Added `web_search` parameter to chat completions for grounded responses - Introduced async job system for long-running generations - Added rate limiting with clear error messages - Implemented usage tracking with credits system ### Documentation - Launched comprehensive API documentation - Added interactive API playground for testing endpoints - Created OpenAPI 3.1 specification - Published SDK examples for Python, TypeScript, and cURL --- ## v0.9.0 - November 2025 (Beta) ### Beta Release - Initial beta release with core API endpoints - Limited access for early adopters - Basic authentication with API keys ### Known Issues - Video generation occasionally times out for long durations - Some voice cloning samples may require specific audio formats --- ## Roadmap We're working on the following features for future releases: | Feature | Status | Target | |---------|--------|--------| | Real-time voice chat | In Development | Q1 2026 | | Custom model fine-tuning | Planning | Q2 2026 | | Batch processing API | Planning | Q2 2026 | | Agent marketplace | Planning | Q2 2026 | | Multi-agent workflows | Research | Q3 2026 | --- ## API Versioning The AI Magicx API uses URL-based versioning: ``` https://www.aimagicx.com/api/v1/... ``` - **v1** - Current stable version (recommended) - Breaking changes will result in a new version number - Deprecation notices will be sent 90 days before removal ## Deprecation Policy When we deprecate an API feature: 1. We announce it in the changelog and via email 2. The feature continues to work for 90 days 3. After 90 days, the feature may return errors 4. We provide migration guides for all breaking changes --- ## AI Magicx API Documentation URL: https://www.aimagicx.com/docs Description: Build powerful AI-powered applications with AI Magicx's comprehensive API suite. import { Card, Cards } from 'fumadocs-ui/components/card' # Welcome to AI Magicx API AI Magicx provides a unified API for accessing 200+ state-of-the-art AI models for text, images, video, audio, and more. Build powerful applications with our simple, consistent interface. ## Capabilities ### Text & Chat - **200+ LLMs** - GPT-4, Claude, Gemini, Llama, Mistral, and more - **Streaming** - Real-time token streaming for chat applications - **Vision** - Analyze images with multimodal models ### Image & Video - **Image Generation** - Flux, Stable Diffusion 3.5, DALL-E 3 - **Image Editing** - Inpainting, outpainting, background removal, upscaling - **Video Generation** - MiniMax, Luma Dream Machine, Kling ### Audio & Music - **Text-to-Speech** - Natural voices with voice cloning support - **Speech-to-Text** - Whisper with speaker diarization - **Music Generation** - Create original tracks with Stable Audio ### AI Agents - **Autonomous Agents** - Build agents that use tools to complete tasks - **7 Built-in Tools** - Web search, image generation, document creation - **Memory & Knowledge** - Persistent memory and RAG knowledge bases ## Base URL All API requests should be made to: ``` https://www.aimagicx.com/api/v1 ``` ## Quick Example ```python import requests # Chat completion response = requests.post( "https://www.aimagicx.com/api/v1/chat/completions", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "model": "openai/gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}] } ) print(response.json()["choices"][0]["message"]["content"]) ``` ## OpenAI Compatible Use your existing OpenAI SDK code with AI Magicx: ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="anthropic/claude-3.5-sonnet", # Use any model! messages=[{"role": "user", "content": "Hello!"}] ) ``` ## Pricing **1 credit = 1,000 tokens** | Plan | Credits/Month | Best For | |------|---------------|----------| | Free | 100 | Testing & experimentation | | Pro | 200 + media quotas | Individual developers | | Business | 800 + media quotas | Teams & production | | CLI Pro | 2,000 | API-heavy workflows | | CLI Team | 10,000 | Teams with high usage | See [Credits & Quotas](/docs/guides/credits-and-quotas) for full details. ## Resources ## Need Help? - Browse the [API Reference](/docs/api-reference) for detailed endpoint documentation - Check out our [Guides](/docs/guides) for common use cases - Visit your [Dashboard](https://www.aimagicx.com/dashboard) to manage API keys and usage --- ## Quickstart URL: https://www.aimagicx.com/docs/quickstart Description: Get started with the AI Magicx API in 5 minutes import { Step, Steps } from 'fumadocs-ui/components/steps' import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Quickstart Get up and running with the AI Magicx API in just a few minutes. ### Create an Account Sign up for a AI Magicx account at [aimagicx.com](https://www.aimagicx.com). New accounts come with free credits to get started. ### Get Your API Key Navigate to **Dashboard → Settings → API Keys** and create a new API key. Select the scopes you need: - `chat` - Chat completions - `image` - Image generation and editing - `video` - Video generation - `tts` - Text-to-speech - `stt` - Speech-to-text - `music` - Music generation - `agents` - AI agents Keep your API key secret. Never commit it to version control or share it publicly. ### Make Your First Request ```bash curl -X POST https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "messages": [{"role": "user", "content": "Hello!"}], "model": "openai/gpt-4o-mini" }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/chat/completions", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "messages": [{"role": "user", "content": "Hello!"}], "model": "openai/gpt-4o-mini" } ) print(response.json()["choices"][0]["message"]["content"]) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/chat/completions", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ messages: [{ role: "user", content: "Hello!" }], model: "openai/gpt-4o-mini", }), } ); const data = await response.json(); console.log(data.choices[0].message.content); ``` ## Using the OpenAI SDK AI Magicx is compatible with the OpenAI SDK, making migration simple: ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk_your_api_key", baseURL: "https://www.aimagicx.com/api/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ## Quick Examples ### Generate an Image ```python response = requests.post( "https://www.aimagicx.com/api/v1/images/generations", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "prompt": "A serene mountain landscape at sunset", "model": "fal-ai/flux/dev" } ) print(response.json()["data"][0]["url"]) ``` ### Transcribe Audio ```python response = requests.post( "https://www.aimagicx.com/api/v1/audio/transcriptions", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "file": "https://example.com/audio.mp3", "language": "auto" } ) print(response.json()["text"]) ``` ### Run an AI Agent ```python import json # Create an agent agent = requests.post( "https://www.aimagicx.com/api/v1/agents", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "name": "Research Assistant", "system_prompt": "You are a helpful research assistant.", "tools": ["web_search", "web_fetch"] } ).json()["agent"] # Run the agent (streaming) response = requests.post( f"https://www.aimagicx.com/api/v1/agents/{agent['id']}/run", headers={"Authorization": "Bearer sk_your_api_key"}, json={"input": "What are the latest AI developments?"}, stream=True ) for line in response.iter_lines(): if line and line.startswith(b'data: '): event = json.loads(line[6:]) if event["type"] == "done": print(event["output"]) ``` ## What's Next? **1 credit = 1,000 tokens.** Check your usage in the dashboard or via the `/quota` endpoint. ### Learn the Basics - [Authentication](/docs/authentication) - API keys and scopes - [Rate Limits](/docs/rate-limits) - Usage limits by plan - [Credits & Quotas](/docs/guides/credits-and-quotas) - Understanding the credit system ### Explore Capabilities - [Chat Completions](/docs/api-reference/chat-completions) - 200+ LLM models - [Image Generation](/docs/api-reference/image-generation) - Flux, SD, DALL-E - [AI Agents](/docs/api-reference/agents) - Autonomous agents with tools ### Integrate - [Webhooks](/docs/guides/webhooks) - Real-time event notifications - [Integrations](/docs/guides/integrations) - Slack, Discord, Zapier, Make - [OpenAI Compatibility](/docs/sdks/openai-compatibility) - Drop-in replacement --- ## Rate Limits & Quotas URL: https://www.aimagicx.com/docs/rate-limits Description: Understanding rate limits, quotas, and usage tracking in the AI Magicx API import { Callout } from 'fumadocs-ui/components/callout' # Rate Limits & Quotas AI Magicx implements rate limiting and quota systems to ensure fair usage and maintain service quality for all users. ## Rate Limits by Plan Rate limits are applied per API key and vary by subscription plan: | Plan | Requests/Min | Max Burst | |------|--------------|-----------| | Free | 30 | 30 | | Pro Monthly | 60 | 120 | | Business Monthly | 120 | 300 | | CLI Pro | 120 | 300 | | CLI Team | 300 | 600 | ## Endpoint-Specific Limits Different API endpoints have specific rate limits: | Endpoint | Limit | Window | |----------|-------|--------| | Chat Completions | 30 req | per minute | | Image Generation | 10 req | per minute | | Image Editing | 10 req | per minute | | Video Generation | 5 req | per hour | | Text-to-Speech | 20 req | per minute | | Speech-to-Text | 10 req | per minute | | Music Generation | 10 req | per hour | Rate limits are enforced using a sliding window algorithm. Limits reset continuously, not at fixed intervals. ## Rate Limit Headers All API responses include headers to help you track your rate limit status: ```http X-RateLimit-Limit: 60 X-RateLimit-Remaining: 45 X-RateLimit-Reset: 1703123456 ``` | Header | Description | |--------|-------------| | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Remaining requests in the current window | | `X-RateLimit-Reset` | Unix timestamp when the window resets | ## Handling Rate Limits When you exceed the rate limit, you'll receive a `429 Too Many Requests` response: ```json { "error": "Rate limit exceeded", "retryAfter": 30 } ``` The `Retry-After` header indicates how many seconds to wait: ```http HTTP/1.1 429 Too Many Requests Retry-After: 30 ``` ### Exponential Backoff Example ```python import time import requests def make_request_with_retry(url, headers, data, max_retries=5): for attempt in range(max_retries): response = requests.post(url, headers=headers, json=data) if response.status_code == 429: retry_after = int(response.headers.get('Retry-After', 2 ** attempt)) print(f"Rate limited. Retrying in {retry_after}s...") time.sleep(retry_after) continue return response raise Exception("Max retries exceeded") ``` ## Usage Quotas Your account has usage quotas based on your subscription plan. Each resource type has its own quota bucket. **1 credit = 1,000 tokens** (input + output combined) | Resource | Free | Pro | Business | CLI Pro | CLI Team | |----------|------|-----|----------|---------|----------| | **Credits** | 100 | 200 | 800 | 2,000 | 10,000 | | Images | - | 150 | 600 | - | - | | Image edits | - | 75 | 300 | - | - | | Video (min) | - | 15 | 60 | - | - | | STT (min) | - | 60 | 300 | - | - | | TTS (chars) | - | 200K | 800K | - | - | | Music tracks | - | 20 | 80 | - | - | See the [Credits & Quotas guide](/docs/guides/credits-and-quotas) for detailed information. ## Checking Your Quota Use the `/quota` endpoint to check your current usage: ```bash curl https://www.aimagicx.com/api/v1/quota \ -H "Authorization: Bearer sk_your_api_key" ``` **Response:** ```json { "org_id": "org_abc123", "plan": { "code": "pro_monthly", "name": "Pro Monthly", "kind": "recurring", "entitled": true, "period_end": "2025-02-01T00:00:00Z" }, "quotas": { "credits": { "remaining": 170, "limit": 200, "used": 30, "usage_percent": 15 }, "image_generations": { "remaining": 138, "limit": 150, "used": 12, "usage_percent": 8 }, "video_seconds": { "remaining": 810, "limit": 900, "used": 90, "usage_percent": 10 } } } ``` ## Quota Exceeded Errors When you exceed a quota, you'll receive a `402 Payment Required` response: ```json { "error": "Quota exceeded for image_generations" } ``` ## Model Tier Multipliers Different model tiers consume quota at different rates: | Tier | Multiplier | Example Models | |------|------------|----------------| | Basic | 1x | GPT-4o Mini, Claude Haiku | | Standard | 1.5-2x | GPT-4o, Claude Sonnet | | Powerful | 2-3x | GPT-4 Turbo, Claude Opus | For example, using a "Powerful" tier model for image generation might consume 2-3x the quota of a "Basic" tier model. ## Usage Tracking Every API response includes usage information: ```json { "choices": [...], "usage": { "prompt_tokens": 150, "completion_tokens": 200, "total_tokens": 350 }, "model": "openai/gpt-4o-mini", "model_tier": "basic" } ``` For image/video generation: ```json { "data": [...], "usage": { "generations_used": 1, "quota_multiplier": 1.5, "generations_remaining": 919 } } ``` ## Best Practices ### 1. Monitor Your Usage Check the `/quota` endpoint regularly and set up alerts before hitting limits. ### 2. Implement Caching Cache responses when appropriate to reduce API calls: ```python from functools import lru_cache @lru_cache(maxsize=100) def get_cached_response(prompt_hash): return make_api_call(prompt_hash) ``` ### 3. Use Streaming for Chat Streaming doesn't reduce token usage, but provides better UX for long responses. ### 4. Batch Requests When Possible Some endpoints support batch parameters (e.g., `n` for image generation). ### 5. Choose Appropriate Models Use faster, cheaper models for simple tasks: - **Quick tasks:** GPT-4o Mini, Claude Haiku - **Complex tasks:** GPT-4o, Claude Sonnet - **Critical tasks:** GPT-4 Turbo, Claude Opus ## Async Mode for Heavy Operations For resource-intensive operations, use async mode to avoid timeouts: ```bash # Start async job curl -X POST "https://www.aimagicx.com/api/v1/videos/generations?async=true" \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{"prompt": "A sunset over the ocean"}' # Response { "id": "job_abc123", "status": "pending", "created": 1703123456 } # Poll for completion (with long-polling) curl "https://www.aimagicx.com/api/v1/jobs/job_abc123?poll=true" \ -H "Authorization: Bearer sk_your_api_key" ``` The `poll=true` parameter enables long-polling, which waits up to 30 seconds for the job to complete before returning. ## Increasing Your Limits If you need higher rate limits or quotas: 1. **Upgrade your plan** - Higher plans include more generous limits 2. **Contact sales** - For enterprise needs, we offer custom limits 3. **Optimize usage** - Use caching and efficient patterns to maximize your allocation --- ## Agents URL: https://www.aimagicx.com/docs/api-reference/agents Description: Build and run AI agents with tools, memory, and knowledge bases import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # AI Agents Build autonomous AI agents that can use tools, maintain memory, and access knowledge bases to complete complex tasks. AI Agents are available on **Pro** and higher plans. Access them in **Dashboard → Agents** or via the API. ## Overview AI Magicx agents use a ReAct (Reasoning, Action, Observation) loop to autonomously solve tasks: 1. **Receive** a user input 2. **Reason** about what actions to take 3. **Act** by calling tools 4. **Observe** the results 5. **Repeat** until the task is complete ## Agent Features | Feature | Description | |---------|-------------| | **Tools** | Web search, image generation, document creation, and more | | **Memory** | Persistent memory across sessions | | **Knowledge Base** | Upload documents for RAG retrieval | | **Streaming** | Real-time step-by-step execution updates | | **Sessions** | Maintain conversation context | | **Templates** | Pre-built agents for common use cases | ## Endpoints | Method | Endpoint | Description | |--------|----------|-------------| | `GET` | `/agents` | List agents | | `POST` | `/agents` | Create agent | | `GET` | `/agents/{id}` | Get agent details | | `PATCH` | `/agents/{id}` | Update agent | | `DELETE` | `/agents/{id}` | Delete agent | | `POST` | `/agents/{id}/run` | Run agent (streaming) | | `GET` | `/agents/{id}/runs` | List agent runs | | `GET` | `/agents/{id}/runs/{runId}` | Get run details | | `POST` | `/agents/{id}/duplicate` | Duplicate agent | **Required scope:** `agents` ## Create Agent ```http POST /agents ``` ### Request Body ```json { "name": "Research Assistant", "description": "Helps with research tasks using web search", "icon": "search", "system_prompt": "You are a helpful research assistant. Search the web to find accurate, up-to-date information and cite your sources.", "model": "anthropic/claude-3.5-sonnet", "tools": ["web_search", "web_fetch", "create_document"], "temperature": 0.7, "max_tokens": 4000, "max_iterations": 10, "memory_enabled": true } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `name` | string | Yes | - | Agent name (max 100 chars) | | `description` | string | No | - | Agent description (max 500 chars) | | `icon` | string | No | `bot` | Icon identifier | | `system_prompt` | string | Yes | - | System instructions (max 10,000 chars) | | `model` | string | No | `openai/gpt-4o` | LLM model to use | | `tools` | array | No | `[]` | Tool IDs to enable | | `temperature` | number | No | `0.7` | Response creativity (0-2) | | `max_tokens` | number | No | `4000` | Max output tokens (100-8000) | | `max_iterations` | number | No | `10` | Max reasoning loops (1-20) | | `memory_enabled` | boolean | No | `false` | Enable persistent memory | ### Response ```json { "agent": { "id": "agent_abc123", "name": "Research Assistant", "description": "Helps with research tasks using web search", "icon": "search", "system_prompt": "You are a helpful research assistant...", "model": "anthropic/claude-3.5-sonnet", "tools": ["web_search", "web_fetch", "create_document"], "temperature": 0.7, "max_tokens": 4000, "max_iterations": 10, "memory_enabled": true, "is_template": false, "is_public": false, "run_count": 0, "created_at": "2025-01-15T10:00:00Z", "updated_at": "2025-01-15T10:00:00Z" } } ``` ## Available Tools | Tool ID | Credit Cost | Description | |---------|-------------|-------------| | `web_search` | 5 | Search the web using Serper API | | `web_fetch` | 3 | Fetch and parse webpage content | | `generate_text` | 0* | Generate text (uses LLM tokens) | | `generate_image` | 15 | Generate images via Fal AI | | `analyze_image` | 5 | Analyze images using vision models | | `generate_chart` | 2 | Create chart visualizations | | `create_document` | 3 | Create PDF, Markdown, or CSV files | *generate_text uses your token quota, not fixed credits ### Tool Categories | Category | Tools | |----------|-------| | Search | `web_search`, `web_fetch` | | Generation | `generate_text`, `generate_image`, `generate_chart` | | Analysis | `analyze_image` | | Documents | `create_document` | ## Run Agent Execute an agent with streaming response. ```http POST /agents/{id}/run ``` ### Request Body ```json { "input": "Research the latest developments in quantum computing and create a summary document", "attachments": [ { "type": "image", "url": "https://example.com/diagram.png", "name": "architecture.png" } ], "conversation_history": [ {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi! How can I help?"} ], "session_id": "session_xyz789" } ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `input` | string | Yes | User input (max 10,000 chars) | | `attachments` | array | No | Files to include | | `conversation_history` | array | No | Previous messages for context | | `session_id` | string | No | Session ID for continuity | ### Streaming Response The endpoint returns a Server-Sent Events (SSE) stream: ``` data: {"type":"start","run_id":"run_abc123","session_id":"session_xyz789"} data: {"type":"step","run_id":"run_abc123","step":{"step_number":1,"type":"thinking","content":"Analyzing the request..."}} data: {"type":"step","run_id":"run_abc123","step":{"step_number":2,"type":"tool_call","tool":"web_search","tool_input":{"query":"quantum computing 2025 developments"}}} data: {"type":"step","run_id":"run_abc123","step":{"step_number":3,"type":"tool_result","tool":"web_search","tool_output":{"results":[...]}}} data: {"type":"step","run_id":"run_abc123","step":{"step_number":4,"type":"response","content":"Based on my research..."}} data: {"type":"done","run_id":"run_abc123","output":"Based on my research...","credits_used":25,"tokens_used":1500} ``` ### Event Types | Type | Description | |------|-------------| | `start` | Run started, includes run_id and session_id | | `step` | Execution step (thinking, tool_call, tool_result, response) | | `done` | Run completed successfully | | `error` | Run failed with error message | ### Step Types | Step Type | Description | |-----------|-------------| | `thinking` | Agent reasoning about next action | | `tool_call` | Agent calling a tool | | `tool_result` | Tool execution result | | `response` | Final response to user | | `error` | Error during execution | ## Examples ```python import requests import json API_KEY = "sk_your_api_key" BASE_URL = "https://www.aimagicx.com/api/v1" headers = {"Authorization": f"Bearer {API_KEY}"} # Create an agent agent_response = requests.post( f"{BASE_URL}/agents", headers=headers, json={ "name": "Research Assistant", "system_prompt": "You are a helpful research assistant.", "tools": ["web_search", "web_fetch"], "model": "anthropic/claude-3.5-sonnet" } ) agent_id = agent_response.json()["agent"]["id"] # Run the agent with streaming response = requests.post( f"{BASE_URL}/agents/{agent_id}/run", headers=headers, json={"input": "What are the latest AI developments?"}, stream=True ) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): event = json.loads(line[6:]) print(f"[{event['type']}]", event.get('step', {}).get('content', '')) ``` ```python # Create agent with memory enabled agent = requests.post( f"{BASE_URL}/agents", headers=headers, json={ "name": "Personal Assistant", "system_prompt": "You are a personal assistant that remembers user preferences.", "tools": ["web_search"], "memory_enabled": True } ).json()["agent"] # First conversation run1 = run_agent(agent["id"], "My name is Alex and I prefer Python") # Later conversation - agent remembers run2 = run_agent(agent["id"], "What's my name and favorite language?") # Agent will remember: "Your name is Alex and you prefer Python" ``` ```python # Upload knowledge file files = {"file": open("company_docs.pdf", "rb")} upload = requests.post( f"{BASE_URL}/agents/{agent_id}/knowledge", headers=headers, files=files ).json() # Wait for processing file_id = upload["file"]["id"] while True: status = requests.get( f"{BASE_URL}/agents/{agent_id}/knowledge/{file_id}", headers=headers ).json() if status["file"]["status"] == "completed": break time.sleep(2) # Now run - agent will use knowledge base run_agent(agent_id, "What does our company policy say about remote work?") ``` ## TypeScript Example ```typescript async function runAgent(agentId: string, input: string) { const response = await fetch( `https://www.aimagicx.com/api/v1/agents/${agentId}/run`, { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ input }), } ); const reader = response.body?.getReader(); const decoder = new TextDecoder(); while (reader) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); const lines = chunk.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { const event = JSON.parse(line.slice(6)); switch (event.type) { case 'step': console.log(`[${event.step.type}]`, event.step.content || event.step.tool); break; case 'done': console.log('Final output:', event.output); console.log('Credits used:', event.credits_used); break; case 'error': console.error('Error:', event.error); break; } } } } } ``` ## Knowledge Base Upload documents for the agent to reference using RAG (Retrieval Augmented Generation). ### Upload File ```http POST /agents/{id}/knowledge Content-Type: multipart/form-data ``` **Supported formats:** PDF, Markdown, TXT, CSV, DOCX ### List Knowledge Files ```http GET /agents/{id}/knowledge ``` ### Delete Knowledge File ```http DELETE /agents/{id}/knowledge/{fileId} ``` ### File Processing Uploaded files are processed asynchronously: 1. **pending** - File uploaded, waiting for processing 2. **processing** - Extracting text and creating embeddings 3. **completed** - Ready for use 4. **failed** - Processing failed (check error_message) ## Agent Runs ### List Runs ```http GET /agents/{id}/runs GET /agents/{id}/runs?status=completed&limit=10 ``` ### Get Run Details ```http GET /agents/{id}/runs/{runId} ``` Returns the full run including all execution steps: ```json { "run": { "id": "run_abc123", "agent_id": "agent_xyz", "status": "completed", "input": "Research quantum computing", "output": "Based on my research...", "total_steps": 5, "tokens_used": 1500, "credits_used": 25, "duration_ms": 12500, "created_at": "2025-01-15T10:00:00Z", "completed_at": "2025-01-15T10:00:12Z", "steps": [ { "step_number": 1, "step_type": "thinking", "content": "I need to search for recent quantum computing developments" }, { "step_number": 2, "step_type": "tool_call", "tool_name": "web_search", "tool_input": {"query": "quantum computing 2025"} } ] } } ``` ## Quota & Pricing Agent runs use the `agent_runs` quota bucket plus token consumption: ### Agent Run Quota | Plan | Agent Runs/Month | |------|------------------| | Pro | 100 | | Business | 500 | | CLI Pro | Unlimited | | CLI Team | Unlimited | ### Credit Calculation Agent runs are charged based on: 1. **Base cost:** 2 credits per run 2. **Token usage:** Standard chat token pricing 3. **Tool calls:** Per-tool credit costs (see tool table above) **Example calculation:** - Base: 2 credits - 1,500 tokens with Claude Sonnet: ~2 credits - 2x web_search calls: 10 credits - 1x generate_image: 15 credits - **Total:** ~29 credits ### Top-up Pricing Agent runs: $0.25 per run ## Plan Limits | Feature | Pro | Business | CLI Pro | CLI Team | |---------|-----|----------|---------|----------| | Max agents | 5 | 20 | 10 | 50 | | Max tools per agent | 4 | 7 | 7 | 7 | | Max iterations | 10 | 20 | 20 | 20 | | Knowledge files | 5 per agent | 20 per agent | 10 per agent | 50 per agent | | Max file size | 10MB | 25MB | 25MB | 50MB | ## Templates Get started quickly with pre-built agent templates: ```http GET /agents?include_templates=true&template_category=research ``` ### Template Categories | Category | Description | |----------|-------------| | `research` | Research and information gathering | | `content` | Content creation and writing | | `coding` | Code assistance and review | | `analysis` | Data analysis and insights | | `support` | Customer support and FAQ | | `productivity` | Task management and automation | ## Error Handling | Status | Error | Solution | |--------|-------|----------| | 400 | `name is required` | Provide agent name | | 400 | `Invalid tools` | Check tool IDs are valid | | 402 | `Agent limit reached` | Delete agents or upgrade plan | | 402 | `Agent run quota exceeded` | Wait for reset or upgrade | | 403 | `AI Agents are not available` | Upgrade to Pro or higher | | 404 | `Agent not found` | Check agent ID | ## Best Practices ### 1. Write Clear System Prompts Be specific about the agent's role, capabilities, and constraints: ``` You are a research assistant specialized in technology news. When asked to research a topic: 1. Search for recent, authoritative sources 2. Summarize key findings with citations 3. Highlight any conflicting information Always cite your sources with URLs. ``` ### 2. Choose Appropriate Tools Only enable tools the agent actually needs. More tools = more complexity. ### 3. Set Reasonable Limits - Start with lower `max_iterations` (5-10) - Increase if the agent consistently runs out of steps ### 4. Use Sessions for Conversations Maintain context across multiple turns: ```python session_id = str(uuid.uuid4()) # Turn 1 run_agent(agent_id, "Search for AI news", session_id=session_id) # Turn 2 - references previous context run_agent(agent_id, "Tell me more about the first result", session_id=session_id) ``` ### 5. Enable Memory for Personalization For agents that should remember user preferences across sessions, enable `memory_enabled`. --- ## Chat Completions URL: https://www.aimagicx.com/docs/api-reference/chat-completions Description: Generate text completions with state-of-the-art language models import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Chat Completions Generate chat completions using GPT-4, Claude, Gemini, Llama, and 200+ other top language models. This endpoint is fully OpenAI SDK compatible. **OpenAI Compatible:** This endpoint works with the OpenAI SDK - just change the base URL to `https://www.aimagicx.com/api/v1` ## Try it Now Test the Chat Completions API directly in your browser: ## Endpoint ```http POST /chat/completions POST /chat/completions?stream=true ``` **Required scope:** `chat` ## Request Body ```json { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ], "model": "openai/gpt-4o-mini", "temperature": 0.7, "max_tokens": 2048, "stream": false, "web_search": false, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0 } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `messages` | array | Yes | - | Array of message objects with `role` and `content` | | `model` | string | No | `openai/gpt-4o-mini` | Model ID from `/models` endpoint | | `temperature` | number | No | `0.7` | Sampling temperature (0-2). Higher = more creative | | `max_tokens` | number | No | `2048` | Maximum tokens to generate | | `stream` | boolean | No | `false` | Enable Server-Sent Events (SSE) streaming | | `web_search` | boolean | No | `false` | Enable web search for real-time information | | `top_p` | number | No | `1` | Nucleus sampling threshold (0-1) | | `frequency_penalty` | number | No | `0` | Reduce repetition of tokens (-2 to 2) | | `presence_penalty` | number | No | `0` | Encourage topic diversity (-2 to 2) | | `stop` | string\|array | No | - | Stop sequences to end generation | | `user` | string | No | - | Unique user ID for tracking | ### Message Object | Field | Type | Required | Description | |-------|------|----------|-------------| | `role` | string | Yes | One of: `system`, `user`, `assistant`, `tool` | | `content` | string | Yes | The message content | | `images` | array | No | Array of image URLs for vision models (up to 4) | | `name` | string | No | Optional name for the participant | **Vision Support:** When using `images`, ensure you're using a vision-capable model like `openai/gpt-4o`, `anthropic/claude-3.5-sonnet`, or `google/gemini-1.5-pro`. ## Response ```json { "id": "chatcmpl-1234567890", "object": "chat.completion", "created": 1703123456, "model": "openai/gpt-4o-mini", "model_tier": "standard", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I help you today?" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 12, "completion_tokens": 8, "total_tokens": 20, "credits_used": 5, "credits_breakdown": {"base": 5}, "tokens_remaining_estimate": 99980 } } ``` ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "Write a Python function to calculate factorial"} ], "model": "openai/gpt-4o-mini", "max_tokens": 500 }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/chat/completions", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "messages": [ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "Write a Python function to calculate factorial"} ], "model": "openai/gpt-4o-mini", "max_tokens": 500 } ) print(response.json()["choices"][0]["message"]["content"]) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/chat/completions", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ messages: [ { role: "system", content: "You are a helpful coding assistant." }, { role: "user", content: "Write a Python function to calculate factorial" } ], model: "openai/gpt-4o-mini", max_tokens: 500, }), } ); const data = await response.json(); console.log(data.choices[0].message.content); ``` ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "Write a Python function to calculate factorial"} ], max_tokens=500 ) print(response.choices[0].message.content) ``` ## Streaming Enable streaming to receive tokens as they're generated: ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) stream = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Write a short story"}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") ``` ## Vision (Image Analysis) Send images for analysis with vision-capable models: ```python response = client.chat.completions.create( model="openai/gpt-4o", messages=[{ "role": "user", "content": "What's in this image?", "images": ["https://example.com/image.jpg"] }] ) ``` ## Web Search Enable web search for up-to-date information: ```bash curl -X POST https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "messages": [{"role": "user", "content": "What are the latest AI news?"}], "web_search": true }' ``` ## Available Models AI Magicx provides access to 200+ models via OpenRouter. Here are some popular choices: ### OpenAI Models | Model | Context | Best For | Tier | |-------|---------|----------|------| | `openai/gpt-4o` | 128K | Complex reasoning, vision, coding | Standard | | `openai/gpt-4o-mini` | 128K | Fast, cost-effective, general use | Basic | | `openai/gpt-4-turbo` | 128K | Highest quality OpenAI model | Powerful | | `openai/o1-preview` | 128K | Advanced reasoning, math | Powerful | | `openai/o1-mini` | 128K | Fast reasoning tasks | Standard | ### Anthropic Models | Model | Context | Best For | Tier | |-------|---------|----------|------| | `anthropic/claude-3.5-sonnet` | 200K | Best balance of speed & quality | Standard | | `anthropic/claude-3-opus` | 200K | Most capable, complex analysis | Powerful | | `anthropic/claude-3-haiku` | 200K | Ultra-fast, cost-effective | Basic | ### Google Models | Model | Context | Best For | Tier | |-------|---------|----------|------| | `google/gemini-1.5-pro` | 1M | Massive context, multimodal | Standard | | `google/gemini-1.5-flash` | 1M | Fast, large context | Basic | | `google/gemini-2.0-flash` | 1M | Latest Gemini, fast | Basic | ### Open Source Models | Model | Context | Best For | Tier | |-------|---------|----------|------| | `meta-llama/llama-3.1-405b` | 128K | Best open-source, reasoning | Powerful | | `meta-llama/llama-3.1-70b` | 128K | Strong general purpose | Standard | | `meta-llama/llama-3.1-8b` | 128K | Fast, lightweight | Basic | | `mistralai/mixtral-8x22b` | 64K | Coding, analysis | Standard | | `deepseek/deepseek-chat` | 64K | Coding, math | Standard | Use the [Models endpoint](/docs/api-reference/models) to get the complete list of 200+ available models with real-time pricing and availability. ## Model Tiers & Credits Different model tiers consume credits at different rates: | Tier | Multiplier | Description | |------|------------|-------------| | Basic | 1x | Fast, cost-effective models | | Standard | 1.5-2x | Balanced quality and speed | | Powerful | 2-3x | Highest capability models | ## Error Handling | Status | Code | Description | |--------|------|-------------| | 400 | `invalid_request` | Malformed request body | | 401 | `unauthorized` | Invalid or missing API key | | 402 | `quota_exceeded` | Token quota exhausted | | 403 | `forbidden` | API key missing `chat` scope | | 429 | `rate_limited` | Too many requests | | 500 | `server_error` | Internal error (retry safe) | ```json { "error": "Quota exceeded for chat_tokens", "code": "quota_exceeded", "remaining": 0 } ``` --- ## Error Codes URL: https://www.aimagicx.com/docs/api-reference/errors Description: Understanding API error responses and handling import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Error Codes All API errors return a consistent JSON format with an `error` field describing what went wrong. This guide covers all error codes and how to handle them. ## Error Response Format ```json { "error": "Error message describing what went wrong" } ``` Some errors include additional context: ```json { "error": "Image generation limit exceeded", "generations_remaining": 0, "generations_needed": 1, "quota_multiplier": 1.5, "credits_estimated": 15 } ``` ## HTTP Status Codes | Code | Name | Description | |------|------|-------------| | `400` | Bad Request | Invalid request parameters or malformed JSON | | `401` | Unauthorized | Missing or invalid API key | | `402` | Payment Required | Quota exceeded | | `403` | Forbidden | Missing scope, feature unavailable, or model tier restricted | | `404` | Not Found | Resource not found | | `429` | Too Many Requests | Rate limit exceeded | | `500` | Internal Server Error | Server-side error | ## Error Details ### 400 Bad Request Returned when your request is malformed or missing required parameters. **Examples:** ```json {"error": "prompt is required"} {"error": "input text cannot be empty"} {"error": "speed must be between 0.25 and 4.0"} {"error": "Invalid operation"} {"error": "mask is required for inpainting"} ``` **Solutions:** - Check that all required parameters are included - Verify parameter types match the expected format - Ensure JSON is valid - Check parameter value ranges ### 401 Unauthorized Returned when authentication fails. ```json {"error": "Invalid API key"} {"error": "API key not found"} {"error": "API key has been revoked"} ``` **Solutions:** - Verify your API key is correct - Check that the key hasn't been revoked in the dashboard - Ensure the Authorization header format is: `Bearer sk_xxx` ### 402 Payment Required Returned when you've exceeded a quota bucket. ```json { "error": "Image generation limit exceeded", "generations_remaining": 0, "generations_needed": 1, "quota_multiplier": 1.5 } ``` **Other examples:** ```json {"error": "Credits limit exceeded"} {"error": "TTS character limit exceeded", "chars_remaining": 0, "chars_needed": 500} {"error": "STT limit exceeded", "seconds_remaining": 0, "seconds_needed": 60} {"error": "Video seconds limit exceeded"} {"error": "Agent run quota exceeded"} ``` **Solutions:** - Upgrade your plan for higher limits - Wait for your quota to reset (monthly) - Purchase a top-up bundle ### 403 Forbidden Returned when your API key lacks permissions. ```json {"error": "Missing required scope: image"} {"error": "Model tier not allowed"} {"error": "AI Agents are not available on your current plan"} ``` **Solutions:** - Create a new API key with the required scopes - Upgrade to a plan that includes the feature - Use a model from an allowed tier ### 404 Not Found Returned when a resource doesn't exist. ```json {"error": "Agent not found"} {"error": "Job not found"} {"error": "Webhook not found"} ``` **Solutions:** - Verify the resource ID is correct - Check if the resource was deleted - Ensure you have access to the resource ### 429 Too Many Requests Returned when you've exceeded the rate limit. ```json { "error": "Rate limit exceeded. Try again in 30 seconds.", "retry_after": 30 } ``` **Solutions:** - Wait for the specified `Retry-After` period - Implement exponential backoff - Request a higher rate limit for enterprise needs ### 500 Internal Server Error Returned when something goes wrong on our end. ```json {"error": "Internal server error"} {"error": "Generation failed"} ``` **Solutions:** - Retry the request after a short delay - Check our status page for outages - Contact support if the issue persists ## Handling Errors ```python import requests import time class AI MagicXError(Exception): def __init__(self, message, status_code, data=None): self.message = message self.status_code = status_code self.data = data or {} class AuthenticationError(AI MagicXError): pass class QuotaExceededError(AI MagicXError): pass class RateLimitError(AI MagicXError): def __init__(self, message, status_code, retry_after, data=None): super().__init__(message, status_code, data) self.retry_after = retry_after def make_api_request(endpoint, data, max_retries=3): for attempt in range(max_retries): response = requests.post( f"https://www.aimagicx.com/api/v1/{endpoint}", headers={"Authorization": "Bearer sk_your_key"}, json=data ) if response.status_code == 200: return response.json() error_data = response.json() error_msg = error_data.get("error", "Unknown error") if response.status_code == 401: raise AuthenticationError(error_msg, 401, error_data) elif response.status_code == 402: raise QuotaExceededError(error_msg, 402, error_data) elif response.status_code == 429: retry_after = error_data.get("retry_after", 60) if attempt < max_retries - 1: time.sleep(retry_after) continue raise RateLimitError(error_msg, 429, retry_after, error_data) elif response.status_code >= 500: if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff continue raise AI MagicXError(error_msg, response.status_code, error_data) else: raise AI MagicXError(error_msg, response.status_code, error_data) raise AI MagicXError("Max retries exceeded", 500) ``` ```typescript class AI MagicXError extends Error { constructor( message: string, public statusCode: number, public data?: Record ) { super(message); this.name = "AI MagicXError"; } } class AuthenticationError extends AI MagicXError { constructor(message: string, data?: Record) { super(message, 401, data); this.name = "AuthenticationError"; } } class QuotaExceededError extends AI MagicXError { constructor(message: string, data?: Record) { super(message, 402, data); this.name = "QuotaExceededError"; } } class RateLimitError extends AI MagicXError { constructor( message: string, public retryAfter: number, data?: Record ) { super(message, 429, data); this.name = "RateLimitError"; } } async function makeApiRequest( endpoint: string, data: object, maxRetries = 3 ): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { const response = await fetch( `https://www.aimagicx.com/api/v1/${endpoint}`, { method: "POST", headers: { "Authorization": "Bearer sk_your_key", "Content-Type": "application/json", }, body: JSON.stringify(data), } ); if (response.ok) { return response.json(); } const errorData = await response.json(); const errorMsg = errorData.error || "Unknown error"; switch (response.status) { case 401: throw new AuthenticationError(errorMsg, errorData); case 402: throw new QuotaExceededError(errorMsg, errorData); case 429: const retryAfter = errorData.retry_after || 60; if (attempt < maxRetries - 1) { await sleep(retryAfter * 1000); continue; } throw new RateLimitError(errorMsg, retryAfter, errorData); default: if (response.status >= 500 && attempt < maxRetries - 1) { await sleep(Math.pow(2, attempt) * 1000); continue; } throw new AI MagicXError(errorMsg, response.status, errorData); } } throw new AI MagicXError("Max retries exceeded", 500); } const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); ``` ```go package aimagicx import ( "encoding/json" "fmt" "net/http" "time" ) type APIError struct { Message string StatusCode int Data map[string]interface{} } func (e *APIError) Error() string { return fmt.Sprintf("%s (status %d)", e.Message, e.StatusCode) } func MakeAPIRequest(endpoint string, data interface{}) (map[string]interface{}, error) { maxRetries := 3 for attempt := 0; attempt < maxRetries; attempt++ { resp, err := doRequest(endpoint, data) if err != nil { return nil, err } defer resp.Body.Close() var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) if resp.StatusCode == 200 { return result, nil } errorMsg, _ := result["error"].(string) if errorMsg == "" { errorMsg = "Unknown error" } switch resp.StatusCode { case 401, 402, 403, 404: return nil, &APIError{errorMsg, resp.StatusCode, result} case 429: retryAfter := 60 if ra, ok := result["retry_after"].(float64); ok { retryAfter = int(ra) } if attempt < maxRetries-1 { time.Sleep(time.Duration(retryAfter) * time.Second) continue } return nil, &APIError{errorMsg, 429, result} default: if resp.StatusCode >= 500 && attempt < maxRetries-1 { time.Sleep(time.Duration(1< ## Quota Error Details When you receive a 402 error, the response includes helpful information: | Field | Description | |-------|-------------| | `error` | Human-readable error message | | `*_remaining` | How many units remain in this bucket | | `*_needed` | How many units this request requires | | `quota_multiplier` | Model tier multiplier applied | | `credits_estimated` | Estimated credits for the operation | Always check your quota before making requests using the `/quota` endpoint to avoid 402 errors. ## Best Practices 1. **Always handle errors gracefully** - Don't let unhandled errors crash your application 2. **Implement retries with backoff** - For 429 and 5xx errors 3. **Log error responses** - Include the full response for debugging 4. **Monitor quota usage** - Check `/quota` proactively to avoid 402 errors 5. **Use appropriate scopes** - Only request scopes your application needs --- ## Image Editing URL: https://www.aimagicx.com/docs/api-reference/image-editing Description: Edit images with inpainting, outpainting, background removal, and more import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Image Editing Edit existing images with a variety of operations including inpainting, outpainting, background removal, upscaling, and more. ## Try it Now Test the Image Editing API directly in your browser: ## Endpoint ```http POST /images/edits POST /images/edits?async=true ``` **Required scope:** `image` Use `async=true` for long-running operations. This returns a job ID that you can poll for completion. ## Request Body ```json { "image": "https://example.com/image.png", "operation": "inpainting", "mask": "https://example.com/mask.png", "prompt": "A red sports car", "strength": 0.95, "model": "fal-ai/flux-kontext-lora/inpaint" } ``` ### Common Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `image` | string | Yes | - | Image URL or base64 data | | `operation` | string | Yes | - | Operation type (see below) | | `model` | string | No | varies | Model to use for the operation | | `strength` | number | No | `0.95` | Edit strength (0-1) | | `model_inputs` | object | No | - | Additional model-specific parameters | ## Operations ### Inpainting Fill a masked region with new content based on a prompt. ```json { "image": "https://example.com/photo.jpg", "operation": "inpainting", "mask": "https://example.com/mask.png", "prompt": "A fluffy cat sitting on the couch" } ``` | Parameter | Required | Description | |-----------|----------|-------------| | `mask` | Yes | Mask image (white = edit area, black = preserve) | | `prompt` | Yes | What to generate in the masked area | ### Outpainting Extend an image beyond its original boundaries. ```json { "image": "https://example.com/photo.jpg", "operation": "outpainting", "direction": "right", "expand_pixels": 512, "prompt": "Continue the forest landscape" } ``` | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `direction` | Yes | - | `left`, `right`, `top`, `bottom`, or `all` | | `expand_pixels` | No | `256` | Pixels to expand | | `prompt` | No | - | Guidance for new content | ### Background Removal Remove the background from an image, returning a PNG with transparency. ```json { "image": "https://example.com/photo.jpg", "operation": "backgroundRemoval" } ``` No additional parameters required. Returns a PNG with transparent background. ### Background Replace Remove and replace the background with a new one. ```json { "image": "https://example.com/portrait.jpg", "operation": "backgroundReplace", "new_background": "A tropical beach at sunset" } ``` | Parameter | Required | Description | |-----------|----------|-------------| | `new_background` | Yes | Description of new background (prompt) | ### Object Removal Remove an object from the image and fill the area naturally. ```json { "image": "https://example.com/photo.jpg", "operation": "objectRemoval", "mask": "https://example.com/mask.png" } ``` | Parameter | Required | Description | |-----------|----------|-------------| | `mask` | Yes | Mask covering the object to remove | ### Super Resolution (Upscaling) Increase image resolution with AI upscaling. ```json { "image": "https://example.com/small.jpg", "operation": "superResolution", "scale": 4 } ``` | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `scale` | No | `2` | Scale factor: `2` or `4` | ### Face Enhancement Enhance and restore faces in images. ```json { "image": "https://example.com/portrait.jpg", "operation": "faceEnhancement" } ``` Automatically detects and enhances all faces in the image. ### Colorization Colorize black and white images. ```json { "image": "https://example.com/vintage.jpg", "operation": "colorization" } ``` ### Style Transfer Apply artistic styles to images. ```json { "image": "https://example.com/photo.jpg", "operation": "styleTransfer", "prompt": "in the style of Van Gogh's Starry Night" } ``` | Parameter | Required | Description | |-----------|----------|-------------| | `prompt` | Yes | Style description to apply | ## Available Models Each operation has a default model, but you can override with any compatible model: | Operation | Default Model | Notes | |-----------|---------------|-------| | `inpainting` | `fal-ai/flux-kontext-lora/inpaint` | Fill masked regions | | `outpainting` | `fal-ai/creative-outpainting` | Extend image borders | | `backgroundRemoval` | `fal-ai/bria/background/remove` | Remove background | | `superResolution` | `fal-ai/topaz/upscale/image` | AI upscaling | | `faceEnhancement` | `fal-ai/face-enhance` | Restore faces | | `styleTransfer` | `fal-ai/z-image/turbo/image-to-image` | Apply styles | | `colorization` | `fal-ai/z-image/turbo/image-to-image` | Colorize B&W | ### Alternative Models | Model | Use Case | |-------|----------| | `fal-ai/z-image/turbo/inpaint` | Fast inpainting | | `fal-ai/flux/dev/image-to-image` | High quality image-to-image | | `fal-ai/aura-sr` | Fast upscaling | | `fal-ai/clarity-upscaler` | High quality upscaling | ## Response ```json { "created": 1703123456, "data": [ { "url": "https://fal.media/files/edited123.png", "width": 1024, "height": 1024 } ], "model": "fal-ai/flux-kontext-lora/inpaint", "model_tier": "standard", "usage": { "edits_used": 1, "quota_multiplier": 1.25, "edits_remaining": 74 } } ``` ## Quota & Pricing Image edits use the `image_edits` quota bucket: | Plan | Image Edits/Month | |------|-------------------| | Free | - | | Pro | 75 | | Business | 300 | Model tier multipliers apply: | Tier | Multiplier | Example Operations | |------|------------|-------------------| | Fast | 1x | Background removal | | Standard | 1.25x | Inpainting, outpainting | | Premium | 1.5x | High-quality upscaling | ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/images/edits \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "image": "https://example.com/product.jpg", "operation": "backgroundRemoval" }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/images/edits", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "image": "https://example.com/room.jpg", "operation": "inpainting", "mask": "https://example.com/couch-mask.png", "prompt": "A modern blue velvet sofa" } ) print(response.json()["data"][0]["url"]) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/images/edits", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ image: "https://example.com/small-image.jpg", operation: "superResolution", scale: 4, }), } ); const data = await response.json(); console.log(`Upscaled to: ${data.data[0].width}x${data.data[0].height}`); ``` ## Mask Format Masks should match the input image dimensions. Use **white** (#FFFFFF) for areas to edit and **black** (#000000) for areas to preserve. You can provide masks as: - URL to a PNG image - Base64-encoded image data ### Creating Masks Programmatically ```python from PIL import Image, ImageDraw import base64 import io # Create a mask mask = Image.new('L', (1024, 1024), 0) # Black background draw = ImageDraw.Draw(mask) # Draw white region for editing (e.g., a rectangle) draw.rectangle([200, 200, 800, 800], fill=255) # Save or convert to base64 mask.save('mask.png') # Or convert to base64 for API buffer = io.BytesIO() mask.save(buffer, format='PNG') base64_mask = base64.b64encode(buffer.getvalue()).decode() ``` ## Async Mode For long-running operations, use async mode: ```python import requests import time # Start async job response = requests.post( "https://www.aimagicx.com/api/v1/images/edits?async=true", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "image": "https://example.com/photo.jpg", "operation": "superResolution", "scale": 4 } ) job_id = response.json()["id"] # Poll for completion while True: status = requests.get( f"https://www.aimagicx.com/api/v1/jobs/{job_id}?poll=true", headers={"Authorization": "Bearer sk_your_api_key"} ).json() if status["status"] == "completed": print(f"Result: {status['outputData']['images'][0]['url']}") break elif status["status"] == "failed": print(f"Failed: {status.get('errorMessage')}") break time.sleep(3) ``` ## Error Handling | Status | Error | Solution | |--------|-------|----------| | 400 | `image is required` | Provide image URL or base64 | | 400 | `Invalid operation` | Use a valid operation type | | 400 | `mask is required for inpainting` | Provide mask for inpainting/object removal | | 402 | `Image edit limit exceeded` | Upgrade plan or wait for reset | | 403 | `Model tier not allowed` | Upgrade plan for premium operations | ## Supported Image Formats Input: - JPEG / JPG - PNG - WebP Output: - PNG (for transparency operations) - JPEG (for others) --- ## Image Generation URL: https://www.aimagicx.com/docs/api-reference/image-generation Description: Generate images from text prompts using Flux, Stable Diffusion, DALL-E, and more import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Image Generation Generate stunning images from text descriptions using state-of-the-art models like Flux Pro, Stable Diffusion 3.5, DALL-E 3, and more. For long-running generations or multiple images, use **async mode** with `?async=true` to avoid timeouts. ## Try it Now Test the Image Generation API directly in your browser: ## Endpoint ```http POST /images/generations POST /images/generations?async=true ``` **Required scope:** `image` ## Request Body ```json { "prompt": "A serene mountain landscape at sunset with vibrant colors", "model": "fal-ai/flux/dev", "size": "1024x1024", "n": 1, "style": "vivid", "upscale": null, "negative_prompt": "blurry, low quality, distorted", "seed": 42 } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `prompt` | string | Yes | - | Text description of the desired image | | `model` | string | No | `fal-ai/flux/dev` | Model ID (see Available Models) | | `size` | string | No | `1024x1024` | Image dimensions | | `n` | number | No | `1` | Number of images to generate (1-10) | | `style` | string | No | `vivid` | Image style: `vivid` or `natural` | | `upscale` | string | No | - | Post-processing upscale: `2x` or `4x` | | `negative_prompt` | string | No | - | Elements to exclude from the image | | `seed` | number | No | random | Random seed for reproducibility | ### Available Sizes | Size | Aspect | Use Case | |------|--------|----------| | `512x512` | 1:1 | Thumbnails, avatars | | `1024x1024` | 1:1 | Standard social media | | `1792x1024` | 16:9 | Landscape, banners | | `1024x1792` | 9:16 | Portrait, stories | | `1536x1024` | 3:2 | Photography style | | `1024x1536` | 2:3 | Vertical photography | ## Response ```json { "created": 1703123456, "data": [ { "url": "https://fal.media/files/abc123.png", "revised_prompt": "A serene mountain landscape...", "width": 1024, "height": 1024 } ], "model": "fal-ai/flux/dev", "model_tier": "standard", "usage": { "credits_used": 15, "credits_breakdown": {"base": 15}, "generations_used": 1, "generations_remaining": 99 } } ``` ## Async Mode For multiple images or high-resolution outputs, use async mode: ```json // Request with ?async=true { "id": "job_abc123", "status": "pending", "created": 1703123456, "model": "fal-ai/flux/dev", "estimated_credits": 15 } ``` Poll the job status with `GET /jobs/{job_id}?poll=true`. ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/images/generations \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A cyberpunk cityscape with neon lights and flying cars", "size": "1024x1024", "n": 2 }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/images/generations", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "prompt": "A cyberpunk cityscape with neon lights and flying cars", "size": "1024x1024", "n": 2 } ) for image in response.json()["data"]: print(image["url"]) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/images/generations", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ prompt: "A cyberpunk cityscape with neon lights and flying cars", size: "1024x1024", n: 2, }), } ); const data = await response.json(); data.data.forEach((image: { url: string }) => console.log(image.url)); ``` ## Available Models ### Flux Models (Recommended) | Model | Speed | Quality | Best For | |-------|-------|---------|----------| | `fal-ai/flux/dev` | ~10s | Excellent | Production images (default) | | `fal-ai/flux-2` | ~8s | Excellent | Latest Flux generation | | `fal-ai/flux-2-pro` | ~12s | Excellent | Professional quality | | `fal-ai/flux-pro/v1.1-ultra` | ~15s | Excellent | Highest quality Flux | | `fal-ai/flux-general` | ~10s | Excellent | With ControlNets and LoRAs | ### Stable Diffusion & Other Models | Model | Speed | Quality | Best For | |-------|-------|---------|----------| | `fal-ai/stable-diffusion-v35-large` | ~12s | Excellent | High quality SD | | `fal-ai/hidream-i1-fast` | ~5s | Good | Fast generation | | `fal-ai/hidream-i1-dev` | ~8s | Excellent | Balanced quality | | `fal-ai/imagen4/preview/fast` | ~6s | Excellent | Google Imagen 4 | ### Specialty Models | Model | Speed | Quality | Best For | |-------|-------|---------|----------| | `fal-ai/recraft/v3/text-to-image` | ~10s | Excellent | Graphic design, logos | | `fal-ai/ideogram/v2` | ~12s | Excellent | Text in images | | `fal-ai/gpt-image-1.5` | ~8s | Good | GPT-style generation | | `bria/text-to-image/3.2` | ~8s | Good | Commercial-safe images | ## Tips for Better Results **Writing effective prompts:** - Be specific and descriptive - Include style references (e.g., "oil painting", "photorealistic") - Mention lighting and mood - Use negative prompts to exclude unwanted elements ### Example Prompts | Style | Prompt | |-------|--------| | Photorealistic | "Professional photo of a golden retriever in a sunny park, shallow depth of field, Canon EOS R5" | | Digital Art | "Fantasy castle on a floating island, digital art, vibrant colors, by Greg Rutkowski" | | Minimalist | "Simple geometric logo design, minimal, clean lines, white background" | ## Upscaling Add `"upscale": "2x"` or `"upscale": "4x"` to increase resolution: ```json { "prompt": "A detailed fantasy map", "size": "1024x1024", "upscale": "4x" } ``` This will generate at 1024x1024 and upscale to 4096x4096. --- ## API Reference URL: https://www.aimagicx.com/docs/api-reference Description: Complete reference for all AI Magicx API endpoints import { Card, Cards } from 'fumadocs-ui/components/card' # API Reference Explore the complete AI Magicx API. All endpoints use the base URL: ``` https://www.aimagicx.com/api/v1 ``` ## Endpoints ## Common Patterns ### Request Format All requests should: - Use `Content-Type: application/json` - Include `Authorization: Bearer sk_your_api_key` header - Send JSON-encoded request bodies for POST requests ### Response Format All responses return JSON with consistent structure: ```json { "created": 1703123456, "data": { ... }, "model": "model-id", "model_tier": "standard", "usage": { "credits_used": 10, "credits_remaining": 990 } } ``` ### Async Mode Long-running operations support async mode with `?async=true`: ```bash # Start async job POST /images/generations?async=true # Response { "id": "job_abc123", "status": "pending" } # Poll for completion GET /jobs/job_abc123?poll=true ``` ### Error Format All errors follow a consistent format: ```json { "error": "Error message describing what went wrong" } ``` See [Error Codes](/docs/api-reference/errors) for a complete list. --- ## Jobs URL: https://www.aimagicx.com/docs/api-reference/jobs Description: Track and manage async generation jobs import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Jobs Track and manage async generation jobs. Use jobs for long-running operations like video and music generation. ## Overview When you use `?async=true` on any generation endpoint, the API returns a job ID instead of waiting for completion. You can then poll the Jobs API to check status and retrieve results. ## List Jobs Get a list of your generation jobs. ```http GET /jobs GET /jobs?tool=image&pending=true&limit=10 ``` **Required scope:** `usage` ### Query Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `tool` | string | - | Filter by tool type | | `pending` | boolean | `false` | Only return pending/processing jobs | | `limit` | number | `20` | Maximum results (1-100) | ### Tool Types - `image` - Image generation - `image_edit` - Image editing - `video` - Video generation - `music` - Music generation - `tts` - Text-to-speech - `stt` - Speech-to-text ### Response ```json { "jobs": [ { "id": "job_abc123", "orgId": "org_xyz", "userId": "api", "tool": "image", "status": "completed", "progress": 100, "inputParams": {"prompt": "A sunset over mountains"}, "outputData": { "images": [ {"url": "https://fal.media/files/img123.png", "width": 1024, "height": 1024} ] }, "estimatedCredits": 15, "actualCredits": 15, "createdAt": "2025-01-01T00:00:00Z", "completedAt": "2025-01-01T00:00:05Z", "model": "fal-ai/flux/dev", "modelTier": "standard" } ] } ``` ## Get Job Status Get the status of a specific job. ```http GET /jobs/{jobId} GET /jobs/{jobId}?poll=true ``` **Required scope:** `usage` ### Query Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `poll` | boolean | `false` | Long-poll for up to 30s until completion | Use `poll=true` for efficient polling. The request will wait up to 30 seconds for the job to complete before returning, reducing the number of API calls needed. ### Job Statuses | Status | Description | |--------|-------------| | `pending` | Job is queued | | `processing` | Job is being processed | | `completed` | Job finished successfully | | `failed` | Job failed with an error | | `cancelled` | Job was cancelled | ### Response ```json { "id": "job_abc123", "orgId": "org_xyz", "userId": "api", "tool": "video", "status": "processing", "progress": 45, "inputParams": { "prompt": "A timelapse of clouds", "duration_seconds": 5 }, "outputData": null, "estimatedCredits": 500, "actualCredits": null, "errorMessage": null, "createdAt": "2025-01-01T00:00:00Z", "startedAt": "2025-01-01T00:00:01Z", "completedAt": null, "model": "fal-ai/minimax/video-01", "modelTier": "standard" } ``` ### Completed Job Response ```json { "id": "job_abc123", "status": "completed", "progress": 100, "outputData": { "video": { "url": "https://fal.media/files/video123.mp4", "duration": 5.0 } }, "actualCredits": 500, "completedAt": "2025-01-01T00:01:30Z" } ``` ### Failed Job Response ```json { "id": "job_abc123", "status": "failed", "progress": 0, "errorMessage": "Content policy violation detected", "completedAt": "2025-01-01T00:00:10Z" } ``` ## Cancel Job Cancel a pending or processing job. ```http DELETE /jobs/{jobId} ``` **Required scope:** `usage` ### Response ```json { "success": true } ``` Only jobs with status `pending` or `processing` can be cancelled. Completed or failed jobs cannot be cancelled. Cancelled jobs do not consume quota. ## Examples ```python import requests import time API_KEY = "sk_your_api_key" BASE_URL = "https://www.aimagicx.com/api/v1" headers = {"Authorization": f"Bearer {API_KEY}"} # Create an async job response = requests.post( f"{BASE_URL}/videos/generations?async=true", headers=headers, json={ "prompt": "A serene lake at sunrise", "duration_seconds": 5 } ) job_id = response.json()["id"] print(f"Job created: {job_id}") # Poll for completion with long-polling while True: status = requests.get( f"{BASE_URL}/jobs/{job_id}?poll=true", headers=headers ).json() print(f"Status: {status['status']}, Progress: {status.get('progress', 0)}%") if status["status"] == "completed": print(f"Video URL: {status['outputData']['video']['url']}") break elif status["status"] == "failed": print(f"Error: {status.get('errorMessage')}") break # With poll=true, we don't need to sleep as long time.sleep(1) ``` ```bash # List all pending jobs curl "https://www.aimagicx.com/api/v1/jobs?pending=true" \ -H "Authorization: Bearer sk_your_api_key" # List recent video jobs curl "https://www.aimagicx.com/api/v1/jobs?tool=video&limit=5" \ -H "Authorization: Bearer sk_your_api_key" ``` ```python import requests response = requests.delete( "https://www.aimagicx.com/api/v1/jobs/job_abc123", headers={"Authorization": "Bearer sk_your_api_key"} ) if response.json().get("success"): print("Job cancelled successfully") else: print("Failed to cancel job") ``` ## Polling Best Practices **Recommended polling strategy:** - Always use `poll=true` for efficient long-polling - Implement exponential backoff as a fallback - Set reasonable timeouts (5-10 minutes for video/music) ### Recommended Intervals | Job Type | Initial Delay | Max Delay | |----------|---------------|-----------| | Image | 2s | 10s | | Image Edit | 3s | 15s | | Video | 5s | 30s | | Music | 5s | 30s | | TTS | 2s | 10s | | STT | 3s | 15s | ### Exponential Backoff Example ```python import time def poll_job(job_id, max_attempts=60): base_delay = 2 max_delay = 30 for attempt in range(max_attempts): # Try long-polling first status = get_job_status(job_id, poll=True) if status["status"] in ["completed", "failed", "cancelled"]: return status # Calculate delay with exponential backoff delay = min(base_delay * (1.5 ** attempt), max_delay) time.sleep(delay) raise TimeoutError("Job polling timed out") def get_job_status(job_id, poll=False): import requests url = f"https://www.aimagicx.com/api/v1/jobs/{job_id}" if poll: url += "?poll=true" return requests.get( url, headers={"Authorization": "Bearer sk_your_api_key"} ).json() ``` ## Output Data Formats ### Image Generation ```json { "outputData": { "images": [ {"url": "https://...", "width": 1024, "height": 1024} ] } } ``` ### Video Generation ```json { "outputData": { "video": { "url": "https://...", "duration": 5.0 } } } ``` ### Music Generation ```json { "outputData": { "audio": { "url": "https://...", "duration_seconds": 30 } } } ``` ### Text-to-Speech ```json { "outputData": { "audio_url": "https://...", "duration_seconds": 3.5 } } ``` ### Speech-to-Text ```json { "outputData": { "text": "Transcribed text...", "segments": [...], "duration": 60.0 } } ``` ## Error Handling | Status | Error | Description | |--------|-------|-------------| | 404 | `Job not found` | Invalid job ID or job expired | | 400 | `Cannot cancel completed job` | Job already finished | | 500 | `Job processing error` | Internal error during generation | --- ## Models URL: https://www.aimagicx.com/docs/api-reference/models Description: List and understand available AI models import { Callout } from 'fumadocs-ui/components/callout' # Models Retrieve a list of available AI models and understand their capabilities, tiers, and pricing. ## Endpoint ```http GET /models ``` **Required scope:** `chat` ## Response ```json { "object": "list", "data": [ { "id": "openai/gpt-4o-mini", "object": "model", "created": 0, "owned_by": "openai" }, { "id": "anthropic/claude-3.5-sonnet", "object": "model", "created": 0, "owned_by": "anthropic" }, { "id": "google/gemini-1.5-flash", "object": "model", "created": 0, "owned_by": "google" } ] } ``` ## Example ```bash curl https://www.aimagicx.com/api/v1/models \ -H "Authorization: Bearer sk_your_api_key" ``` ## Chat Models AI Magicx provides access to 200+ chat models from leading providers via OpenRouter. ### OpenAI | Model ID | Context | Tier | Best For | |----------|---------|------|----------| | `openai/gpt-4o` | 128K | Standard | Complex reasoning, vision | | `openai/gpt-4o-mini` | 128K | Basic | Fast, cost-effective | | `openai/gpt-4-turbo` | 128K | Powerful | High-quality responses | | `openai/o1-preview` | 128K | Powerful | Advanced reasoning | | `openai/o1-mini` | 128K | Standard | Efficient reasoning | ### Anthropic | Model ID | Context | Tier | Best For | |----------|---------|------|----------| | `anthropic/claude-3.5-sonnet` | 200K | Standard | Balanced quality/speed | | `anthropic/claude-3-opus` | 200K | Powerful | Highest quality | | `anthropic/claude-3-haiku` | 200K | Basic | Fast responses | | `anthropic/claude-3.5-haiku` | 200K | Basic | Cost-effective | ### Google | Model ID | Context | Tier | Best For | |----------|---------|------|----------| | `google/gemini-1.5-pro` | 1M | Standard | Long context | | `google/gemini-1.5-flash` | 1M | Basic | Fast, multimodal | | `google/gemini-2.0-flash-exp` | 1M | Basic | Latest features | ### Meta (Llama) | Model ID | Context | Tier | Best For | |----------|---------|------|----------| | `meta-llama/llama-3.1-405b-instruct` | 128K | Powerful | Largest open model | | `meta-llama/llama-3.1-70b-instruct` | 128K | Standard | Balanced | | `meta-llama/llama-3.1-8b-instruct` | 128K | Basic | Fast, lightweight | ### Other Providers | Model ID | Provider | Context | Tier | |----------|----------|---------|------| | `mistralai/mistral-large` | Mistral | 128K | Standard | | `mistralai/mistral-small` | Mistral | 128K | Basic | | `deepseek/deepseek-chat` | DeepSeek | 64K | Basic | | `qwen/qwen-2.5-72b-instruct` | Qwen | 128K | Standard | ## Image Models | Model ID | Speed | Quality | Notes | |----------|-------|---------|-------| | `fal-ai/flux/dev` | Medium | Excellent | Production quality (default) | | `fal-ai/flux-2` | Fast | Excellent | Latest Flux generation | | `fal-ai/flux-2-pro` | Medium | Excellent | Professional quality | | `fal-ai/flux-pro/v1.1-ultra` | Slow | Best | Highest quality | | `fal-ai/stable-diffusion-v35-large` | Medium | Excellent | Detailed artwork | | `fal-ai/ideogram/v2` | Medium | Excellent | Text in images | ## Video Models | Model ID | Max Duration | Notes | |----------|--------------|-------| | `fal-ai/minimax/video-01` | 6s | High quality, realistic (default) | | `fal-ai/veo3` | 10s | Google Veo 3 | | `fal-ai/kling-video/v2.5-turbo/pro/text-to-video` | 10s | Kling v2.5 | | `fal-ai/minimax/hailuo-02/standard/text-to-video` | 6s | Latest MiniMax | ## Audio Models ### Text-to-Speech | Model ID | Tier | Notes | |----------|------|-------| | `fal-ai/f5-tts` | Standard | Voice cloning support (default) | | `fal-ai/maya` | Standard | High-quality synthesis | | `fal-ai/chatterbox/text-to-speech/turbo` | Fast | Fast generation | | `fal-ai/minimax/speech-2.6-hd` | Premium | HD quality | ### Speech-to-Text | Model ID | Tier | Notes | |----------|------|-------| | `fal-ai/whisper` | Fast | 90+ languages (default) | | `fal-ai/wizper` | Standard | Enhanced accuracy | | `fal-ai/elevenlabs/speech-to-text` | Premium | ElevenLabs quality | ## Music Models | Model ID | Max Duration | Notes | |----------|--------------|-------| | `fal-ai/stable-audio` | 47s | High quality music (default) | | `fal-ai/minimax-music/v2` | 60s | MiniMax Music v2 | | `fal-ai/stable-audio-25/text-to-audio` | 60s | Stable Audio 2.5 | ## Model Tiers Models are categorized into tiers that affect credit costs: | Tier | Credit Multiplier | Examples | |------|-------------------|----------| | Basic | 1x | GPT-4o Mini, Claude Haiku, Llama 8B | | Standard | 1.5-2x | GPT-4o, Claude Sonnet, Llama 70B | | Powerful | 2-3x | GPT-4 Turbo, Claude Opus, Llama 405B | The tier affects credits charged for each request. Check the response `model_tier` field to see which tier was used. ## Model Availability by Plan Some models may be restricted based on your plan: | Plan | Available Tiers | |------|-----------------| | Free | Basic only | | Pro | Basic, Standard | | Business | All tiers | | CLI Pro | All tiers | | CLI Team | All tiers | ## Choosing the Right Model | Use Case | Recommended Model | Why | |----------|-------------------|-----| | Simple Q&A | `openai/gpt-4o-mini` | Fast, cheap | | Complex reasoning | `anthropic/claude-3.5-sonnet` | Good balance | | Long documents | `google/gemini-1.5-pro` | 1M context | | Critical tasks | `anthropic/claude-3-opus` | Highest quality | | Open source | `meta-llama/llama-3.1-70b-instruct` | Self-hostable | | Budget | `mistralai/mistral-small` | Very affordable | ## Rate Limits by Model Different models may have different rate limits. See [Rate Limits](/docs/rate-limits) for details. --- ## Music Generation URL: https://www.aimagicx.com/docs/api-reference/music-generation Description: Generate original music tracks from text prompts import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Music Generation Generate original music tracks from text descriptions using Stable Audio and other music models. Music generation can take 30-60 seconds. We recommend using **async mode** for production applications. ## Try it Now Test the Music Generation API directly in your browser: ## Endpoint ```http POST /music/generations POST /music/generations?async=true ``` **Required scope:** `music` ## Request Body ```json { "prompt": "Upbeat electronic dance music with pulsing synths, 128 BPM", "model": "fal-ai/stable-audio", "duration_seconds": 30, "mode": "text_to_music", "output_format": "mp3", "negative_prompt": null } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `prompt` | string | Yes | - | Description of the music to generate | | `model` | string | No | `fal-ai/stable-audio` | Music model to use | | `duration_seconds` | number | No | `30` | Duration (max 47 seconds) | | `mode` | string | No | `text_to_music` | Generation mode | | `source_audio` | string | No | - | Audio URL for audio-to-audio mode | | `output_format` | string | No | `mp3` | `mp3` or `wav` | | `negative_prompt` | string | No | - | What to avoid in the generation | | `model_inputs` | object | No | - | Additional model-specific parameters | ### Generation Modes | Mode | Description | |------|-------------| | `text_to_music` | Generate from text prompt only | | `audio_to_audio` | Transform existing audio based on prompt | ### Available Models | Model ID | Max Duration | Notes | |----------|--------------|-------| | `fal-ai/stable-audio` | 47s | High quality, diverse styles (default) | | `fal-ai/stable-audio-25/text-to-audio` | 60s | Stable Audio 2.5 | | `fal-ai/minimax-music/v2` | 60s | MiniMax Music v2 | | `fal-ai/minimax-music/v1.5` | 60s | MiniMax Music v1.5 | | `beatoven/music-generation` | 60s | Beatoven AI | | `sonauto/v2/text-to-music` | 60s | Sonauto V2 | ## Response ```json { "created": 1703123456, "data": { "audio_url": "https://fal.media/files/music123.mp3", "duration_seconds": 30 }, "model": "fal-ai/stable-audio", "model_tier": "standard", "usage": { "tracks_used": 1, "quota_multiplier": 1.25, "tracks_remaining": 19 } } ``` ## Quota & Pricing Music generation uses the `music_tracks` quota bucket: | Plan | Music Tracks/Month | |------|-------------------| | Free | - | | Pro | 20 | | Business | 80 | **Top-up pricing:** $0.50 per track ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/music/generations \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "prompt": "Relaxing lo-fi hip hop beat with vinyl crackle and mellow piano", "duration_seconds": 30 }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/music/generations", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "prompt": "Epic orchestral trailer music with dramatic drums and strings", "duration_seconds": 45 } ) audio_url = response.json()["data"]["audio_url"] print(f"Music: {audio_url}") # Download the audio file audio = requests.get(audio_url) with open("music.mp3", "wb") as f: f.write(audio.content) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/music/generations", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ prompt: "Ambient electronic soundscape with ethereal pads", duration_seconds: 30, }), } ); const data = await response.json(); console.log(`Music URL: ${data.data.audio_url}`); ``` ## Prompt Writing Tips **Writing effective music prompts:** - Specify genre and style (e.g., "jazz", "electronic", "classical") - Include tempo/BPM when relevant - Describe instruments and sounds - Mention mood and atmosphere ### Example Prompts by Genre | Genre | Example Prompt | |-------|---------------| | Lo-fi | "Chill lo-fi hip hop beat, vinyl crackling, soft piano chords, rain sounds, 75 BPM" | | Electronic | "Energetic EDM drop with pulsing bass, synth leads, and build-up, 128 BPM" | | Cinematic | "Epic orchestral score with soaring strings, brass fanfare, and timpani drums" | | Jazz | "Smooth jazz trio with walking bass, brush drums, and warm piano improvisation" | | Ambient | "Peaceful ambient soundscape with gentle pads, nature sounds, and soft drones" | | Rock | "Classic rock guitar riff with driving drums and electric bass, 120 BPM" | | Classical | "Solo piano piece in the style of Chopin, romantic and melancholic" | | Hip Hop | "Boom bap beat with heavy 808s, crispy snares, and soulful vocal samples, 90 BPM" | ### Using Negative Prompts Exclude unwanted elements from your generation: ```json { "prompt": "Peaceful acoustic guitar melody", "negative_prompt": "drums, electronic, distortion, loud, vocals" } ``` ## Audio-to-Audio Mode Transform existing audio based on a text prompt: ```python response = requests.post( "https://www.aimagicx.com/api/v1/music/generations", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "prompt": "Make this more energetic with electronic beats", "mode": "audio_to_audio", "source_audio": "https://example.com/original-track.mp3", "duration_seconds": 30 } ) ``` ## Async Mode For production use, always use async mode: ```python import requests import time # Start async generation response = requests.post( "https://www.aimagicx.com/api/v1/music/generations?async=true", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "prompt": "Upbeat pop song with catchy melody", "duration_seconds": 45 } ) job_id = response.json()["id"] print(f"Job started: {job_id}") # Poll for completion with long-polling while True: status = requests.get( f"https://www.aimagicx.com/api/v1/jobs/{job_id}?poll=true", headers={"Authorization": "Bearer sk_your_api_key"} ).json() print(f"Status: {status['status']}, Progress: {status.get('progress', 0)}%") if status["status"] == "completed": print(f"Music URL: {status['outputData']['audio']['url']}") break elif status["status"] == "failed": print(f"Failed: {status.get('errorMessage')}") break time.sleep(2) ``` ## Output Formats | Format | Description | Best For | |--------|-------------|----------| | `mp3` | Compressed, smaller files | Web, streaming | | `wav` | Uncompressed, higher quality | Production, editing | ## Error Handling | Status | Error | Solution | |--------|-------|----------| | 400 | `prompt is required` | Provide a music description | | 400 | `duration_seconds exceeds maximum` | Keep under 47 seconds | | 402 | `Music track limit exceeded` | Upgrade plan or purchase top-up | | 403 | `Model tier not allowed` | Check plan permissions | ## Best Practices ### 1. Be Specific with Prompts Instead of: > "Happy music" Try: > "Uplifting acoustic folk song with strumming guitar, warm vocals, and light percussion, 110 BPM, major key" ### 2. Include Musical Details - **Tempo**: "120 BPM", "fast tempo", "slow and relaxed" - **Key/Mode**: "major key", "minor key", "modal" - **Instruments**: List specific instruments you want - **Style references**: "in the style of [artist/genre]" ### 3. Use Negative Prompts Remove unwanted elements: ```json { "prompt": "Calm meditation music", "negative_prompt": "drums, percussion, fast, intense, vocals" } ``` ### 4. Iterate and Refine Music generation has inherent randomness. Generate multiple versions and pick the best one: ```python results = [] for i in range(3): response = generate_music({ "prompt": "Jazz piano solo", "duration_seconds": 30 }) results.append(response["data"]["audio_url"]) ``` --- ## OpenAPI Specification URL: https://www.aimagicx.com/docs/api-reference/openapi Description: Download the AI Magicx OpenAPI 3.1 specification import { Callout } from 'fumadocs-ui/components/callout' # OpenAPI Specification AI Magicx provides a complete OpenAPI 3.1 specification that you can use to generate client libraries, explore the API, or import into tools like Postman, Insomnia, or Swagger UI. The OpenAPI spec is always up-to-date with the latest API changes and includes all endpoints, request/response schemas, and authentication details. ## Download Choose your preferred format: - **JSON**: [Download openapi.json](/api/openapi) - **YAML**: [Download openapi.yaml](/api/openapi?format=yaml) ## Quick Links | Tool | URL | |------|-----| | Swagger UI | `https://www.aimagicx.com/api/openapi` | | Postman Import | `https://www.aimagicx.com/api/openapi` | | OpenAPI Explorer | `https://www.aimagicx.com/api/openapi` | ## Using the Spec ### Import into Postman 1. Open Postman and click **Import** 2. Select **Link** and paste: `https://www.aimagicx.com/api/openapi` 3. Click **Import** to generate a collection ### Generate Client Libraries Use [OpenAPI Generator](https://openapi-generator.tech/) to create client libraries: ```bash # Install OpenAPI Generator npm install @openapitools/openapi-generator-cli -g # Generate TypeScript client openapi-generator-cli generate \ -i https://www.aimagicx.com/api/openapi \ -g typescript-fetch \ -o ./aimagicx-client # Generate Python client openapi-generator-cli generate \ -i https://www.aimagicx.com/api/openapi \ -g python \ -o ./aimagicx-python ``` ### View in Swagger UI You can view the interactive API documentation using Swagger UI: ```bash docker run -p 8080:8080 \ -e SWAGGER_JSON_URL=https://www.aimagicx.com/api/openapi \ swaggerapi/swagger-ui ``` Then open http://localhost:8080 in your browser. ## Spec Overview The OpenAPI specification includes: | Category | Endpoints | |----------|-----------| | Chat Completions | `POST /chat/completions` | | Image Generation | `POST /images/generations`, `POST /images/edits` | | Video Generation | `POST /videos/generations` | | Audio (TTS) | `POST /audio/speech` | | Audio (STT) | `POST /audio/transcriptions` | | Music | `POST /music/generations` | | Embeddings | `POST /embeddings` | | Models | `GET /models` | | Jobs | `GET /jobs/{jobId}` | ## Authentication All endpoints use Bearer token authentication: ```yaml securitySchemes: BearerAuth: type: http scheme: bearer ``` Include your API key in the Authorization header: ``` Authorization: Bearer sk_your_api_key ``` --- ## Speech-to-Text URL: https://www.aimagicx.com/docs/api-reference/speech-to-text Description: Transcribe audio to text with speaker detection and timestamps import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Speech-to-Text Transcribe audio files to text with support for multiple languages, speaker detection (diarization), timestamps, and translation. ## Try it Now Test the Speech-to-Text API directly in your browser: ## Endpoint ```http POST /audio/transcriptions ``` **Required scope:** `stt` ## Request Body ```json { "file": "https://example.com/audio.mp3", "model": "fal-ai/whisper", "language": "auto", "response_format": "json", "timestamp_granularities": ["segment"], "diarization": false, "translation": false } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `file` | string | Yes | - | Audio URL or base64 data | | `model` | string | No | `fal-ai/whisper` | STT model to use | | `language` | string | No | `auto` | ISO language code or `auto` | | `response_format` | string | No | `json` | Output format | | `timestamp_granularities` | array | No | `["segment"]` | Timestamp detail level | | `diarization` | boolean | No | `false` | Enable speaker detection | | `translation` | boolean | No | `false` | Translate to English | | `model_inputs` | object | No | - | Additional model-specific parameters | ### Available Models | Model ID | Tier | Features | |----------|------|----------| | `fal-ai/whisper` | Fast | Standard transcription (default) | | `fal-ai/wizper` | Standard | Enhanced accuracy | | `fal-ai/speech-to-text/turbo` | Fast | Fast transcription | | `fal-ai/elevenlabs/speech-to-text` | Premium | ElevenLabs quality | ### Response Formats | Format | Description | |--------|-------------| | `json` | JSON with text, segments, and metadata | | `text` | Plain text only | | `srt` | SubRip subtitle format | | `vtt` | WebVTT subtitle format | ### Timestamp Granularities - `segment` - Sentence/phrase level timestamps - `word` - Individual word timestamps ## Response (JSON format) ```json { "text": "Hello, this is a test recording.", "segments": [ { "start": 0.0, "end": 2.5, "text": "Hello, this is a test recording.", "speaker": null } ], "language": "en", "duration": 2.5, "model": "fal-ai/whisper", "model_tier": "fast", "usage": { "seconds_used": 3, "quota_multiplier": 1.0, "seconds_remaining": 3597 } } ``` ## Quota & Pricing STT uses the `stt_seconds` quota bucket. Duration is multiplied by the model tier: | Tier | Multiplier | Example Models | |------|------------|----------------| | Fast | 1x | Whisper | | Standard | 1.25x | Wizper | | Premium | 1.5x | Whisper Diarize | **Plan limits:** | Plan | STT Seconds/Month | |------|-------------------| | Free | - | | Pro | 3,600 (60 min) | | Business | 18,000 (300 min) | ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/audio/transcriptions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "file": "https://example.com/podcast.mp3", "language": "auto", "diarization": true }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/audio/transcriptions", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "file": "https://example.com/podcast.mp3", "language": "auto", "diarization": True, "timestamp_granularities": ["segment", "word"] } ) data = response.json() print(f"Transcript: {data['text']}") print(f"Duration: {data['duration']} seconds") print(f"Detected language: {data['language']}") ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/audio/transcriptions", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ file: "https://example.com/podcast.mp3", language: "auto", diarization: true, }), } ); const data = await response.json(); console.log(`Transcript: ${data.text}`); ``` ## Speaker Diarization Enable `diarization: true` to detect different speakers: ```json { "text": "Hello. Hi there. How are you?", "segments": [ { "start": 0.0, "end": 0.8, "text": "Hello.", "speaker": "SPEAKER_00" }, { "start": 1.0, "end": 1.5, "text": "Hi there.", "speaker": "SPEAKER_01" }, { "start": 2.0, "end": 2.8, "text": "How are you?", "speaker": "SPEAKER_00" } ] } ``` Speaker labels (SPEAKER_00, SPEAKER_01, etc.) are consistent within a single transcription but may vary between requests. ## Translation Set `translation: true` to translate non-English audio to English: ```json { "file": "https://example.com/spanish-audio.mp3", "translation": true } ``` The response will contain English text regardless of the source language. The original language is still detected and returned in the `language` field. ## Generating Subtitles Request SRT or VTT format for video subtitles: ```bash curl -X POST https://www.aimagicx.com/api/v1/audio/transcriptions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "file": "https://example.com/video.mp4", "response_format": "srt" }' ``` **Response:** ```text 1 00:00:00,000 --> 00:00:02,500 Hello, this is a test recording. 2 00:00:03,000 --> 00:00:05,200 And this is the second sentence. ``` ```bash curl -X POST https://www.aimagicx.com/api/v1/audio/transcriptions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "file": "https://example.com/video.mp4", "response_format": "vtt" }' ``` **Response:** ```text WEBVTT 00:00:00.000 --> 00:00:02.500 Hello, this is a test recording. 00:00:03.000 --> 00:00:05.200 And this is the second sentence. ``` ## Word-Level Timestamps Request word-level timestamps for precise synchronization: ```json { "file": "https://example.com/audio.mp3", "timestamp_granularities": ["word"] } ``` **Response includes:** ```json { "segments": [ { "start": 0.0, "end": 2.5, "text": "Hello world", "words": [ {"word": "Hello", "start": 0.0, "end": 0.5}, {"word": "world", "start": 0.6, "end": 1.0} ] } ] } ``` ## Supported Languages The API supports 90+ languages including: | Code | Language | Code | Language | |------|----------|------|----------| | `en` | English | `de` | German | | `es` | Spanish | `fr` | French | | `zh` | Chinese | `ja` | Japanese | | `ko` | Korean | `pt` | Portuguese | | `ar` | Arabic | `hi` | Hindi | | `ru` | Russian | `it` | Italian | | `nl` | Dutch | `pl` | Polish | | `tr` | Turkish | `vi` | Vietnamese | Use `language: "auto"` for automatic language detection. ## Error Handling Common errors you may encounter: | Status | Error | Solution | |--------|-------|----------| | 400 | `file is required` | Provide audio URL or base64 | | 402 | `STT limit exceeded` | Upgrade plan or wait for reset | | 403 | `Model tier not allowed` | Upgrade plan for premium models | | 500 | Transcription failed | Check audio format/quality | ## Supported Audio Formats - MP3 - WAV - M4A - FLAC - OGG - WebM For best results, use audio with: - Clear speech without excessive background noise - Sample rate of 16kHz or higher - Single speaker or clear speaker separation --- ## Text-to-Speech URL: https://www.aimagicx.com/docs/api-reference/text-to-speech Description: Convert text to natural-sounding speech with voice cloning import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Text-to-Speech Convert text into natural-sounding speech with multiple voice options and voice cloning capabilities. ## Try it Now Test the Text-to-Speech API directly in your browser: ## Endpoint ```http POST /audio/speech ``` **Required scope:** `tts` ## Request Body ```json { "input": "Hello, welcome to our API!", "model": "fal-ai/f5-tts", "voice": "nova", "speed": 1.0, "response_format": "mp3", "reference_audio": null, "reference_text": null } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `input` | string | Yes | - | Text to synthesize (max 10,000 chars) | | `model` | string | No | `fal-ai/f5-tts` | TTS model to use | | `voice` | string | No | `nova` | Voice preset or custom voice | | `speed` | number | No | `1.0` | Speech speed (0.25-4.0) | | `response_format` | string | No | `mp3` | Output format: `mp3`, `wav`, `opus`, `aac` | | `reference_audio` | string | No | - | Audio URL for voice cloning | | `reference_text` | string | No | - | Transcript of reference audio | ### Available Models | Model ID | Tier | Features | |----------|------|----------| | `fal-ai/f5-tts` | Standard | Voice cloning, natural speech (default) | | `fal-ai/maya` | Standard | High-quality synthesis | | `fal-ai/chatterbox/text-to-speech/turbo` | Fast | Fast generation | | `fal-ai/minimax/speech-2.6-hd` | Premium | HD quality speech | | `fal-ai/minimax/speech-2.6-turbo` | Fast | Fast MiniMax | | `fal-ai/index-tts-2/text-to-speech` | Standard | Index TTS 2.0 | | `fal-ai/chatterbox/text-to-speech/multilingual` | Standard | Multi-language support | ### Voice Presets | Voice | Description | |-------|-------------| | `alloy` | Neutral, balanced | | `echo` | Warm, conversational | | `fable` | Expressive, storytelling | | `onyx` | Deep, authoritative | | `nova` | Friendly, clear | | `shimmer` | Soft, gentle | Voice presets work best with the default model. For custom voices, use the voice cloning feature with `reference_audio`. ## Response ```json { "created": 1703123456, "audio_url": "https://fal.media/files/audio123.mp3", "duration_seconds": 3.5, "character_count": 35, "model": "fal-ai/f5-tts", "model_tier": "standard", "usage": { "chars_used": 35, "quota_multiplier": 1.25, "chars_remaining": 199965 } } ``` ## Quota & Pricing TTS uses the `tts_chars` quota bucket. Character usage is multiplied by the model tier: | Tier | Multiplier | Example Models | |------|------------|----------------| | Fast | 1x | F5-TTS Fast | | Standard | 1.25x | F5-TTS, MetaVoice | | Premium | 1.5x | Voice cloning models | **Plan limits:** | Plan | TTS Characters/Month | |------|---------------------| | Free | - | | Pro | 200,000 | | Business | 800,000 | ## Examples ```bash curl -X POST https://www.aimagicx.com/api/v1/audio/speech \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "input": "Welcome to AI Magicx! We are excited to have you here.", "voice": "nova", "speed": 1.1 }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/audio/speech", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "input": "Welcome to AI Magicx! We are excited to have you here.", "voice": "nova", "speed": 1.1 } ) audio_url = response.json()["audio_url"] print(f"Audio: {audio_url}") # Download the audio file audio_response = requests.get(audio_url) with open("output.mp3", "wb") as f: f.write(audio_response.content) ``` ```typescript const response = await fetch( "https://www.aimagicx.com/api/v1/audio/speech", { method: "POST", headers: { "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json", }, body: JSON.stringify({ input: "Welcome to AI Magicx! We are excited to have you here.", voice: "nova", speed: 1.1, }), } ); const data = await response.json(); console.log(`Audio URL: ${data.audio_url}`); ``` ## Voice Cloning Clone any voice using a reference audio sample with the F5-TTS model: ```python response = requests.post( "https://www.aimagicx.com/api/v1/audio/speech", headers={"Authorization": "Bearer sk_your_api_key"}, json={ "input": "This is my cloned voice speaking.", "model": "fal-ai/f5-tts", "reference_audio": "https://example.com/voice-sample.mp3", "reference_text": "Hello, this is a sample of my voice." } ) ``` **For best voice cloning results:** - Use a clear audio sample (5-15 seconds) - Provide accurate transcript via `reference_text` - Avoid background noise in the reference - MP3 or WAV formats work best ## Model-Specific Inputs Pass additional parameters using `model_inputs`: ```json { "input": "Hello world", "model": "fal-ai/metavoice", "model_inputs": { "guidance_scale": 3.0, "top_p": 0.95 } } ``` ## Error Handling Common errors you may encounter: | Status | Error | Solution | |--------|-------|----------| | 400 | `input is required` | Provide non-empty text | | 400 | `input text exceeds maximum length` | Keep under 10,000 characters | | 400 | `speed must be between 0.25 and 4.0` | Adjust speed value | | 402 | `TTS character limit exceeded` | Upgrade plan or wait for reset | | 403 | `Model tier not allowed` | Upgrade plan for premium models | ## Use Cases | Use Case | Recommended Settings | |----------|---------------------| | Podcast intros | `voice: "echo"`, `speed: 0.95` | | Audiobook narration | `voice: "fable"`, `speed: 0.9` | | Voice assistants | `voice: "nova"`, `speed: 1.1` | | Announcements | `voice: "onyx"`, `speed: 1.0` | | Meditation guides | `voice: "shimmer"`, `speed: 0.85` | | Custom brand voice | Use voice cloning with your audio | --- ## Video Generation URL: https://www.aimagicx.com/docs/api-reference/video-generation Description: Generate videos from text prompts or images import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Video Generation Generate high-quality videos from text descriptions or source images using MiniMax, Luma, and other video models. Video generation is resource-intensive. We recommend using **async mode** for all video requests. ## Try it Now Test the Video Generation API directly in your browser: ## Endpoint ```http POST /videos/generations POST /videos/generations?async=true ``` **Required scope:** `video` ## Request Body ```json { "prompt": "A timelapse of a flower blooming", "model": "fal-ai/minimax/video-01", "duration_seconds": 5, "resolution": "720p", "fps": 30, "aspect_ratio": "16:9", "mode": "text_to_video", "source_image": null, "negative_prompt": "blurry, static", "seed": null, "prompt_optimizer": true, "loop": false } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `prompt` | string | Yes | - | Text description of the video | | `model` | string | No | `fal-ai/minimax/video-01` | Model ID | | `duration_seconds` | number | No | `5` | Video duration in seconds | | `resolution` | string | No | `720p` | `720p`, `1080p`, or `4k` | | `fps` | number | No | `30` | Frames per second: `30` or `60` | | `aspect_ratio` | string | No | `16:9` | Aspect ratio | | `mode` | string | No | `text_to_video` | Generation mode | | `source_image` | string | No | - | Image URL for image-to-video | | `source_video` | string | No | - | Video URL for video-to-video | | `negative_prompt` | string | No | - | What to avoid | | `seed` | number | No | random | Random seed | | `prompt_optimizer` | boolean | No | `true` | Enhance prompt (MiniMax) | | `loop` | boolean | No | `false` | Create looping video (Luma) | ### Aspect Ratios - `16:9` - Landscape (default) - `9:16` - Portrait (vertical video) - `1:1` - Square - `4:3` - Classic - `3:4` - Tall ### Generation Modes | Mode | Description | |------|-------------| | `text_to_video` | Generate video from text prompt | | `image_to_video` | Animate a source image | | `video_to_video` | Transform an existing video | ## Response ```json { "created": 1703123456, "data": { "url": "https://fal.media/files/video123.mp4", "duration_seconds": 5, "width": 1280, "height": 720 }, "model": "fal-ai/minimax/video-01", "model_tier": "standard", "usage": { "credits_used": 500, "seconds_used": 5, "seconds_remaining": 55 } } ``` ## Async Response ```json { "id": "job_video123", "status": "pending", "created": 1703123456, "model": "fal-ai/minimax/video-01", "estimated_credits": 500 } ``` ## Examples ```bash curl -X POST "https://www.aimagicx.com/api/v1/videos/generations?async=true" \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A drone flyover of a tropical beach at golden hour, cinematic", "duration_seconds": 5, "aspect_ratio": "16:9" }' ``` ```python import requests response = requests.post( "https://www.aimagicx.com/api/v1/videos/generations?async=true", headers={ "Authorization": "Bearer sk_your_api_key", "Content-Type": "application/json" }, json={ "prompt": "The person slowly turns and smiles", "mode": "image_to_video", "source_image": "https://example.com/portrait.jpg", "duration_seconds": 3 } ) job_id = response.json()["id"] print(f"Job started: {job_id}") ``` ```python import requests import time # Start the job response = requests.post( "https://www.aimagicx.com/api/v1/videos/generations?async=true", headers={"Authorization": "Bearer sk_your_api_key"}, json={"prompt": "Ocean waves crashing on rocks", "duration_seconds": 5} ) job_id = response.json()["id"] # Poll until complete while True: status = requests.get( f"https://www.aimagicx.com/api/v1/jobs/{job_id}?poll=true", headers={"Authorization": "Bearer sk_your_api_key"} ).json() print(f"Status: {status['status']}, Progress: {status.get('progress', 0)}%") if status["status"] == "completed": print(f"Video URL: {status['outputData']['video']['url']}") break elif status["status"] == "failed": print(f"Failed: {status.get('errorMessage')}") break time.sleep(5) ``` ## Available Models ### Text-to-Video | Model | Quality | Best For | |-------|---------|----------| | `fal-ai/minimax/video-01` | Excellent | Realistic, high quality (default) | | `fal-ai/minimax/hailuo-02/standard/text-to-video` | Excellent | Latest MiniMax | | `fal-ai/veo3` | Excellent | Google Veo 3 | | `fal-ai/veo3/fast` | Good | Fast Veo 3 | | `fal-ai/kling-video/v2.5-turbo/pro/text-to-video` | Excellent | Kling v2.5 | | `fal-ai/kling-video/v2/master/text-to-video` | Excellent | Kling 2.0 Master | | `fal-ai/pixverse/v5.5/text-to-video` | Good | Pixverse | | `fal-ai/ltx-2/text-to-video/fast` | Good | Fast LTX Video 2.0 | ### Image-to-Video | Model | Quality | Best For | |-------|---------|----------| | `fal-ai/minimax/video-01/image-to-video` | Excellent | Animate images | | `fal-ai/veo2/image-to-video` | Excellent | Google Veo 2 | | `fal-ai/kling-video/v2.5-turbo/pro/image-to-video` | Excellent | Kling v2.5 | | `fal-ai/wan-pro/image-to-video` | Excellent | Wan 2.1 Pro | | `fal-ai/minimax/hailuo-2.3/pro/image-to-video` | Excellent | Hailuo 2.3 | | `fal-ai/bytedance/seedance/v1/pro/image-to-video` | Good | ByteDance Seedance | ## Tips for Better Videos **Writing effective video prompts:** - Describe motion explicitly ("camera pans left", "person walks forward") - Include temporal cues ("timelapse", "slow motion") - Specify camera angles ("close-up", "aerial shot", "tracking shot") - Mention lighting and atmosphere ### Example Prompts | Type | Prompt | |------|--------| | Nature | "Timelapse of clouds rolling over mountain peaks, golden hour lighting, 4K cinematic" | | Portrait | "Close-up of a woman's face, gentle wind blowing her hair, soft natural lighting" | | Action | "Sports car drifting around a corner, dust and smoke, dramatic slow motion" | | Abstract | "Flowing liquid metal morphing into geometric shapes, reflective surface, dark background" | --- ## AI Magicx CLI URL: https://www.aimagicx.com/docs/cli Description: AI-powered coding agent for the terminal with multi-provider support, semantic search, and extensible tools import { Callout } from 'fumadocs-ui/components/callout' import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Step, Steps } from 'fumadocs-ui/components/steps' AI Magicx CLI is an AI-powered coding agent that brings intelligent code assistance directly to your terminal. It supports multiple LLM providers, persistent sessions, semantic code search, and extensible tools. Current version: **0.1.9** | Requires Node.js 18+ ## Features - **Multi-Provider Support** - OpenAI, Anthropic, GitHub Copilot, OpenRouter, Groq, and more - **Interactive TUI** - Rich terminal interface with markdown rendering - **Agent Mode** - AI with access to file operations, shell commands, and web search - **Approval Modes** - Control autonomy: read-only, auto, or full - **Background Tasks** - Spawn parallel agents for concurrent work - **Session Management** - Resume conversations, auto-compact, export transcripts - **Semantic Code Search** - Vector-indexed codebase for intelligent context retrieval - **LSP Integration** - Go-to-definition, find references, hover info, diagnostics - **Memory System** - Persistent memories across sessions - **MCP Integration** - Extend capabilities with Model Context Protocol servers - **Custom Commands & Agents** - Define your own slash commands and specialized agents ## Installation ```bash npm install -g @aimagicx/cli ``` ```bash pnpm add -g @aimagicx/cli ``` ## Quick Start ```bash # Start the TUI (opens provider connect if not authenticated) aimagicx # With a specific model aimagicx chat -m gpt-4o # Resume a previous session aimagicx -r # One-shot prompt aimagicx chat -p "Explain this codebase" ``` ## Keyboard Shortcuts ### Global Shortcuts | Shortcut | Action | |----------|--------| | `Ctrl+L` | Switch model | | `Ctrl+N` | New session | | `Ctrl+O` | Connect provider | | `Ctrl+C` | Cancel current operation (2x to quit) | | `Ctrl+W` | Quit immediately | | `Ctrl+Z` | Undo last file change | | `Ctrl+Y` | Redo last undone change | | `Ctrl+X` | Toggle expand/collapse messages | | `Esc Esc` | Rewind to last checkpoint | | `Tab` | Cycle approval mode (read-only → auto → full) | | `Shift+Tab` | Cycle modes (Agent → Review → Plan) | | `Alt+T` | Toggle task panel | | `/` | Open command palette | | `@` | Attach file | | `#` | Save/attach memory | | `$` | Save/insert snippet | | `*` | Toggle favorite (in model selector) | ### Input Shortcuts | Shortcut | Action | |----------|--------| | `Ctrl+U` | Clear input line | | `Escape` | Clear input (if not empty) | | `Ctrl+A` | Jump to beginning of line | | `Ctrl+E` | Jump to end of line | | `Ctrl+N` | Insert new line (multiline input) | | `↑` / `↓` | Navigate input history | ## Commands ### Authentication ```bash # Login with API key aimagicx auth login aimagicx auth login --provider anthropic # Check auth status aimagicx auth status # Logout aimagicx auth logout aimagicx auth logout --provider openai ``` ### Chat ```bash # Start interactive chat aimagicx chat # Use specific model aimagicx chat -m claude-sonnet-4-20250514 # Resume previous session aimagicx chat -r # Set approval mode aimagicx chat -a read-only # Read-only mode (exploration only) aimagicx chat -a auto # Auto mode (default) aimagicx chat -a full # Full mode (auto-approve all) aimagicx chat --yolo # Alias for --approval-mode full # Headless mode (for automation/scripts) aimagicx chat -p "Fix the bug" --headless ``` ### Providers ```bash # List configured providers aimagicx provider list # Show available presets aimagicx provider presets # Add provider from preset aimagicx provider add anthropic --preset anthropic # Add custom provider aimagicx provider add my-provider \ --endpoint https://api.example.com/v1 \ --protocol openai \ --model gpt-4 # Switch active provider aimagicx provider use anthropic # Remove provider aimagicx provider remove openai ``` ### Sessions ```bash # List sessions aimagicx session list aimagicx session list --all # Resume session aimagicx session resume # Rename session aimagicx session rename "Feature Implementation" # Compact session (reduce context) aimagicx session compact # Export session aimagicx session export --format markdown aimagicx session export --format json # Delete session aimagicx session delete ``` ### Configuration ```bash # Show all config aimagicx config list # Get specific value aimagicx config get defaultModel # Set value aimagicx config set maxTokens 8192 aimagicx config set autoConfirmWrites true # Initialize project config aimagicx config init # Show config paths aimagicx config path # Reset to defaults aimagicx config reset ``` ### Semantic Search Index ```bash # Build vector index aimagicx index build # Check index status aimagicx index status # Search codebase aimagicx index search "authentication logic" ``` ### Shell Completions ```bash aimagicx completion bash >> ~/.bashrc # Or aimagicx completion bash > /etc/bash_completion.d/aimagicx ``` ```bash mkdir -p ~/.zsh/completions aimagicx completion zsh > ~/.zsh/completions/_aimagicx # Add to ~/.zshrc: # fpath=(~/.zsh/completions $fpath) # autoload -Uz compinit && compinit ``` ```bash mkdir -p ~/.config/fish/completions aimagicx completion fish > ~/.config/fish/completions/aimagicx.fish ``` ### Other Commands ```bash # Check API quota/usage aimagicx usage # Run diagnostics aimagicx doctor # Start server for IDE extensions aimagicx serve # Check for updates aimagicx update ``` ## In-Chat Commands Type `/` to open the command palette: | Command | Description | |---------|-------------| | `/new-session` | Start new session | | `/session-list` | List sessions | | `/compact` | Summarize conversation to reduce context | | `/switch-model` | Switch model | | `/provider-connect` | Connect a provider | | `/index-build` | Build semantic search index | | `/memories` | List saved memories | | `/commit` | Generate AI commit message | | `/diff` | Show git status/diff | | `/undo` | Undo last file change | | `/redo` | Redo last undone change | | `/history` | Show recent file changes | | `/tools` | Open Tool Manager | | `/checkpoint` | Create manual checkpoint | | `/rewind` | Rewind to last checkpoint | | `/spawn` | Spawn a background task | | `/tasks` | List background tasks | | `/mcp-status` | Show MCP server status | | `/approval-mode` | Cycle approval mode | | `/quota` | Show API quota/balance | | `/help` | Show keyboard shortcuts | | `/quit` | Exit chat | ## Configuration ### Config Locations | Type | Location | |------|----------| | Global config | `~/.aimagicx/config.json` | | Project config | `.aimagicx/config.json` | | Credentials | `~/.aimagicx/credentials.d/` | | Sessions | `~/.aimagicx/sessions/` | | Memories | `~/.aimagicx/memory/` | | Vector Index | `.aimagicx/index/` | | Custom Commands | `~/.aimagicx/commands.json` | | Custom Agents | `~/.aimagicx/agents.json` | | MCP Servers | `~/.aimagicx/mcp.json` | | LSP Servers | `~/.aimagicx/lsp.json` | | Checkpoints | `.aimagicx/checkpoints/` | | Context Files | `AI_MAGICX.md` | | Ignore Patterns | `.aimagicxignore` | ### Config Options ```json { "defaultModel": "claude-sonnet-4-20250514", "maxTokens": 16384, "maxToolIterations": 10, "autoConfirmWrites": false, "showTokenUsage": true, "contextThreshold": 0.9, "autoCompactEnabled": true, "useVectorIndex": true, "maxContextChunks": 10, "maxContextTokens": 8000, "minContextScore": 0.15, "favoriteModels": ["gpt-4o", "claude-sonnet-4-20250514"], "disabledTools": [], "approvalMode": "auto" } ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `defaultModel` | string | - | Default model to use | | `maxTokens` | number | 16384 | Maximum tokens per request | | `maxToolIterations` | number | 10 | Max tool calls per response | | `autoConfirmWrites` | boolean | false | Skip file operation confirmations | | `contextThreshold` | number | 0.9 | Auto-compact threshold (0-1) | | `useVectorIndex` | boolean | true | Enable semantic code search | | `approvalMode` | string | "auto" | Default: read-only, auto, or full | ## Supported Providers | Provider | Protocol | Default Model | Auth | |----------|----------|---------------|------| | Anthropic | anthropic | claude-sonnet-4-5-20250929 | API Key | | OpenAI | openai | gpt-4o-mini | API Key | | GitHub Copilot | openai | gpt-4o | OAuth | | OpenRouter | openai | openai/gpt-4o-mini | API Key | | Groq | openai | moonshotai/kimi-k2 | API Key | | AI Magicx | aimagicx | openai/gpt-oss-120b | API Key | ### Adding Custom Providers ```bash aimagicx provider add ollama \ --endpoint http://localhost:11434/v1 \ --protocol openai \ --model llama3.2 ``` ## Agent Tools | Tool | Description | |------|-------------| | `read` | Read file contents with line numbers | | `write` | Create new files | | `edit` | Modify existing files | | `apply_patch` | Apply unified diff patches | | `glob` | Find files by pattern | | `grep` | Search file contents with regex | | `bash` | Execute shell commands | | `list_directory` | List directory contents | | `web_search` | Search the web | | `web_fetch` | Fetch and analyze web pages | | `vector_search` | Semantic code search | | `vision` | Analyze images | | `save_memory` | Save persistent memories | | `lsp_goto_definition` | Navigate to symbol definition | | `lsp_find_references` | Find all references | | `lsp_hover` | Get type info and docs | | `lsp_diagnostics` | Get file errors/warnings | | `todos` | Track multi-step tasks | | `spawn_agent` | Spawn specialized subagents | ### Tool Modes - **Agent Mode** (default) - Full access to all tools - **Review Mode** - Collects changes for batch review - **Plan Mode** - Read-only tools for exploration Toggle with `Shift+Tab`. ## Approval Modes | Mode | Description | Use Case | |------|-------------|----------| | `read-only` | Only exploration tools | Safe exploration | | `auto` | Confirm file changes and shell commands | Normal development | | `full` | Auto-approve all operations | Trusted automation | ```bash # Change via CLI aimagicx chat -a read-only aimagicx chat --yolo # Alias for -a full # Or press Tab to cycle modes during chat ``` ## Background Tasks Spawn parallel agents to work concurrently: ```bash # In chat /spawn Run all tests and fix any failures /spawn Generate API documentation # Monitor /tasks # Kill a task /task-kill ``` ### Task Status | Status | Icon | Description | |--------|------|-------------| | pending | ⏳ | Waiting to start | | running | 🔄 | Actively executing | | completed | ✅ | Finished successfully | | failed | ❌ | Encountered error | | cancelled | ⏹️ | Manually stopped | ## Context Files (AI_MAGICX.md) Create `AI_MAGICX.md` files to provide persistent context: ```markdown # Project: My App ## Architecture - React frontend with TypeScript - Express backend with PostgreSQL ## Conventions - Use functional components with hooks - All API responses follow { data, error, meta } format ## Do NOT modify - src/legacy/ (deprecated) @docs/api-reference.md ``` Use `@path/to/file.md` to import content from other files. ## Memory System Save important information that persists across sessions: ```bash # In chat, use # prefix #project-context This is a React app using TypeScript... # Or type # to open the memory picker ``` Memories are stored as markdown files in `~/.aimagicx/memory/` (global) or `.aimagicx/memory/` (project). ## Custom Commands Create custom slash commands in `~/.aimagicx/commands.json`: ```json { "commands": [ { "id": "review", "name": "Code Review", "description": "Review current file", "type": "prompt", "content": "Review this code for bugs and security issues:\n\n{{input}}" }, { "id": "git-log", "name": "Git Log", "type": "bash", "content": "git log --oneline -10", "showOutput": true } ] } ``` ## Custom Agents Define specialized agents in `~/.aimagicx/agents.json`: ```json { "agents": [ { "id": "reviewer", "name": "Code Reviewer", "icon": "🔍", "systemPrompt": "You are an expert code reviewer...", "model": "claude-sonnet-4-20250514", "includeContext": true } ] } ``` ## MCP Integration Configure MCP servers in `~/.aimagicx/mcp.json`: ```json { "servers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"] }, "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "your-token" } } } } ``` Use `/mcp-status`, `/mcp-connect`, `/mcp-disconnect` to manage. ## LSP Integration Configure LSP servers in `~/.aimagicx/lsp.json`: ```json { "servers": [ { "name": "typescript", "languages": [".ts", ".tsx", ".js", ".jsx"], "command": "typescript-language-server", "args": ["--stdio"], "enabled": true } ], "autoDetect": true, "autoStart": true } ``` ### Default LSP Servers | Language | Server | Extensions | |----------|--------|------------| | TypeScript/JS | `typescript-language-server` | `.ts`, `.tsx`, `.js`, `.jsx` | | Python | `pylsp` | `.py` | | Go | `gopls` | `.go` | | Rust | `rust-analyzer` | `.rs` | ## Custom Ignore File Control which files AI Magicx ignores in `.aimagicxignore`: ```txt # Large data files *.csv data/ # Sensitive files .env* secrets/ # Generated files dist/ build/ ``` ## IDE Extensions (Server Mode) AI Magicx runs as a JSON-RPC server for IDE integration: ```bash aimagicx serve ``` ### Protocol Uses JSON-RPC 2.0 over stdio: | Method | Description | |--------|-------------| | `initialize` | Initialize with project path | | `chat` | Send message, receive streaming response | | `tool/confirm` | Confirm or deny tool execution | | `session/list` | List available sessions | | `abort` | Cancel current operation | | `shutdown` | Gracefully shutdown | ## Security ### File Access - Use `allowedReadRoots` to restrict file access - Write operations require confirmation (unless `autoConfirmWrites: true`) - Dangerous bash commands are blocked ### Credentials - API keys stored with restricted permissions (0600) - Keys never logged or displayed in full - Environment variable fallback: `AI_MAGICX_API_KEY` ### Blocked Commands - `rm -rf /` and system path deletions - `shutdown`, `reboot`, `halt` - Fork bombs - Device file writes ## Environment Variables | Variable | Description | |----------|-------------| | `AI_MAGICX_API_KEY` | Default API key (fallback) | | `AI_MAGICX_CONFIG_DIR` | Custom config directory | | `NO_COLOR` | Disable colored output | ## Telemetry AI Magicx collects anonymous usage data (optional): **Collected:** CLI version, session duration, tool execution stats, feature usage **NOT collected:** File paths, code content, prompts, API keys, PII ```bash # Opt out aimagicx config set telemetryEnabled false ``` ## Troubleshooting ### Run Diagnostics ```bash aimagicx doctor ``` ### Common Issues **"Not authenticated"** ```bash aimagicx auth login --provider ``` **"Model not found"** - Verify model name matches provider's naming - Check `aimagicx provider presets` for defaults **High context usage** ```bash /compact # Or aimagicx session compact ``` **GitHub Copilot auth issues** - Tokens expire quickly (~30 min) - Reconnect with `Ctrl+O` ## Best Practices ### Start in Read-Only Mode Use `aimagicx chat -a read-only` for safe exploration of unfamiliar code. ### Use AI_MAGICX.md for Context Create a `AI_MAGICX.md` in your project root with architecture and conventions. ### Build the Vector Index Run `aimagicx index build` for large codebases to enable semantic search. ### Use Sessions for Complex Tasks Resume conversations with `aimagicx chat -r ` to maintain context. ### Leverage Checkpoints Use `/checkpoint` before risky changes, `/rewind` or `Esc Esc` to rollback. ## Links - [AI Magicx Homepage](https://www.aimagicx.com/cli) --- ## Async Jobs URL: https://www.aimagicx.com/docs/guides/async-jobs Description: Handle long-running operations with async jobs import { Callout } from 'fumadocs-ui/components/callout' # Async Jobs For long-running operations like video and music generation, use async mode to avoid timeouts and provide better user experience. ## When to Use Async Use async mode for: - Video generation (30-120 seconds) - Music generation (30-60 seconds) - High-resolution image generation - Batch operations ## Workflow ``` 1. Submit request with ?async=true 2. Receive job ID immediately 3. Poll /jobs/{id} for status 4. Retrieve result when complete ``` ## Implementation ```python import requests import time class AsyncJobHandler: def __init__(self, api_key): self.api_key = api_key self.base_url = "https://www.aimagicx.com/api/v1" self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } def submit_job(self, endpoint, data): """Submit an async job and return job ID.""" response = requests.post( f"{self.base_url}/{endpoint}?async=true", headers=self.headers, json=data ) response.raise_for_status() return response.json()["id"] def poll_job(self, job_id, interval=5, timeout=300): """Poll job until completion or timeout.""" start_time = time.time() while time.time() - start_time < timeout: response = requests.get( f"{self.base_url}/jobs/{job_id}?poll=true", headers=self.headers ) response.raise_for_status() status = response.json() if status["status"] == "completed": return status if status["status"] == "failed": raise Exception(f"Job failed: {status.get('errorMessage')}") if status["status"] == "cancelled": raise Exception("Job was cancelled") progress = status.get("progress", 0) print(f"Progress: {progress}%") time.sleep(interval) raise TimeoutError("Job polling timed out") def run(self, endpoint, data, callback=None): """Submit and poll until completion.""" job_id = self.submit_job(endpoint, data) print(f"Job started: {job_id}") result = self.poll_job(job_id) if callback: callback(result) return result # Usage handler = AsyncJobHandler("sk_your_api_key") result = handler.run( "videos/generations", {"prompt": "A sunset over mountains", "duration_seconds": 5} ) print(f"Video URL: {result['outputData']['video']['url']}") ``` ## Progress Tracking ```typescript async function generateWithProgress( endpoint: string, data: object, onProgress?: (progress: number) => void ): Promise { // Submit job const submitResponse = await fetch( `${BASE_URL}/${endpoint}?async=true`, { method: "POST", headers, body: JSON.stringify(data), } ); const { id: jobId } = await submitResponse.json(); // Poll with progress callback while (true) { const statusResponse = await fetch( `${BASE_URL}/jobs/${jobId}?poll=true`, { headers } ); const status = await statusResponse.json(); if (onProgress && status.progress !== undefined) { onProgress(status.progress); } if (status.status === "completed") { return status; } if (status.status === "failed") { throw new Error(status.errorMessage); } await new Promise((r) => setTimeout(r, 5000)); } } // Usage with progress bar await generateWithProgress( "videos/generations", { prompt: "A flying bird" }, (progress) => console.log(`Progress: ${progress}%`) ); ``` ## Cancelling Jobs ```python def cancel_job(job_id): response = requests.delete( f"{BASE_URL}/jobs/{job_id}", headers=headers ) return response.json().get("success", False) ``` ## Best Practices 1. **Implement exponential backoff** - Increase poll interval over time 2. **Set reasonable timeouts** - Video: 5 min, Music: 3 min 3. **Handle all status types** - pending, processing, completed, failed, cancelled 4. **Store job IDs** - Allow users to check status later 5. **Show progress** - Use the `progress` field to update UI --- ## Best Practices URL: https://www.aimagicx.com/docs/guides/best-practices Description: Tips and patterns for building production applications import { Callout } from 'fumadocs-ui/components/callout' # Best Practices Follow these best practices to build reliable, efficient applications with the AI Magicx API. ## API Key Security Never expose your API key in client-side code or public repositories. **Do:** - Store API keys in environment variables - Use server-side API routes to proxy requests - Rotate keys periodically - Use minimal scopes **Don't:** - Commit keys to git - Include keys in client-side JavaScript - Share keys in logs or error messages ```python # Good: Use environment variables import os api_key = os.environ.get("AI_MAGICX_API_KEY") # Bad: Hardcoded key api_key = "sk_live_abc123..." # Never do this! ``` ## Request Optimization ### Batch When Possible ```python # Instead of multiple single requests for prompt in prompts: generate_image(prompt) # 10 requests # Use batch parameters where supported generate_images(prompts, n=10) # 1 request ``` ### Cache Responses ```python import hashlib import json def get_cached_or_fetch(prompt, cache): cache_key = hashlib.md5(prompt.encode()).hexdigest() if cache_key in cache: return cache[cache_key] result = make_api_request(prompt) cache[cache_key] = result return result ``` ### Use Appropriate Models | Task | Recommended Model | |------|-------------------| | Simple chat | `openai/gpt-4o-mini` | | Complex reasoning | `openai/gpt-4o` | | Quick drafts | `fal-ai/hidream-i1-fast` | | Production images | `fal-ai/flux/dev` | ## Rate Limit Management ```python import time from collections import deque class RateLimiter: def __init__(self, requests_per_minute=60): self.requests_per_minute = requests_per_minute self.request_times = deque() def wait_if_needed(self): now = time.time() minute_ago = now - 60 # Remove old timestamps while self.request_times and self.request_times[0] < minute_ago: self.request_times.popleft() # Wait if at limit if len(self.request_times) >= self.requests_per_minute: sleep_time = self.request_times[0] - minute_ago time.sleep(sleep_time) self.request_times.append(now) limiter = RateLimiter(60) for request in requests: limiter.wait_if_needed() make_request(request) ``` ## Error Recovery ```python def robust_generate(prompt, max_retries=3): """Generate with automatic retry and fallback.""" errors = [] for attempt in range(max_retries): try: return generate(prompt) except RateLimitError as e: time.sleep(e.retry_after) errors.append(e) except QuotaExceededError: raise # Can't retry this except APIError as e: if e.status_code >= 500: time.sleep(2 ** attempt) errors.append(e) else: raise # All retries failed - try fallback model try: return generate(prompt, model="fallback-model") except Exception: raise errors[-1] ``` ## Prompt Engineering ### Be Specific ```python # Vague prompt "A dog" # Better prompt "A golden retriever playing fetch in a sunny park, photorealistic, shallow depth of field" ``` ### Use System Messages ```python messages = [ { "role": "system", "content": "You are a helpful coding assistant. Provide concise, " "working code examples. Always include error handling." }, {"role": "user", "content": "Write a function to fetch JSON from a URL"} ] ``` ### Test and Iterate ```python def optimize_prompt(base_prompt, test_inputs, scorer): """A/B test prompts to find the best version.""" variants = [ base_prompt, f"Be concise. {base_prompt}", f"{base_prompt} Think step by step.", ] scores = {} for variant in variants: results = [run(variant, input) for input in test_inputs] scores[variant] = sum(scorer(r) for r in results) return max(scores, key=scores.get) ``` ## Monitoring ### Log Request Metrics ```python import logging import time logging.basicConfig(level=logging.INFO) logger = logging.getLogger("aimagicx") def logged_request(endpoint, data): start = time.time() try: result = make_request(endpoint, data) duration = time.time() - start logger.info( f"Request to {endpoint} succeeded in {duration:.2f}s, " f"credits used: {result.get('usage', {}).get('credits_used', 0)}" ) return result except Exception as e: duration = time.time() - start logger.error(f"Request to {endpoint} failed after {duration:.2f}s: {e}") raise ``` ### Track Usage ```python class UsageTracker: def __init__(self): self.total_credits = 0 self.requests = 0 def track(self, response): usage = response.get("usage", {}) self.total_credits += usage.get("credits_used", 0) self.requests += 1 def report(self): return { "total_credits": self.total_credits, "total_requests": self.requests, "avg_credits_per_request": self.total_credits / max(1, self.requests) } ``` ## Checklist Before going to production: - [ ] API keys stored securely in environment variables - [ ] Error handling with retries and backoff - [ ] Rate limiting to stay within quota - [ ] Request logging and monitoring - [ ] Timeout handling for long operations - [ ] Graceful degradation for failures - [ ] User-friendly error messages - [ ] Caching where appropriate --- ## Credits & Quotas URL: https://www.aimagicx.com/docs/guides/credits-and-quotas Description: Understanding the AI Magicx credit system, quotas, and usage tracking import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Credits & Quotas AI Magicx uses a quota-based system to track and manage API usage. This guide explains how quotas work, how they're structured, and how to monitor your usage. ## How Credits Work **1 credit = 1,000 tokens** (input + output combined) Credits are used for chat completions. Your monthly credit allowance determines how many tokens you can use for AI chat. ## Quota Limits by Plan ### Web App Plans | Resource | Free | Pro | Business | |----------|------|-----|----------| | **Credits** | 100/mo | 200/mo | 800/mo | | Image generations | - | 150/mo | 600/mo | | Image edits | - | 75/mo | 300/mo | | Video seconds | - | 15 min/mo | 60 min/mo | | STT seconds | - | 60 min/mo | 300 min/mo | | TTS characters | - | 200K/mo | 800K/mo | | Music tracks | - | 20/mo | 80/mo | ### CLI Plans (API-only) | Resource | CLI Pro | CLI Team | |----------|---------|----------| | **Credits** | 2,000/mo | 10,000/mo | | Team members | 1 | 3 | | All model tiers | ✓ | ✓ | **Token conversion:** 1 credit = 1,000 tokens. A Pro plan with 200 credits gives you 200,000 tokens per month. ## Model Tiers Models are categorized into tiers that affect credit consumption: ### Basic Tier (1x multiplier) - GPT-4o Mini - Claude 3 Haiku - Gemini 1.5 Flash - Llama 3.1 8B - Flux Schnell - SD 3.5 Turbo ### Standard Tier (1.5-2x multiplier) - GPT-4o - Claude 3.5 Sonnet - Gemini 1.5 Pro - Llama 3.1 70B - Flux Dev - MiniMax Video ### Powerful Tier (2-3x multiplier) - GPT-4 Turbo - Claude 3 Opus - o1 Preview - Llama 3.1 405B - Flux Pro - Luma Pro ## Checking Your Quota ### Via Dashboard Go to **Dashboard → Usage** to see: - Current credit balance - Usage breakdown by bucket - Historical usage graphs - Upcoming reset date ### Via API ```bash curl https://www.aimagicx.com/api/v1/quota \ -H "Authorization: Bearer sk_your_api_key" ``` **Response:** ```json { "org_id": "org_abc123", "plan": { "code": "pro_monthly", "name": "Pro Monthly", "kind": "recurring", "entitled": true, "period_end": "2025-02-01T00:00:00Z" }, "quotas": { "credits": { "remaining": 170, "limit": 200, "used": 30, "usage_percent": 15 }, "image_generations": { "remaining": 138, "limit": 150, "used": 12, "usage_percent": 8 }, "video_seconds": { "remaining": 810, "limit": 900, "used": 90, "usage_percent": 10 }, "stt_seconds": { "remaining": 3240, "limit": 3600, "used": 360, "usage_percent": 10 } } } ``` ## Usage in Responses Every API response includes usage information: ### Chat Completions ```json { "choices": [...], "usage": { "prompt_tokens": 150, "completion_tokens": 200, "total_tokens": 350 }, "model": "openai/gpt-4o-mini", "model_tier": "basic" } ``` Tokens are deducted from your credit balance. 1,000 tokens = 1 credit. ### Image Generation ```json { "data": [...], "usage": { "generations_used": 1, "generations_remaining": 149 }, "model": "fal-ai/flux/dev", "model_tier": "standard" } ``` ### Video Generation ```json { "data": {...}, "usage": { "seconds_used": 5, "seconds_remaining": 895 }, "model": "fal-ai/minimax/video-01", "model_tier": "standard" } ``` ## Quota Exceeded Errors When you exceed a quota, you'll receive a `402 Payment Required` response: ```json { "error": "Quota exceeded for image_generations", "bucket": "image_generations", "remaining": 0, "limit": 100, "reset_at": "2025-02-01T00:00:00Z" } ``` ### Handling Quota Errors ```typescript try { const response = await aimagicx.images.generate({ prompt: "A sunset", }); } catch (error) { if (error.status === 402) { // Quota exceeded console.log(`Quota exceeded for ${error.bucket}`); console.log(`Resets at: ${error.reset_at}`); // Notify user or upgrade plan await notifyUser("quota_exceeded", error.bucket); } } ``` ## Top-ups Purchase additional quota without upgrading your plan: 1. Go to **Dashboard → Billing → Top-up** 2. Select a package or custom amount 3. Complete payment 4. Quota is added immediately ### Top-up Bundles | Bundle | Contents | Price | |--------|----------|-------| | **Creator Boost** | 200 credits + 100 images + 200 edits | ~$15 | | **Media Boost** | 10 min video + 30 min STT + 200K TTS | ~$17 | | **API Chat Pack (2.5K)** | 2,500 credits | $50 | | **API Chat Pack (10K)** | 10,000 credits | $200 | | **Video Pack (15 min)** | 15 min video generation | $15 | | **Video Pack (60 min)** | 60 min video generation | $60 | | **Music Pack (20)** | 20 music tracks | $10 | | **Music Pack (80)** | 80 music tracks | $40 | ### Per-Unit Pricing | Resource | Price | |----------|-------| | Credits | $0.02 per credit (1K tokens) | | Images | $0.10 per image | | Image edits | $0.05 per edit | | Video | $1.00 per minute | | STT | $0.50 per minute | | TTS | $0.05 per 1K characters | | Music | $0.50 per track | | Agent runs | $0.25 per run | Top-ups don't expire at the end of your billing period. They're used after your plan allowance is exhausted. ## Quota Reset - **Monthly plans**: Quotas reset on your billing date - **Annual plans**: Quotas reset monthly on your signup date - **Top-ups**: Never expire, used after plan allowance ## Monitoring & Alerts ### Low Credit Alerts AI Magicx sends notifications when credits are running low: | Alert | Trigger | |-------|---------| | Warning | 20% remaining | | Critical | 10% remaining | | Depleted | 0% remaining | Configure alerts in **Dashboard → Settings → Notifications**. ### Webhook Events Subscribe to billing webhooks for programmatic alerts: ```json // credits.low event { "type": "credits.low", "data": { "bucketType": "chat_tokens", "remaining": 100000, "limit": 1000000, "percentUsed": 90 } } ``` See [Webhooks Guide](/docs/guides/webhooks) for setup. ## Best Practices ### 1. Monitor Usage Regularly Check the dashboard weekly and set up alerts to avoid unexpected cutoffs. ### 2. Use Appropriate Models Don't use expensive models for simple tasks: | Task | Recommended Model | Why | |------|-------------------|-----| | Simple Q&A | GPT-4o Mini | Fast, cheap | | Complex reasoning | GPT-4o | Good balance | | Critical tasks | Claude 3 Opus | Best quality | ### 3. Implement Caching Cache responses to reduce redundant API calls: ```typescript const cache = new Map(); async function getCachedResponse(prompt: string) { const key = hashPrompt(prompt); if (cache.has(key)) { return cache.get(key); } const response = await aimagicx.chat.completions.create({ messages: [{ role: "user", content: prompt }], }); cache.set(key, response); return response; } ``` ### 4. Batch Operations Use async mode and batch parameters where available: ```typescript // Generate multiple images in one request const response = await aimagicx.images.generate({ prompt: "A sunset", n: 4, // Generate 4 images at once }); ``` ### 5. Set Client-Side Limits Prevent runaway usage with client-side limits: ```typescript const MAX_DAILY_REQUESTS = 1000; let dailyRequests = 0; async function makeRequest() { if (dailyRequests >= MAX_DAILY_REQUESTS) { throw new Error("Daily limit reached"); } dailyRequests++; // Make API call... } ``` ## Usage Analytics View detailed usage analytics in **Dashboard → Usage**: - **Usage by Model**: See which models consume the most credits - **Usage by Tool**: Breakdown by chat, image, video, etc. - **Daily Trends**: Usage patterns over time - **Top Users**: If using team features, see per-user breakdown ## FAQ ### Do unused credits roll over? Plan allowances reset each billing period. Only top-up credits carry over. ### What happens when I exceed my quota? API requests return `402 Payment Required`. Services continue working once you top up or the quota resets. ### Can I get a refund for unused credits? Plan credits are use-it-or-lose-it. Top-up credits are non-refundable but never expire. ### How are tokens counted? We use the same tokenization as OpenAI. Roughly 1 token = 4 characters or ~0.75 words. ### Do failed requests consume credits? No. Credits are only consumed for successful completions. Failed requests don't count against your quota. --- ## Document Chat URL: https://www.aimagicx.com/docs/guides/documents Description: Upload documents and chat with them using AI. Get answers with citations from PDFs, URLs, YouTube videos, and more. import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' import { Step, Steps } from 'fumadocs-ui/components/steps' # Document Chat Chat with your documents using AI. Upload PDFs, paste URLs, import YouTube videos, or paste text — then ask questions and get intelligent answers with citations. Document Chat is available on **Pro** and higher plans. Access it in **AI → Documents**. ## Overview Document Chat uses Retrieval-Augmented Generation (RAG) to provide accurate, grounded answers from your content. Every response includes citations linking back to the exact source passages. ### Supported Sources | Source Type | Description | Formats | |-------------|-------------|---------| | **File Upload** | Upload documents directly | PDF, DOCX, MD, TXT, CSV | | **URL Import** | Extract content from web pages | Any public URL | | **YouTube** | Import video transcripts | Any YouTube video with captions | | **Paste Text** | Paste content directly | Plain text, Markdown | ## Getting Started ### Add a Source Navigate to **AI → Documents** and click **Add Source**. Choose from: - **Upload File**: Drag & drop or select files - **URL**: Paste a web page URL - **YouTube**: Paste a YouTube video URL - **Paste Text**: Paste text content directly ### Wait for Processing Documents are automatically processed: 1. **Parsing**: Content is extracted from the source 2. **Chunking**: Content is split into semantic chunks 3. **Embedding**: Chunks are converted to vector embeddings 4. **Indexing**: Content is indexed for semantic search ### Start Chatting Click on any document to open the chat interface. Ask questions in natural language and get AI-powered answers with citations. ## Source Types ### File Upload Upload documents directly from your computer. Supported formats: | Format | Extension | Max Size | Notes | |--------|-----------|----------|-------| | PDF | `.pdf` | 10MB | Scanned PDFs not supported | | Word | `.docx` | 10MB | Modern Word format only | | Markdown | `.md` | 10MB | GitHub-flavored Markdown | | Text | `.txt` | 10MB | Plain text files | | CSV | `.csv` | 10MB | Tabular data | Scanned PDFs (image-based) are not currently supported. Documents must contain selectable text. ### URL Import Import content from any public web page: ```bash # Supported URLs https://example.com/article https://docs.example.com/guide https://blog.example.com/post ``` The system will: - Fetch the page content - Extract the main article/content - Remove navigation, ads, and boilerplate - Preserve headings, lists, and formatting Pages behind authentication or paywalls cannot be imported. The URL must be publicly accessible. ### YouTube Import Import YouTube video transcripts: ```bash # Supported URL formats https://www.youtube.com/watch?v=VIDEO_ID https://youtu.be/VIDEO_ID ``` Requirements: - Video must have captions (auto-generated or manual) - Videos without captions cannot be imported The system imports the full transcript with timestamps, allowing you to ask questions about any part of the video. ### Paste Text Paste any text content directly: - Meeting notes - Email threads - Code snippets - Research notes ## Chat Interface ### Asking Questions Ask questions in natural language: - "What are the key findings in this report?" - "Summarize the main arguments" - "What does it say about X?" - "Compare the approaches mentioned in section 2 and 3" ### Citations Every AI response includes numbered citations: ``` The report indicates revenue grew 35% year-over-year [1], driven primarily by enterprise expansion [2]. ``` Click any citation to: - View the original passage - See the page number or location - Navigate to that section in the document ### Chat Settings Customize chat behavior: | Setting | Options | Description | |---------|---------|-------------| | **Model** | GPT-4, Claude 3.5, etc. | AI model for responses | | **Temperature** | 0.0 - 1.0 | Response creativity | | **Response Length** | Concise, Balanced, Detailed | Output verbosity | | **Max Sources** | 1-10 | Number of chunks to retrieve | ## Collections Organize documents into collections for: - **Project Organization**: Group related documents - **Multi-Document Chat**: Chat across an entire collection - **Team Collaboration**: Share collections with team members ### Creating Collections 1. Click **New Collection** in the sidebar 2. Enter a name and optional description 3. Choose a color for visual organization 4. Click **Create** ### Moving Documents - Drag documents into collections - Use the document menu → **Move to Collection** - Documents can belong to one collection at a time ### Collection Chat Chat with all documents in a collection at once: 1. Select a collection in the sidebar 2. Click **Chat with Collection** 3. Ask questions that span multiple documents ## API Access Access Document Chat via the REST API. ### Upload Document ```bash curl -X POST https://api.aimagicx.com/v1/documents/upload \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "file=@document.pdf" \ -F "collection_id=optional-collection-id" ``` ### Import from URL ```bash curl -X POST https://api.aimagicx.com/v1/documents/import \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source_type": "url", "url": "https://example.com/article", "name": "Example Article" }' ``` ### Import YouTube ```bash curl -X POST https://api.aimagicx.com/v1/documents/import \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source_type": "youtube", "url": "https://www.youtube.com/watch?v=VIDEO_ID" }' ``` ### Chat with Document ```bash curl -X POST https://api.aimagicx.com/v1/documents/chat \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "document_ids": ["doc_123", "doc_456"], "message": "What are the key findings?", "model": "gpt-4o" }' ``` ### Response Format ```json { "content": "The key findings include...[1]...[2]", "citations": [ { "index": 1, "chunk_id": "chunk_abc", "document_id": "doc_123", "text": "Original passage...", "page": 5 } ], "usage": { "input_tokens": 1234, "output_tokens": 567 } } ``` ## Billing Document Chat uses credits from your **Chat Tokens** quota: | Operation | Credits | |-----------|---------| | Document embedding | ~1 credit per 1000 characters | | Chat query | Standard chat rates by model | Check your quota usage in **Dashboard → Usage**. ## Best Practices ### Document Preparation - **Clean formatting**: Remove unnecessary headers/footers - **Text-based PDFs**: Ensure PDFs contain selectable text - **Reasonable length**: Very long documents may have lower retrieval accuracy ### Effective Questions - Be specific: "What does section 3 say about pricing?" vs "Tell me about pricing" - Reference context: "Based on the Q4 report, what were the growth metrics?" - Ask follow-ups: Build on previous answers for deeper exploration ### Collection Strategy - Group by project or topic - Keep collections focused (5-20 documents) - Use descriptive names ## Troubleshooting ### Document Processing Failed | Error | Cause | Solution | |-------|-------|----------| | "Unsupported file type" | Wrong format | Use PDF, DOCX, MD, TXT, or CSV | | "File too large" | Exceeds 10MB | Split into smaller files | | "No text content" | Scanned PDF | Use text-based documents | | "Failed to fetch URL" | Inaccessible page | Check URL is public | | "No transcript available" | No YouTube captions | Use video with captions | ### Chat Issues | Issue | Solution | |-------|----------| | Irrelevant answers | Rephrase question, be more specific | | Missing citations | Increase "Max Sources" setting | | Slow responses | Reduce response length setting | ### Retry Failed Documents For URL and YouTube imports that failed: 1. Go to **AI → Documents** 2. Find the failed document 3. Click **Retry** to attempt processing again File uploads cannot be retried. You'll need to upload the file again. ## Limits | Limit | Free | Pro | Team | |-------|------|-----|------| | Documents | 5 | Unlimited | Unlimited | | File size | 10MB | 10MB | 10MB | | Collections | 1 | Unlimited | Unlimited | | API access | No | Yes | Yes | --- ## Error Handling URL: https://www.aimagicx.com/docs/guides/error-handling Description: Implement robust error handling for production applications import { Callout } from 'fumadocs-ui/components/callout' # Error Handling Proper error handling is crucial for building reliable applications with the AI Magicx API. ## Error Types | Status | Error | Action | |--------|-------|--------| | 400 | Bad Request | Fix request parameters | | 401 | Unauthorized | Check API key | | 402 | Payment Required | Upgrade plan or wait for reset | | 403 | Forbidden | Check API key scopes | | 429 | Rate Limited | Retry with backoff | | 500 | Server Error | Retry with backoff | ## Python Implementation ```python import requests import time from typing import Optional class AI MagicXError(Exception): """Base exception for AI Magicx API errors.""" def __init__(self, message: str, status_code: int, response: dict): super().__init__(message) self.status_code = status_code self.response = response class AuthenticationError(AI MagicXError): """API key is invalid or missing.""" pass class QuotaExceededError(AI MagicXError): """Account quota has been exceeded.""" pass class RateLimitError(AI MagicXError): """Rate limit has been exceeded.""" def __init__(self, message: str, status_code: int, response: dict): super().__init__(message, status_code, response) self.retry_after = response.get("retry_after", 60) class APIError(AI MagicXError): """General API error.""" pass def make_request( endpoint: str, data: dict, max_retries: int = 3, base_delay: float = 1.0 ) -> dict: """Make an API request with automatic retries.""" for attempt in range(max_retries): try: response = requests.post( f"{BASE_URL}/{endpoint}", headers=headers, json=data, timeout=30 ) if response.status_code == 200: return response.json() error_data = response.json() error_message = error_data.get("error", "Unknown error") if response.status_code == 401: raise AuthenticationError( error_message, response.status_code, error_data ) if response.status_code == 402: raise QuotaExceededError( error_message, response.status_code, error_data ) if response.status_code == 429: error = RateLimitError( error_message, response.status_code, error_data ) if attempt < max_retries - 1: time.sleep(error.retry_after) continue raise error if response.status_code >= 500: if attempt < max_retries - 1: delay = base_delay * (2 ** attempt) time.sleep(delay) continue raise APIError( error_message, response.status_code, error_data ) raise APIError( error_message, response.status_code, error_data ) except requests.exceptions.Timeout: if attempt < max_retries - 1: time.sleep(base_delay * (2 ** attempt)) continue raise except requests.exceptions.ConnectionError: if attempt < max_retries - 1: time.sleep(base_delay * (2 ** attempt)) continue raise raise APIError("Max retries exceeded", 0, {}) # Usage try: result = make_request( "chat/completions", {"messages": [{"role": "user", "content": "Hello"}]} ) print(result["choices"][0]["message"]["content"]) except AuthenticationError as e: print(f"Auth failed: {e}. Check your API key.") except QuotaExceededError as e: print(f"Quota exceeded: {e}. Upgrade your plan.") except RateLimitError as e: print(f"Rate limited. Retry after {e.retry_after}s") except APIError as e: print(f"API error ({e.status_code}): {e}") ``` ## TypeScript Implementation ```typescript class AI MagicXError extends Error { constructor( message: string, public statusCode: number, public response: Record ) { super(message); this.name = "AI MagicXError"; } } class RateLimitError extends AI MagicXError { retryAfter: number; constructor( message: string, statusCode: number, response: Record ) { super(message, statusCode, response); this.name = "RateLimitError"; this.retryAfter = response.retry_after ?? 60; } } async function makeRequest( endpoint: string, data: object, maxRetries = 3 ): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await fetch(`${BASE_URL}/${endpoint}`, { method: "POST", headers, body: JSON.stringify(data), }); if (response.ok) { return response.json(); } const errorData = await response.json(); if (response.status === 429) { const error = new RateLimitError( errorData.error, response.status, errorData ); if (attempt < maxRetries - 1) { await sleep(error.retryAfter * 1000); continue; } throw error; } if (response.status >= 500 && attempt < maxRetries - 1) { await sleep(1000 * Math.pow(2, attempt)); continue; } throw new AI MagicXError( errorData.error, response.status, errorData ); } catch (error) { if (error instanceof AI MagicXError) throw error; if (attempt < maxRetries - 1) { await sleep(1000 * Math.pow(2, attempt)); continue; } throw error; } } } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); ``` ## Best Practices 1. **Always implement retries** for 429 and 5xx errors 2. **Use exponential backoff** to avoid thundering herd 3. **Set timeouts** to prevent hanging requests 4. **Log errors** for debugging and monitoring 5. **Show user-friendly messages** in your UI --- ## Incoming Webhooks URL: https://www.aimagicx.com/docs/guides/incoming-webhooks Description: Trigger AI Magicx actions from external services using custom webhook URLs import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Incoming Webhooks Incoming webhooks allow external services to trigger actions in your AI Magicx account. Create a unique URL that other services can POST to, triggering AI agents, generations, or custom workflows. Incoming webhooks are available on **Pro** and higher plans. See [plan limits](/docs/rate-limits#usage-quotas) for webhook quotas. ## Use Cases - **Zapier/Make/n8n Integration**: Trigger AI Magicx from any automation platform - **CI/CD Pipelines**: Generate release notes or summaries automatically - **Form Submissions**: Process form data with AI agents - **Slack/Discord Commands**: Trigger generations from chat platforms - **IoT Devices**: Trigger actions from sensors or hardware - **CRM Events**: Generate content when deals close or contacts are updated ## How It Works 1. Create an incoming webhook in Dashboard → Settings → Integrations → Incoming 2. Configure the action (run agent, generate content, send notification) 3. Get your unique webhook URL and secret token 4. Send POST requests to trigger the action ## Creating an Incoming Webhook ### Via Dashboard 1. Go to **Dashboard → Settings → Integrations → Incoming Webhooks** 2. Click **Create Webhook** 3. Enter a name and unique slug (e.g., `generate-summary`) 4. Select the action type 5. Configure action-specific settings 6. Copy the URL and secret token (shown only once!) ### Webhook URL Format ``` https://www.aimagicx.com/api/webhooks/incoming/{slug} ``` Example: `https://www.aimagicx.com/api/webhooks/incoming/generate-summary` ## Action Types ### 1. Run Agent (`run_agent`) Trigger an AI agent with dynamic input. **Configuration:** ```json { "actionType": "run_agent", "actionConfig": { "agentId": "agent_abc123", "inputField": "message" } } ``` **Request:** ```bash curl -X POST https://www.aimagicx.com/api/webhooks/incoming/my-agent \ -H "Authorization: Bearer whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{ "message": "Summarize this customer feedback: Great product!" }' ``` **Response:** ```json { "success": true, "runId": "run_xyz789", "status": "started", "message": "Agent run started" } ``` ### 2. Trigger Generation (`trigger_generation`) Start an image, video, or other generation job. **Configuration:** ```json { "actionType": "trigger_generation", "actionConfig": { "tool": "image", "model": "fal-ai/flux/dev", "promptField": "prompt", "defaults": { "size": "1024x1024" } } } ``` **Request:** ```bash curl -X POST https://www.aimagicx.com/api/webhooks/incoming/generate-image \ -H "Authorization: Bearer whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A sunset over mountains" }' ``` **Response:** ```json { "success": true, "jobId": "job_abc123", "status": "pending", "message": "Generation started" } ``` ### 3. Send Notification (`send_notification`) Send a notification to configured channels (email, Slack, Discord). **Configuration:** ```json { "actionType": "send_notification", "actionConfig": { "channels": ["slack", "email"], "titleField": "subject", "messageField": "body" } } ``` **Request:** ```bash curl -X POST https://www.aimagicx.com/api/webhooks/incoming/notify-team \ -H "Authorization: Bearer whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{ "subject": "New Lead", "body": "John Doe just signed up for a demo" }' ``` ### 4. Custom Action (`custom`) Execute a custom workflow or chain of actions. **Configuration:** ```json { "actionType": "custom", "actionConfig": { "workflow": "process-feedback", "mappings": { "input": "$.feedback", "metadata": "$.user" } } } ``` ## Authentication All incoming webhook requests require authentication via the secret token. ### Bearer Token (Recommended) ```bash curl -X POST https://www.aimagicx.com/api/webhooks/incoming/my-webhook \ -H "Authorization: Bearer whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{"message": "Hello"}' ``` ### Header Token ```bash curl -X POST https://www.aimagicx.com/api/webhooks/incoming/my-webhook \ -H "X-Webhook-Token: whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{"message": "Hello"}' ``` ### Query Parameter (Not Recommended) ```bash curl -X POST "https://www.aimagicx.com/api/webhooks/incoming/my-webhook?token=whsec_your_secret_token" \ -H "Content-Type: application/json" \ -d '{"message": "Hello"}' ``` **Security:** Store your webhook secret securely. If compromised, regenerate it immediately in the dashboard. ## Rate Limiting Each incoming webhook has its own rate limit to prevent abuse. ### Limits by Plan | Plan | Default Rate | Max Rate | |------|--------------|----------| | Free | 30/min | 30/min | | Pro | 60/min | 120/min | | Business | 120/min | 300/min | | CLI Team | 120/min | 300/min | ### Rate Limit Headers Responses include rate limit information: ```http X-RateLimit-Limit: 60 X-RateLimit-Remaining: 45 X-RateLimit-Reset: 1703123456 ``` ### Rate Limited Response ```json { "error": "Rate limit exceeded", "retryAfter": 30, "limit": 60, "remaining": 0 } ``` **Status:** `429 Too Many Requests` ## Error Responses | Status | Error | Description | |--------|-------|-------------| | 400 | `invalid_request` | Missing or invalid request body | | 401 | `unauthorized` | Missing or invalid token | | 403 | `forbidden` | Webhook disabled or feature not available | | 404 | `not_found` | Webhook slug doesn't exist | | 429 | `rate_limited` | Too many requests | | 500 | `internal_error` | Server error (retry safe) | ```json { "error": "unauthorized", "message": "Invalid or missing webhook token" } ``` ## Request Logging All incoming webhook requests are logged for debugging. View logs in: **Dashboard → Settings → Integrations → Incoming Webhooks → [Webhook] → Logs** Logs include: - Request timestamp - Request headers (sensitive data redacted) - Request body - Response status - Action result - Duration Logs are retained for 7 days on Pro plans and 30 days on Business plans. ## Integration Examples ### Zapier 1. Create a new Zap 2. Add a trigger (e.g., "New Row in Google Sheets") 3. Add a **Webhooks by Zapier** action 4. Select **POST** 5. Enter your AI Magicx webhook URL 6. Add header: `Authorization: Bearer whsec_your_token` 7. Map data fields to your webhook's expected format ### Make (Integromat) 1. Create a new scenario 2. Add a trigger module 3. Add an **HTTP > Make a request** module 4. Configure: - URL: Your webhook URL - Method: POST - Headers: `Authorization: Bearer whsec_your_token` - Body type: JSON - Request content: Your payload ### n8n ```json { "nodes": [ { "parameters": { "url": "https://www.aimagicx.com/api/webhooks/incoming/your-webhook", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "options": { "bodyContentType": "json" } }, "name": "HTTP Request", "type": "n8n-nodes-base.httpRequest", "position": [450, 300] } ] } ``` ### GitHub Actions ```yaml - name: Trigger AI Magicx run: | curl -X POST https://www.aimagicx.com/api/webhooks/incoming/release-notes \ -H "Authorization: Bearer ${{ secrets.AI_MAGICX_WEBHOOK_TOKEN }}" \ -H "Content-Type: application/json" \ -d '{ "version": "${{ github.ref_name }}", "changes": "${{ github.event.release.body }}" }' ``` ### Slack Slash Command 1. Create a Slack App 2. Add a Slash Command (e.g., `/generate`) 3. Set Request URL to your AI Magicx webhook 4. In your webhook config, map Slack's `text` field to your prompt ## Managing Webhooks ### Regenerate Secret If your secret is compromised: 1. Go to **Dashboard → Incoming Webhooks** 2. Click on the webhook 3. Click **Regenerate Secret** 4. Update the token in all integrations ### Enable/Disable Temporarily disable a webhook without deleting it: ```bash # Via dashboard or API PATCH /api/v1/incoming-webhooks/{id} { "enabled": false } ``` ### Delete Permanently remove a webhook: 1. Go to **Dashboard → Incoming Webhooks** 2. Click on the webhook 3. Click **Delete** 4. Confirm deletion Deleting a webhook is permanent. Any services using that URL will receive 404 errors. ## Best Practices ### 1. Use Descriptive Slugs Choose slugs that describe the action: - ✅ `generate-product-image` - ✅ `process-customer-feedback` - ❌ `webhook1` - ❌ `test` ### 2. Set Appropriate Rate Limits Start with lower limits and increase as needed. This prevents runaway automation from exhausting your quota. ### 3. Monitor Usage Check the dashboard regularly for: - Error rates - Usage patterns - Unexpected activity ### 4. Validate Input Use the `inputField` and `promptField` configs to specify which fields to use, preventing injection of unexpected data. ### 5. Test Before Production Use the "Test" feature in the dashboard to verify your webhook works before connecting production systems. --- ## Guides URL: https://www.aimagicx.com/docs/guides Description: Learn how to use AI Magicx effectively with these practical guides import { Card, Cards } from 'fumadocs-ui/components/card' # Guides Practical guides to help you get the most out of the AI Magicx API. ## Core Concepts ## Webhooks & Integrations --- ## Integrations URL: https://www.aimagicx.com/docs/guides/integrations Description: Connect AI Magicx to Slack, Discord, Zapier, Make, n8n, and other platforms import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Integrations AI Magicx integrates with popular platforms to send notifications, trigger automations, and connect your AI workflows to thousands of apps. Integrations are available on **Pro** and higher plans. Access them in **Dashboard → Settings → Integrations**. ## Available Integrations | Platform | Auth Type | Features | |----------|-----------|----------| | **Slack** | OAuth | Real-time notifications, custom channels, rich formatting | | **Discord** | Webhook | Webhook notifications, rich embeds, custom bot name | | **Zapier** | Webhook | Trigger Zaps, connect to 5,000+ apps | | **Make** | Webhook | Complex workflows, data transformation | | **n8n** | Webhook | Self-hosted automation, open source | ## Slack Integration Connect Slack to receive real-time notifications when events occur in AI Magicx. ### Setup 1. Go to **Dashboard → Settings → Integrations → Connectors** 2. Click **Connect Slack** 3. Authorize AI Magicx to access your Slack workspace 4. Select a default channel for notifications 5. Choose which events to notify on ### Features - **Real-time Notifications**: Get instant updates on generations, agent runs, and more - **Channel Selection**: Choose which channel receives notifications - **Rich Formatting**: Messages include formatted content, links, and metadata - **Event Filtering**: Only receive notifications for events you care about ### Notification Events Select which events trigger Slack notifications: - Generation completed/failed - Agent run completed/failed - Credits low/depleted - Team member changes - Subscription updates ### Example Notification ``` 🎨 Image Generated Successfully Model: fal-ai/flux/dev Prompt: "A sunset over mountains" Duration: 3.2s Credits: 5 [View Image] [Open Dashboard] ``` ## Discord Integration Send notifications to Discord channels using webhooks. ### Setup 1. In Discord, go to **Server Settings → Integrations → Webhooks** 2. Click **New Webhook** 3. Copy the webhook URL 4. In AI Magicx, go to **Settings → Integrations → Connectors** 5. Click **Connect Discord** 6. Paste your webhook URL 7. Configure the bot name and avatar (optional) ### Configuration Options ```json { "webhookUrl": "https://discord.com/api/webhooks/...", "username": "AI Magicx Bot", "avatarUrl": "https://www.aimagicx.com/logo.png", "notifyOnEvents": [ "generation.completed", "credits.low" ] } ``` ### Features - **Rich Embeds**: Notifications include images, colors, and formatted content - **Custom Bot Name**: Set a custom name for the webhook messages - **Custom Avatar**: Use your own avatar image - **Event Filtering**: Choose which events to notify on ## Zapier Integration Connect to 5,000+ apps through Zapier automations. ### Setup 1. In Zapier, create a new Zap 2. Choose **Webhooks by Zapier** as the trigger 3. Select **Catch Hook** 4. Copy the webhook URL 5. In AI Magicx, go to **Settings → Integrations → Connectors** 6. Click **Connect Zapier** 7. Paste your webhook URL 8. Select which events trigger the Zap ### Use Cases - **Google Sheets**: Log all generations to a spreadsheet - **Notion**: Create pages for completed agent runs - **Email**: Send email notifications for important events - **Trello**: Create cards when tasks are generated - **Airtable**: Build a database of AI-generated content ### Example Zap: Log Images to Google Sheets **Trigger**: AI Magicx → generation.completed (image) **Action**: Google Sheets → Create Row | Column | Value | |--------|-------| | Timestamp | `{{timestamp}}` | | Prompt | `{{data.prompt}}` | | Model | `{{data.model}}` | | Image URL | `{{data.outputUrl}}` | | Credits | `{{data.unitsUsed}}` | ## Make Integration Build powerful automations with Make (formerly Integromat). ### Setup 1. In Make, create a new Scenario 2. Add a **Webhooks > Custom webhook** module 3. Click **Add** to create a new webhook 4. Copy the webhook URL 5. In AI Magicx, connect Make with the webhook URL 6. Select your events ### Use Cases - **Multi-step workflows**: Chain multiple actions - **Data transformation**: Process and format webhook data - **Conditional logic**: Different actions based on event type - **Error handling**: Retry failed operations ### Example Scenario ``` [Webhook Trigger] ↓ [Router] ├── generation.completed → [Google Drive: Upload] ├── agent.run.completed → [Slack: Send Message] └── credits.low → [Email: Send Alert] ``` ## n8n Integration Self-hosted workflow automation for maximum control. ### Setup 1. In n8n, create a new Workflow 2. Add a **Webhook** node 3. Configure the webhook settings 4. Copy the Production URL 5. In AI Magicx, connect n8n with the webhook URL ### Configuration ```json { "webhookUrl": "https://your-n8n.example.com/webhook/aimagicx", "notifyOnEvents": [ "generation.completed", "agent.run.completed" ] } ``` ### Features - **Self-hosted**: Keep data on your own infrastructure - **Open source**: Full control and customization - **No limits**: No execution limits like SaaS alternatives - **Custom nodes**: Build your own integrations ## Event Payloads All integrations receive standardized event payloads: ```json { "id": "evt_abc123", "type": "generation.completed", "timestamp": "2025-01-15T10:30:00Z", "orgId": "org_xyz789", "data": { // Event-specific data } } ``` See [Webhooks Documentation](/docs/guides/webhooks#webhook-events) for detailed event payloads. ## Managing Integrations ### Enable/Disable Toggle integrations without removing them: 1. Go to **Settings → Integrations → Connectors** 2. Click on the integration 3. Toggle the **Enabled** switch ### Update Events Change which events trigger notifications: 1. Click on the connected integration 2. Check/uncheck events in the Events section 3. Click **Save Changes** ### Disconnect Remove an integration completely: 1. Click on the connected integration 2. Click **Disconnect** 3. Confirm the action Disconnecting removes all configuration. You'll need to re-authorize for OAuth integrations. ## API Access Manage integrations programmatically via the API: ### List Integrations ```bash curl https://www.aimagicx.com/api/v1/integrations \ -H "Authorization: Bearer sk_your_api_key" ``` ### Create Integration ```bash curl -X POST https://www.aimagicx.com/api/v1/integrations \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "provider": "discord", "credentials": { "webhookUrl": "https://discord.com/api/webhooks/..." }, "config": { "username": "AI Magicx Bot", "notifyOnEvents": ["generation.completed"] } }' ``` ### Update Integration ```bash curl -X PATCH https://www.aimagicx.com/api/v1/integrations/{id} \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "config": { "notifyOnEvents": ["generation.completed", "credits.low"] } }' ``` ### Delete Integration ```bash curl -X DELETE https://www.aimagicx.com/api/v1/integrations/{id} \ -H "Authorization: Bearer sk_your_api_key" ``` ## Best Practices ### 1. Filter Events Only subscribe to events you need. Too many notifications lead to alert fatigue. ### 2. Use Dedicated Channels Create a dedicated Slack/Discord channel for AI Magicx notifications to avoid noise in main channels. ### 3. Test Before Production Use the "Test" feature to verify your integration works before relying on it. ### 4. Monitor Delivery Check the delivery logs for failed notifications and fix issues promptly. ### 5. Secure Webhook URLs Treat webhook URLs as secrets. Regenerate them if compromised. ## Limits by Plan | Feature | Pro | Business | |---------|-----|----------| | Integrations | 3 | 10 | | Events per integration | All | All | | Custom config | ✓ | ✓ | | Delivery logs | 7 days | 30 days | ## Troubleshooting ### Notifications Not Arriving 1. Check the integration is **enabled** 2. Verify the webhook URL is correct 3. Check delivery logs for errors 4. Ensure the event type is selected ### Slack OAuth Failed 1. Ensure you have permission to install apps 2. Try logging out and back in to Slack 3. Contact your Slack admin if workspace restrictions apply ### Discord Webhook Invalid 1. Verify the webhook still exists in Discord 2. Check the webhook URL format is correct 3. Regenerate the webhook in Discord and update AI Magicx ### Rate Limits Integration webhooks are subject to the target platform's rate limits. If you're hitting limits: - Reduce the number of events - Use filtering to only send important events - Consider batching notifications --- ## Sharing & Collaboration URL: https://www.aimagicx.com/docs/guides/sharing Description: Share conversations, agents, and runs with your team or via public links import { Callout } from 'fumadocs-ui/components/callout' AI Magicx allows you to share your AI work with team members or publicly. Share conversations, custom agents, and agent runs with three visibility levels. **Team Plan Required** — Sharing with team members or via public links requires an active Team plan. Free and Pro users can only use Private visibility. [Upgrade to Team →](/pricing) ## Visibility Levels ### Private (Default) - Only you can access - Default for all new resources - Full control over your work - **Available on all plans** ### Team - All organization members can view - Members can fork to their own account - Great for internal knowledge sharing - **Requires Team plan** ### Public Link - Anyone with the link can view - Visitors can fork to their account - Perfect for showcasing work or sharing with clients - **Requires Team plan** ## Shareable Resources ### Conversations Share entire chat threads with full message history: - All messages preserved - Markdown rendering - Code syntax highlighting ### AI Agents Share custom agent configurations: - System prompt - Model settings - Tool selections - Sample prompts ### Agent Runs Share specific execution results: - Step-by-step timeline - Tool inputs and outputs - Token usage and timing ## How to Share ### From the UI 1. **Open the resource** you want to share (conversation, agent, or run) 2. **Click the Share button** (or select Share from the menu) 3. **Choose visibility level**: - Private: Only you - Team: All org members - Public: Anyone with link 4. **Copy the share link** (for Public visibility) 5. **Click Save Changes** ### Share Dialog Options ``` ┌─────────────────────────────────────┐ │ Share Conversation │ ├─────────────────────────────────────┤ │ Visibility │ │ ○ Private - Only you │ │ ○ Team - All team members │ │ ● Public Link - Anyone with link │ ├─────────────────────────────────────┤ │ ⚠️ Public visibility │ │ Anyone with the link can view │ │ and fork this resource. │ ├─────────────────────────────────────┤ │ Share link │ │ [https://www.aimagicx.com/sha...] [Copy] │ ├─────────────────────────────────────┤ │ [Cancel] [Save] │ └─────────────────────────────────────┘ ``` ## Forking When viewing a shared resource, you can **fork** it to your own account: 1. Visit the shared link 2. Click **"Fork to my account"** 3. Sign in if needed 4. The resource is copied to your account ### Fork Behavior - Forked copies are **completely independent** - Changes don't affect the original - Forked resources start as **Private** - You have full edit access ## Team Sharing Team members see shared resources in dedicated sections: ### Conversations - **Shared** tab in the chat sidebar - Click to view the shared conversation - Fork to continue in your own thread ### Agents - **Shared** tab on the agents page - View agent configuration - Fork to customize and run ## API Access ### Update Visibility ```bash POST /api/v1/share Content-Type: application/json Authorization: Bearer YOUR_API_KEY { "resourceType": "conversation", "resourceId": "conv_abc123", "visibility": "public" } ``` **Response:** ```json { "visibility": "public", "shareToken": "abc123xyz789...", "shareUrl": "https://www.aimagicx.com/shared/conversation/abc123xyz789..." } ``` ### Get Shared Resource (Public) ```bash GET /api/v1/share/{token}?type=conversation ``` **Response:** ```json { "resourceType": "conversation", "resource": { "id": "conv_abc123", "title": "AI Research Discussion", "messages": [...] } } ``` ### Fork a Shared Resource ```bash POST /api/v1/fork Content-Type: application/json Authorization: Bearer YOUR_API_KEY { "resourceType": "conversation", "shareToken": "abc123xyz789..." } ``` **Response:** ```json { "conversation": { "id": "conv_xyz789", "title": "AI Research Discussion (Copy)", "visibility": "private" } } ``` ## Security ### Share Tokens - 128-bit entropy (22 characters) - Cryptographically secure - Impossible to guess ### Team Verification - Team shares verify org membership - Access denied if not in same org - RLS policies enforce access ### Instant Revoke - Set to Private to revoke all access - Share links immediately stop working - Team members lose access ## Best Practices ### For Team Sharing - Use Team visibility for internal templates - Share successful agent configurations - Build a library of useful conversations ### For Public Sharing - Review content before making public - Remove any sensitive information - Use for portfolios and demos ### For Security - Regularly review shared resources - Revoke access when no longer needed - Use Team over Public when possible ## Troubleshooting ### "Sharing requires a Team plan" - Team and Public visibility require an active Team plan - Upgrade at [aimagicx.com/pricing](/pricing) - Private visibility is available on all plans ### "Conversation not found" - The share link may have been revoked - You may need to be logged in for team shares - Try forking instead of viewing directly ### "Please log in to fork" - Fork requires authentication - Sign in to your AI Magicx account - Then retry the fork ### Share link not generating - Save changes after selecting Public - Token generates on first save to Public - Try refreshing and saving again --- ## Streaming Responses URL: https://www.aimagicx.com/docs/guides/streaming Description: Handle streaming responses for real-time chat output import { Tab, Tabs } from 'fumadocs-ui/components/tabs' # Streaming Responses Streaming allows you to receive chat responses token-by-token as they're generated, providing a better user experience for real-time applications. ## Basic Streaming ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) stream = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Tell me a story"}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) ``` ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk_your_api_key", baseURL: "https://www.aimagicx.com/api/v1", }); const stream = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Tell me a story" }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ""; process.stdout.write(content); } ``` ```bash curl -N https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "messages": [{"role": "user", "content": "Tell me a story"}], "stream": true }' ``` ## React/Next.js Integration Using the Vercel AI SDK: ```typescript // app/api/chat/route.ts import { streamText } from "ai"; import { createOpenAI } from "@ai-sdk/openai"; const aimagicx = createOpenAI({ apiKey: process.env.AI_MAGICX_API_KEY, baseURL: "https://www.aimagicx.com/api/v1", }); export async function POST(req: Request) { const { messages } = await req.json(); const result = await streamText({ model: aimagicx("openai/gpt-4o-mini"), messages, }); return result.toDataStreamResponse(); } ``` ```tsx // components/chat.tsx "use client"; import { useChat } from "ai/react"; export function Chat() { const { messages, input, handleInputChange, handleSubmit } = useChat(); return (
{messages.map((m) => (
{m.role}: {m.content}
))}
); } ``` ## SSE Event Format The stream consists of Server-Sent Events (SSE): ``` data: {"id":"chatcmpl-123","choices":[{"delta":{"content":"Hello"}}]} data: {"id":"chatcmpl-123","choices":[{"delta":{"content":" there"}}]} data: {"id":"chatcmpl-123","choices":[{"delta":{"content":"!"}}]} data: [DONE] ``` ## Handling Stream Completion ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) full_response = "" stream = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Write a haiku"}], stream=True ) for chunk in stream: content = chunk.choices[0].delta.content or "" full_response += content print(content, end="", flush=True) print(f"\n\nFull response: {full_response}") ``` --- ## Webhooks URL: https://www.aimagicx.com/docs/guides/webhooks Description: Receive real-time notifications when events occur in your AI Magicx account import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Webhooks Webhooks allow you to receive real-time HTTP notifications when events occur in your AI Magicx account. Instead of polling for changes, webhooks push data to your server automatically. Webhooks are available on **Pro** and higher plans. Check your [plan limits](/docs/rate-limits#usage-quotas) for webhook quotas. ## How Webhooks Work 1. You create a webhook endpoint in your application 2. You register that URL in AI Magicx Dashboard → Settings → Webhooks 3. When an event occurs, AI Magicx sends a POST request to your URL 4. Your server processes the event and returns a 2xx response ## Webhook Events ### AI Agents | Event | Description | |-------|-------------| | `agent.run.started` | An agent run has started | | `agent.run.completed` | An agent run completed successfully | | `agent.run.failed` | An agent run failed with an error | ### Generations | Event | Description | |-------|-------------| | `generation.started` | A generation job started (image, video, music, etc.) | | `generation.completed` | A generation job completed | | `generation.failed` | A generation job failed | ### Chat | Event | Description | |-------|-------------| | `chat.message.created` | A new chat message was created | | `chat.conversation.created` | A new conversation was started | ### Billing | Event | Description | |-------|-------------| | `subscription.created` | A new subscription was created | | `subscription.updated` | Subscription plan was changed | | `subscription.cancelled` | Subscription was cancelled | | `credits.low` | Credits are below 10% remaining | | `credits.depleted` | Credits are fully exhausted | ### Team | Event | Description | |-------|-------------| | `team.member.added` | A team member was added | | `team.member.removed` | A team member was removed | | `team.member.role_changed` | A team member's role was changed | ## Webhook Payload All webhook payloads follow this structure: ```json { "id": "evt_abc123xyz", "type": "generation.completed", "timestamp": "2025-01-15T10:30:00Z", "data": { "jobId": "job_abc123", "tool": "image", "model": "fal-ai/flux/dev", "outputUrl": "https://fal.media/files/...", "durationMs": 3200, "unitsUsed": 1, "unitType": "image_generations" }, "orgId": "org_xyz789" } ``` ### Event-Specific Payloads **agent.run.started** ```json { "runId": "run_abc123", "agentId": "agent_xyz", "agentName": "Customer Support Bot", "input": "Help me reset my password" } ``` **agent.run.completed** ```json { "runId": "run_abc123", "agentId": "agent_xyz", "agentName": "Customer Support Bot", "input": "Help me reset my password", "output": "I can help you reset your password...", "totalSteps": 3, "durationMs": 4500, "unitsUsed": 1, "unitType": "agent_runs" } ``` **agent.run.failed** ```json { "runId": "run_abc123", "agentId": "agent_xyz", "agentName": "Customer Support Bot", "input": "Help me reset my password", "errorMessage": "Rate limit exceeded" } ``` **generation.started** ```json { "jobId": "job_abc123", "tool": "video", "model": "fal-ai/minimax/video-01" } ``` **generation.completed** ```json { "jobId": "job_abc123", "tool": "video", "model": "fal-ai/minimax/video-01", "outputUrl": "https://fal.media/files/video.mp4", "durationMs": 45000, "unitsUsed": 5, "unitType": "video_seconds" } ``` **generation.failed** ```json { "jobId": "job_abc123", "tool": "video", "model": "fal-ai/minimax/video-01", "errorMessage": "Content policy violation" } ``` **credits.low** ```json { "bucketType": "chat_tokens", "remaining": 8500, "limit": 100000, "percentUsed": 91.5 } ``` **subscription.updated** ```json { "subscriptionId": "sub_abc123", "planCode": "pro_monthly", "planName": "Pro Monthly", "status": "active" } ``` ## Security ### Signature Verification All webhook requests are signed using HMAC-SHA256. Always verify the signature to ensure requests are from AI Magicx. **Signature Headers:** | Header | Description | |--------|-------------| | `x-aimagicx-signature` | HMAC-SHA256 signature | | `x-aimagicx-timestamp` | Unix timestamp of request | | `x-aimagicx-event-id` | Unique event ID (for deduplication) | | `x-aimagicx-event-type` | Event type (e.g., `generation.completed`) | ### Verifying Signatures ```typescript import crypto from 'crypto'; function verifyWebhookSignature( payload: string, signature: string, timestamp: string, secret: string ): boolean { const signedPayload = `${timestamp}:${payload}`; const expectedSignature = crypto .createHmac('sha256', secret) .update(signedPayload) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expectedSignature) ); } // Express.js example app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.headers['x-aimagicx-signature'] as string; const timestamp = req.headers['x-aimagicx-timestamp'] as string; const payload = req.body.toString(); if (!verifyWebhookSignature(payload, signature, timestamp, WEBHOOK_SECRET)) { return res.status(401).json({ error: 'Invalid signature' }); } const event = JSON.parse(payload); // Process event... res.status(200).json({ received: true }); }); ``` ```python import hmac import hashlib from flask import Flask, request, jsonify def verify_webhook_signature(payload: bytes, signature: str, timestamp: str, secret: str) -> bool: signed_payload = f"{timestamp}:{payload.decode()}" expected = hmac.new( secret.encode(), signed_payload.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): signature = request.headers.get('x-aimagicx-signature') timestamp = request.headers.get('x-aimagicx-timestamp') payload = request.get_data() if not verify_webhook_signature(payload, signature, timestamp, WEBHOOK_SECRET): return jsonify({'error': 'Invalid signature'}), 401 event = request.get_json() # Process event... return jsonify({'received': True}), 200 ``` ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "net/http" ) func verifySignature(payload, signature, timestamp, secret string) bool { signedPayload := fmt.Sprintf("%s:%s", timestamp, payload) mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(signedPayload)) expected := hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(signature), []byte(expected)) } func webhookHandler(w http.ResponseWriter, r *http.Request) { signature := r.Header.Get("x-aimagicx-signature") timestamp := r.Header.Get("x-aimagicx-timestamp") payload, _ := io.ReadAll(r.Body) if !verifySignature(string(payload), signature, timestamp, webhookSecret) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } // Process event... w.WriteHeader(http.StatusOK) } ``` ### Timestamp Validation Reject requests with timestamps older than 5 minutes to prevent replay attacks: ```typescript const timestamp = parseInt(headers['x-aimagicx-timestamp']); const now = Math.floor(Date.now() / 1000); const FIVE_MINUTES = 300; if (Math.abs(now - timestamp) > FIVE_MINUTES) { return res.status(401).json({ error: 'Request too old' }); } ``` ## Retry Policy If your endpoint doesn't return a 2xx status code, AI Magicx will retry the webhook: | Attempt | Delay | |---------|-------| | 1 | Immediate | | 2 | 30 seconds | | 3 | 2 minutes | | 4 | 10 minutes | | 5 | 1 hour | After 5 failed attempts, the webhook delivery is marked as failed. **Auto-Disable:** If a webhook fails consistently (10+ consecutive failures), it will be automatically disabled. Re-enable it in the dashboard after fixing your endpoint. ## Event Deduplication Use the `x-aimagicx-event-id` header to deduplicate events. Store processed event IDs and skip duplicates: ```typescript const eventId = req.headers['x-aimagicx-event-id']; // Check if already processed const alreadyProcessed = await redis.get(`webhook:${eventId}`); if (alreadyProcessed) { return res.status(200).json({ received: true, duplicate: true }); } // Process event await processEvent(event); // Mark as processed (expire after 24 hours) await redis.set(`webhook:${eventId}`, '1', 'EX', 86400); ``` ## Creating Webhooks ### Via Dashboard 1. Go to **Dashboard → Settings → Integrations → Webhooks** 2. Click **Create Webhook** 3. Enter your endpoint URL (must be HTTPS) 4. Select the events you want to receive 5. Optionally add custom headers 6. Copy the signing secret and store it securely ### Via API ```bash curl -X POST https://www.aimagicx.com/api/v1/webhooks \ -H "Authorization: Bearer sk_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "name": "Production Webhook", "url": "https://api.yourapp.com/aimagicx-webhook", "events": ["generation.completed", "generation.failed"], "enabled": true }' ``` ## Best Practices ### 1. Respond Quickly Return a 200 response immediately and process asynchronously: ```typescript app.post('/webhook', async (req, res) => { // Verify signature first if (!verifySignature(req)) { return res.status(401).send(); } // Respond immediately res.status(200).json({ received: true }); // Process asynchronously await queue.add('process-webhook', req.body); }); ``` ### 2. Use Idempotent Processing Handle the same event being delivered multiple times gracefully. ### 3. Log Everything Keep detailed logs of webhook deliveries for debugging: ```typescript console.log({ eventId: req.headers['x-aimagicx-event-id'], eventType: req.headers['x-aimagicx-event-type'], timestamp: new Date().toISOString(), payload: req.body }); ``` ### 4. Monitor Failures Set up alerts for webhook failures in your monitoring system. ### 5. Use HTTPS Always use HTTPS endpoints. HTTP endpoints are not supported. ## Testing Webhooks ### Using the Dashboard 1. Go to your webhook settings 2. Click **Send Test Event** 3. Select an event type 4. Review the request/response in the delivery logs ### Using cURL Test your endpoint locally with a sample payload: ```bash curl -X POST http://localhost:3000/webhook \ -H "Content-Type: application/json" \ -H "x-aimagicx-signature: test" \ -H "x-aimagicx-timestamp: $(date +%s)" \ -H "x-aimagicx-event-id: test_123" \ -H "x-aimagicx-event-type: generation.completed" \ -d '{ "id": "evt_test123", "type": "generation.completed", "timestamp": "2025-01-15T10:30:00Z", "data": { "jobId": "job_abc123", "tool": "image", "model": "fal-ai/flux/dev" } }' ``` ## Webhook Limits by Plan | Plan | Max Webhooks | Events | Custom Headers | |------|--------------|--------|----------------| | Free | 0 | - | - | | Pro | 5 | All | Yes | | Business | 20 | All | Yes | | CLI Team | 20 | All | Yes | --- ## SDKs & Libraries URL: https://www.aimagicx.com/docs/sdks Description: Official and community SDKs for the AI Magicx API import { Card, Cards } from 'fumadocs-ui/components/card' import { Callout } from 'fumadocs-ui/components/callout' # SDKs & Libraries Use our SDKs and compatible libraries to integrate AI Magicx into your applications. ## Quick Comparison | Feature | Direct API | OpenAI SDK | |---------|------------|------------| | Chat completions | Full support | Full support | | Streaming | Full support | Full support | | Image generation | Full support | Partial | | Video/Audio/Music | Full support | Not available | | AI Agents | Full support | Not available | For chat completions, we recommend using the **OpenAI SDK** for the best developer experience. For AI Agents, image editing, video, audio, and music generation, use our REST API directly. ## Installation ### Using pip (Python) ```bash pip install openai requests ``` ### Using npm (TypeScript/JavaScript) ```bash npm install openai # or pnpm add openai ``` ## Quick Examples ### Chat Completions ```python from openai import OpenAI client = OpenAI( api_key="sk_your_api_key", base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) ``` ### AI Agents ```python import requests import json headers = {"Authorization": "Bearer sk_your_api_key"} # Create an agent agent = requests.post( "https://www.aimagicx.com/api/v1/agents", headers=headers, json={ "name": "Research Assistant", "system_prompt": "You help with research tasks.", "tools": ["web_search", "web_fetch"] } ).json()["agent"] # Run with streaming response = requests.post( f"https://www.aimagicx.com/api/v1/agents/{agent['id']}/run", headers=headers, json={"input": "What's the latest in AI?"}, stream=True ) for line in response.iter_lines(): if line and line.startswith(b'data: '): event = json.loads(line[6:]) print(event) ``` ## Community SDKs We welcome community contributions! If you've built an SDK or wrapper for AI Magicx, let us know and we'll feature it here. --- ## OpenAI SDK Compatibility URL: https://www.aimagicx.com/docs/sdks/openai-compatibility Description: Use the OpenAI SDK with AI Magicx as a drop-in replacement import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # OpenAI SDK Compatibility AI Magicx's chat completions endpoint is fully compatible with the OpenAI SDK, making it easy to migrate existing applications or use familiar tooling. The OpenAI SDK works with AI Magicx's chat completions endpoint. For other features (images, video, audio, music), use our REST API directly. ## Quick Start ```python from openai import OpenAI client = OpenAI( api_key="sk_your_aimagicx_api_key", base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk_your_aimagicx_api_key", baseURL: "https://www.aimagicx.com/api/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ```bash curl https://www.aimagicx.com/api/v1/chat/completions \ -H "Authorization: Bearer sk_your_aimagicx_api_key" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ## Migrating from OpenAI If you're currently using the OpenAI API, migration requires only two changes: ### Before (OpenAI) ```python from openai import OpenAI client = OpenAI( api_key="sk-your-openai-key" # OpenAI key ) response = client.chat.completions.create( model="gpt-4o-mini", # OpenAI model name messages=[{"role": "user", "content": "Hello!"}] ) ``` ### After (AI Magicx) ```python from openai import OpenAI client = OpenAI( api_key="sk_your_aimagicx_key", # 1. Change to AI Magicx key base_url="https://www.aimagicx.com/api/v1" # 2. Add base URL ) response = client.chat.completions.create( model="openai/gpt-4o-mini", # 3. Prefix with provider messages=[{"role": "user", "content": "Hello!"}] ) ``` ## Supported Features | Feature | Supported | Notes | |---------|-----------|-------| | Chat completions | Yes | Full support | | Streaming | Yes | SSE streaming | | System messages | Yes | Full support | | Multi-turn conversations | Yes | Full support | | Temperature/max_tokens | Yes | Standard parameters | | Vision (image analysis) | Yes | Via images array | | Function calling | Partial | Model-dependent | ## Model Name Mapping AI Magicx uses provider-prefixed model names: | OpenAI Model | AI Magicx Model | |--------------|---------------| | `gpt-4o` | `openai/gpt-4o` | | `gpt-4o-mini` | `openai/gpt-4o-mini` | | `gpt-4-turbo` | `openai/gpt-4-turbo` | | `gpt-3.5-turbo` | `openai/gpt-3.5-turbo` | You can also use models from other providers: | Provider | Example Model | |----------|---------------| | Anthropic | `anthropic/claude-3.5-sonnet` | | Google | `google/gemini-pro` | | Meta | `meta-llama/llama-3-70b` | ## Streaming Example ```python from openai import OpenAI client = OpenAI( api_key="sk_your_aimagicx_key", base_url="https://www.aimagicx.com/api/v1" ) stream = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Write a haiku about coding"}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) ``` ## Environment Variables For cleaner code, use environment variables: ```bash export OPENAI_API_KEY="sk_your_aimagicx_key" export OPENAI_BASE_URL="https://www.aimagicx.com/api/v1" ``` Then your code doesn't need explicit configuration: ```python from openai import OpenAI client = OpenAI() # Uses environment variables response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) ``` ## Limitations The following OpenAI SDK features are **not supported** through AI Magicx: - `client.images.generate()` - Use our REST API for images - `client.audio.speech.create()` - Use our REST API for TTS - `client.audio.transcriptions.create()` - Use our REST API for STT - Assistants API - Embeddings API - Fine-tuning API For features not covered by OpenAI SDK compatibility, use our [REST API](/docs/api-reference) directly. --- ## Python SDK URL: https://www.aimagicx.com/docs/sdks/python Description: Using the AI Magicx API with Python import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # Python SDK The easiest way to use AI Magicx from Python is with the `requests` library for full API access, or the `openai` library for chat completions. ## Installation ```bash pip install requests openai ``` ## Configuration ```python import os API_KEY = os.environ.get("AI_MAGICX_API_KEY") BASE_URL = "https://www.aimagicx.com/api/v1" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } ``` ## Chat Completions ```python from openai import OpenAI client = OpenAI( api_key=os.environ.get("AI_MAGICX_API_KEY"), base_url="https://www.aimagicx.com/api/v1" ) response = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ] ) print(response.choices[0].message.content) ``` ```python import requests response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json={ "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ], "model": "openai/gpt-4o-mini" } ) print(response.json()["choices"][0]["message"]["content"]) ``` ## Streaming ```python from openai import OpenAI client = OpenAI( api_key=os.environ.get("AI_MAGICX_API_KEY"), base_url="https://www.aimagicx.com/api/v1" ) stream = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Write a short poem"}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) ``` ## AI Agents Create and run autonomous agents with tools and memory. ### Create an Agent ```python import requests response = requests.post( f"{BASE_URL}/agents", headers=headers, json={ "name": "Research Assistant", "description": "Helps with research and information gathering", "system_prompt": "You are a helpful research assistant. Search the web to find accurate information and cite your sources.", "model": "anthropic/claude-3.5-sonnet", "tools": ["web_search", "web_fetch", "create_document"], "max_iterations": 10, "memory_enabled": True } ) agent = response.json()["agent"] print(f"Created agent: {agent['id']}") ``` ### Run Agent with Streaming ```python import requests import json def run_agent(agent_id, user_input, session_id=None): """Run an agent and stream the response.""" payload = {"input": user_input} if session_id: payload["session_id"] = session_id response = requests.post( f"{BASE_URL}/agents/{agent_id}/run", headers=headers, json=payload, stream=True ) result = None for line in response.iter_lines(): if not line: continue line = line.decode('utf-8') if not line.startswith('data: '): continue event = json.loads(line[6:]) event_type = event.get("type") if event_type == "start": print(f"Run started: {event['run_id']}") elif event_type == "step": step = event.get("step", {}) step_type = step.get("type") if step_type == "thinking": print(f"[Thinking] {step.get('content', '')[:100]}...") elif step_type == "tool_call": print(f"[Tool] Calling {step.get('tool')}...") elif step_type == "tool_result": print(f"[Result] Got response from {step.get('tool')}") elif step_type == "response": print(f"\n[Response]\n{step.get('content', '')}") elif event_type == "done": result = event print(f"\nCompleted! Credits used: {event.get('credits_used')}") elif event_type == "error": print(f"Error: {event.get('error')}") return result # Usage result = run_agent( agent_id="agent_abc123", user_input="Research the latest developments in quantum computing" ) ``` ### Multi-turn Conversation ```python import uuid # Create a session for conversation continuity session_id = str(uuid.uuid4()) # First turn run_agent(agent["id"], "Search for AI news from today", session_id=session_id) # Second turn - references previous context run_agent(agent["id"], "Tell me more about the first result", session_id=session_id) # Third turn run_agent(agent["id"], "Create a summary document of what we discussed", session_id=session_id) ``` ### Upload Knowledge Base ```python import requests # Upload a document for RAG with open("company_docs.pdf", "rb") as f: response = requests.post( f"{BASE_URL}/agents/{agent_id}/knowledge", headers={"Authorization": f"Bearer {API_KEY}"}, files={"file": f} ) file_info = response.json()["file"] print(f"Uploaded: {file_info['id']}, Status: {file_info['status']}") # Wait for processing import time while True: status = requests.get( f"{BASE_URL}/agents/{agent_id}/knowledge/{file_info['id']}", headers=headers ).json() if status["file"]["status"] == "completed": print("Knowledge file ready!") break elif status["file"]["status"] == "failed": print(f"Failed: {status['file'].get('error_message')}") break time.sleep(2) ``` ### List Agent Runs ```python response = requests.get( f"{BASE_URL}/agents/{agent_id}/runs?limit=10", headers=headers ) for run in response.json()["runs"]: print(f"{run['id']}: {run['status']} - {run['input'][:50]}...") ``` ## Image Generation ```python import requests response = requests.post( f"{BASE_URL}/images/generations", headers=headers, json={ "prompt": "A beautiful sunset over the ocean", "model": "fal-ai/flux/dev", "size": "1024x1024" } ) data = response.json() image_url = data["data"][0]["url"] print(f"Image URL: {image_url}") ``` ## Video Generation (Async) ```python import requests import time # Start async job response = requests.post( f"{BASE_URL}/videos/generations?async=true", headers=headers, json={ "prompt": "A timelapse of clouds moving over mountains", "duration_seconds": 5 } ) job_id = response.json()["id"] print(f"Job started: {job_id}") # Poll for completion while True: status = requests.get( f"{BASE_URL}/jobs/{job_id}?poll=true", headers=headers ).json() print(f"Status: {status['status']}, Progress: {status.get('progress', 0)}%") if status["status"] == "completed": video_url = status["outputData"]["video"]["url"] print(f"Video URL: {video_url}") break elif status["status"] == "failed": print(f"Failed: {status.get('errorMessage')}") break time.sleep(5) ``` ## Text-to-Speech ```python import requests response = requests.post( f"{BASE_URL}/audio/speech", headers=headers, json={ "input": "Hello, welcome to AI Magicx!", "voice": "nova", "speed": 1.0 } ) audio_url = response.json()["audio_url"] # Download the audio file audio_response = requests.get(audio_url) with open("output.mp3", "wb") as f: f.write(audio_response.content) ``` ## Speech-to-Text ```python import requests response = requests.post( f"{BASE_URL}/audio/transcriptions", headers=headers, json={ "file": "https://example.com/audio.mp3", "language": "auto", "diarization": True } ) data = response.json() print(f"Transcript: {data['text']}") print(f"Duration: {data['duration']} seconds") # Print speaker segments for segment in data.get("segments", []): speaker = segment.get("speaker", "Unknown") print(f"[{speaker}] {segment['text']}") ``` ## Error Handling ```python import requests def make_request(endpoint, data): response = requests.post( f"{BASE_URL}/{endpoint}", headers=headers, json=data ) if response.status_code == 200: return response.json() error = response.json() if response.status_code == 401: raise Exception(f"Authentication failed: {error['error']}") elif response.status_code == 402: raise Exception(f"Quota exceeded: {error['error']}") elif response.status_code == 429: retry_after = error.get("retry_after", 60) raise Exception(f"Rate limited. Retry after {retry_after}s") else: raise Exception(f"API error: {error['error']}") ``` ## Helper Class ```python import requests import json import os class AI MagicXClient: def __init__(self, api_key=None): self.api_key = api_key or os.environ.get("AI_MAGICX_API_KEY") self.base_url = "https://www.aimagicx.com/api/v1" self.headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } def chat(self, messages, model="openai/gpt-4o-mini", **kwargs): response = requests.post( f"{self.base_url}/chat/completions", headers=self.headers, json={"messages": messages, "model": model, **kwargs} ) response.raise_for_status() return response.json() def generate_image(self, prompt, **kwargs): response = requests.post( f"{self.base_url}/images/generations", headers=self.headers, json={"prompt": prompt, **kwargs} ) response.raise_for_status() return response.json() def create_agent(self, name, system_prompt, tools=None, **kwargs): response = requests.post( f"{self.base_url}/agents", headers=self.headers, json={ "name": name, "system_prompt": system_prompt, "tools": tools or [], **kwargs } ) response.raise_for_status() return response.json()["agent"] def run_agent(self, agent_id, input_text, session_id=None): payload = {"input": input_text} if session_id: payload["session_id"] = session_id response = requests.post( f"{self.base_url}/agents/{agent_id}/run", headers=self.headers, json=payload, stream=True ) events = [] for line in response.iter_lines(): if line and line.startswith(b'data: '): events.append(json.loads(line[6:])) return events # Usage client = AI MagicXClient() # Chat response = client.chat([{"role": "user", "content": "Hello!"}]) print(response["choices"][0]["message"]["content"]) # Create and run agent agent = client.create_agent( name="Helper", system_prompt="You are helpful.", tools=["web_search"] ) events = client.run_agent(agent["id"], "What's the weather in NYC?") ``` --- ## TypeScript SDK URL: https://www.aimagicx.com/docs/sdks/typescript Description: Using the AI Magicx API with TypeScript and JavaScript import { Tab, Tabs } from 'fumadocs-ui/components/tabs' import { Callout } from 'fumadocs-ui/components/callout' # TypeScript SDK Use AI Magicx from TypeScript or JavaScript with the `openai` package for chat completions, or native `fetch` for full API access. ## Installation ```bash npm install openai # or pnpm add openai ``` ## Configuration ```typescript const API_KEY = process.env.AI_MAGICX_API_KEY; const BASE_URL = "https://www.aimagicx.com/api/v1"; const headers = { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json", }; ``` ## Chat Completions ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.AI_MAGICX_API_KEY, baseURL: "https://www.aimagicx.com/api/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Hello!" }, ], }); console.log(response.choices[0].message.content); ``` ```typescript const response = await fetch(`${BASE_URL}/chat/completions`, { method: "POST", headers, body: JSON.stringify({ messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Hello!" }, ], model: "openai/gpt-4o-mini", }), }); const data = await response.json(); console.log(data.choices[0].message.content); ``` ## Streaming ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.AI_MAGICX_API_KEY, baseURL: "https://www.aimagicx.com/api/v1", }); const stream = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Write a short poem" }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ""; process.stdout.write(content); } ``` ## AI Agents Create and run autonomous agents with tools and memory. ### Types ```typescript interface Agent { id: string; name: string; description?: string; system_prompt: string; model: string; tools: string[]; temperature: number; max_iterations: number; memory_enabled: boolean; created_at: string; } interface AgentRunEvent { type: "start" | "step" | "done" | "error"; run_id?: string; session_id?: string; step?: { step_number: number; type: "thinking" | "tool_call" | "tool_result" | "response"; content?: string; tool?: string; tool_input?: Record; tool_output?: unknown; }; output?: string; credits_used?: number; error?: string; } ``` ### Create an Agent ```typescript async function createAgent(config: { name: string; system_prompt: string; tools?: string[]; model?: string; memory_enabled?: boolean; }): Promise { const response = await fetch(`${BASE_URL}/agents`, { method: "POST", headers, body: JSON.stringify({ name: config.name, system_prompt: config.system_prompt, tools: config.tools || ["web_search"], model: config.model || "anthropic/claude-3.5-sonnet", memory_enabled: config.memory_enabled || false, }), }); const data = await response.json(); return data.agent; } // Usage const agent = await createAgent({ name: "Research Assistant", system_prompt: "You help with research tasks. Search the web and cite sources.", tools: ["web_search", "web_fetch", "create_document"], memory_enabled: true, }); console.log(`Created agent: ${agent.id}`); ``` ### Run Agent with Streaming ```typescript async function runAgent( agentId: string, input: string, sessionId?: string, onEvent?: (event: AgentRunEvent) => void ): Promise { const response = await fetch(`${BASE_URL}/agents/${agentId}/run`, { method: "POST", headers, body: JSON.stringify({ input, session_id: sessionId, }), }); const reader = response.body?.getReader(); const decoder = new TextDecoder(); let finalEvent: AgentRunEvent | null = null; if (!reader) { throw new Error("No response body"); } while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); const lines = chunk.split("\n"); for (const line of lines) { if (!line.startsWith("data: ")) continue; const event: AgentRunEvent = JSON.parse(line.slice(6)); if (onEvent) { onEvent(event); } switch (event.type) { case "start": console.log(`Run started: ${event.run_id}`); break; case "step": const step = event.step!; if (step.type === "thinking") { console.log(`[Thinking] ${step.content?.slice(0, 100)}...`); } else if (step.type === "tool_call") { console.log(`[Tool] Calling ${step.tool}...`); } else if (step.type === "response") { console.log(`\n[Response]\n${step.content}`); } break; case "done": console.log(`\nCompleted! Credits: ${event.credits_used}`); finalEvent = event; break; case "error": console.error(`Error: ${event.error}`); break; } } } return finalEvent; } // Usage const result = await runAgent( agent.id, "Research the latest developments in quantum computing" ); ``` ### Multi-turn Conversation ```typescript import { randomUUID } from "crypto"; // Create a session for conversation continuity const sessionId = randomUUID(); // First turn await runAgent(agent.id, "Search for AI news from today", sessionId); // Second turn - references previous context await runAgent(agent.id, "Tell me more about the first result", sessionId); // Third turn await runAgent(agent.id, "Create a summary document", sessionId); ``` ### Upload Knowledge Base ```typescript async function uploadKnowledge(agentId: string, file: File): Promise { const formData = new FormData(); formData.append("file", file); const response = await fetch(`${BASE_URL}/agents/${agentId}/knowledge`, { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, }, body: formData, }); const { file: fileInfo } = await response.json(); console.log(`Uploaded: ${fileInfo.id}, Status: ${fileInfo.status}`); // Poll for processing completion while (true) { const statusResponse = await fetch( `${BASE_URL}/agents/${agentId}/knowledge/${fileInfo.id}`, { headers } ); const { file: status } = await statusResponse.json(); if (status.status === "completed") { console.log("Knowledge file ready!"); break; } else if (status.status === "failed") { throw new Error(`Failed: ${status.error_message}`); } await new Promise((r) => setTimeout(r, 2000)); } } ``` ## Image Generation ```typescript interface ImageResponse { created: number; data: Array<{ url: string; width: number; height: number }>; usage: { credits_used: number }; } const response = await fetch(`${BASE_URL}/images/generations`, { method: "POST", headers, body: JSON.stringify({ prompt: "A beautiful sunset over the ocean", model: "fal-ai/flux/dev", size: "1024x1024", }), }); const data: ImageResponse = await response.json(); console.log(`Image URL: ${data.data[0].url}`); ``` ## Video Generation (Async) ```typescript interface JobResponse { id: string; status: "pending" | "processing" | "completed" | "failed"; progress?: number; outputData?: { video: { url: string }; }; errorMessage?: string; } // Start async job const createResponse = await fetch( `${BASE_URL}/videos/generations?async=true`, { method: "POST", headers, body: JSON.stringify({ prompt: "A timelapse of clouds moving over mountains", duration_seconds: 5, }), } ); const { id: jobId } = await createResponse.json(); console.log(`Job started: ${jobId}`); // Poll for completion const pollJob = async (jobId: string): Promise => { while (true) { const response = await fetch(`${BASE_URL}/jobs/${jobId}?poll=true`, { headers, }); const status: JobResponse = await response.json(); console.log(`Status: ${status.status}, Progress: ${status.progress || 0}%`); if (status.status === "completed") { return status; } else if (status.status === "failed") { throw new Error(status.errorMessage); } await new Promise((resolve) => setTimeout(resolve, 5000)); } }; const result = await pollJob(jobId); console.log(`Video URL: ${result.outputData?.video.url}`); ``` ## Type Definitions ```typescript // Request types interface ChatMessage { role: "system" | "user" | "assistant"; content: string; images?: string[]; } interface ChatRequest { messages: ChatMessage[]; model?: string; temperature?: number; max_tokens?: number; stream?: boolean; } interface ImageRequest { prompt: string; model?: string; size?: "512x512" | "1024x1024" | "1792x1024" | "1024x1792"; n?: number; style?: "vivid" | "natural"; upscale?: "2x" | "4x"; negative_prompt?: string; seed?: number; } interface AgentRequest { name: string; system_prompt: string; tools?: string[]; model?: string; temperature?: number; max_iterations?: number; memory_enabled?: boolean; } // Response types interface ChatResponse { id: string; choices: Array<{ index: number; message: { role: string; content: string }; finish_reason: string; }>; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number; credits_used: number; }; } ``` ## Helper Class ```typescript class AI MagicXClient { private apiKey: string; private baseUrl: string; constructor(apiKey?: string) { this.apiKey = apiKey || process.env.AI_MAGICX_API_KEY || ""; this.baseUrl = "https://www.aimagicx.com/api/v1"; } private get headers() { return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json", }; } async chat(messages: ChatMessage[], options: Partial = {}) { const response = await fetch(`${this.baseUrl}/chat/completions`, { method: "POST", headers: this.headers, body: JSON.stringify({ messages, ...options }), }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json() as Promise; } async generateImage(prompt: string, options: Partial = {}) { const response = await fetch(`${this.baseUrl}/images/generations`, { method: "POST", headers: this.headers, body: JSON.stringify({ prompt, ...options }), }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } async createAgent(config: AgentRequest): Promise { const response = await fetch(`${this.baseUrl}/agents`, { method: "POST", headers: this.headers, body: JSON.stringify(config), }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } const data = await response.json(); return data.agent; } async *runAgentStream( agentId: string, input: string, sessionId?: string ): AsyncGenerator { const response = await fetch(`${this.baseUrl}/agents/${agentId}/run`, { method: "POST", headers: this.headers, body: JSON.stringify({ input, session_id: sessionId }), }); const reader = response.body?.getReader(); const decoder = new TextDecoder(); if (!reader) throw new Error("No response body"); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); for (const line of chunk.split("\n")) { if (line.startsWith("data: ")) { yield JSON.parse(line.slice(6)); } } } } } // Usage const client = new AI MagicXClient(); // Chat const response = await client.chat([{ role: "user", content: "Hello!" }]); console.log(response.choices[0].message.content); // Create and run agent const agent = await client.createAgent({ name: "Helper", system_prompt: "You are helpful.", tools: ["web_search"], }); for await (const event of client.runAgentStream(agent.id, "What's new in AI?")) { console.log(event); } ``` For production use, consider adding retry logic, better error handling, and request queuing to stay within rate limits. ---