AI Magicx
Getting Started

Code Examples

Code Examples

Complete examples for integrating the AI Magicx API into your applications.

Quick Start

1. Get Your API Key

First, obtain your API key from the AI Magicx Dashboard.

2. Set Up Environment

Code(bash)
# Set as environment variable export AIMAGICX_API_KEY="mgx-sk-your-api-key-here"

3. Make Your First Request

Code(bash)
curl -X POST https://beta.aimagicx.com/api/v1/chat \ -H "Authorization: Bearer $AIMAGICX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Hello, AI!", "model": "4o-mini" }'

JavaScript/Node.js Examples

Basic Setup

Code(javascript)
// api-client.js const AIMAGICX_API_KEY = process.env.AIMAGICX_API_KEY; const API_BASE_URL = 'https://beta.aimagicx.com/api/v1'; class AImagicxClient { constructor(apiKey) { this.apiKey = apiKey; this.baseURL = API_BASE_URL; } async request(endpoint, options = {}) { const response = await fetch(`${this.baseURL}${endpoint}`, { ...options, headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', ...options.headers } }); if (!response.ok) { const error = await response.json(); throw new Error(error.error.message); } return response.json(); } } const client = new AImagicxClient(AIMAGICX_API_KEY);

Chat Completion

Code(javascript)
async function chatWithAI() { try { const response = await client.request('/chat', { method: 'POST', body: JSON.stringify({ message: 'Explain quantum computing in simple terms', model: '4o-mini', temperature: 0.7, maxTokens: 500 }) }); console.log(response.data.choices[0].message.content); } catch (error) { console.error('Error:', error.message); } }

Streaming Chat

Code(javascript)
async function streamChat() { const response = await fetch(`${API_BASE_URL}/chat`, { method: 'POST', headers: { 'Authorization': `Bearer ${AIMAGICX_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Write a story about a time-traveling scientist', model: 'claude-3-5-sonnet', stream: true }) }); const reader = response.body.getReader(); const decoder = new TextDecoder(); 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: ')) { const data = line.slice(6); if (data === '[DONE]') continue; try { const parsed = JSON.parse(data); process.stdout.write(parsed.choices[0].delta.content || ''); } catch (e) { // Handle parsing errors } } } } }

Using Tools

Code(javascript)
async function chatWithTools() { const response = await client.request('/chat', { method: 'POST', body: JSON.stringify({ message: 'What\'s the weather in New York and convert 100 USD to EUR?', model: '4o-mini', tools: ['getWeather', 'convertCurrency'] }) }); // The AI will use the tools and provide a comprehensive response console.log(response.data.choices[0].message.content); // Tool calls are available in the response const toolCalls = response.data.choices[0].message.tool_calls; console.log('Tools used:', toolCalls); }

Image Generation

Code(javascript)
async function generateImage() { const response = await client.request('/ai-image/generate', { method: 'POST', body: JSON.stringify({ prompt: 'A futuristic city with flying cars at sunset, cyberpunk style', model: 'fal-ai/flux/schnell', size: 'landscape_16_9', style: 'cyberpunk', quality: 'hd' }) }); console.log('Generated image URL:', response.data.data[0].url); console.log('Credits used:', response.data.usage.credits_consumed); }

Logo Generation

Code(javascript)
async function generateLogo() { const response = await client.request('/ai-image/logo', { method: 'POST', body: JSON.stringify({ prompt: 'Modern tech startup logo for "CloudSync"', model: 'fal-ai/flux/dev', style: 'minimal', industry: 'technology', mood: 'professional', color_scheme: 'Blue and white gradient', typography: 'sans-serif', n: 3 // Generate 3 variations }) }); response.data.data.forEach((logo, index) => { console.log(`Logo ${index + 1}: ${logo.url}`); }); }

Python Examples

Basic Setup

Code(python)
import os import requests from typing import Dict, Any, Optional class AImagicxClient: def __init__(self, api_key: str): self.api_key = api_key self.base_url = "https://beta.aimagicx.com/api/v1" self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } def request(self, endpoint: str, method: str = "GET", data: Optional[Dict] = None) -> Dict[str, Any]: url = f"{self.base_url}{endpoint}" response = requests.request( method=method, url=url, headers=self.headers, json=data ) if response.status_code != 200: error = response.json() raise Exception(f"API Error: {error['error']['message']}") return response.json() # Initialize client api_key = os.environ.get("AIMAGICX_API_KEY") client = AImagicxClient(api_key)

Chat Completion

Code(python)
def chat_with_ai(): response = client.request("/chat", "POST", { "message": "What are the benefits of machine learning?", "model": "4o-mini", "temperature": 0.7, "maxTokens": 500 }) content = response["data"]["choices"][0]["message"]["content"] print(content)

Streaming with Python

Code(python)
import json import requests def stream_chat(): response = requests.post( f"{client.base_url}/chat", headers=client.headers, json={ "message": "Write a haiku about programming", "model": "claude-3-5-sonnet", "stream": True }, stream=True ) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data = line[6:] if data != '[DONE]': try: parsed = json.loads(data) content = parsed['choices'][0]['delta'].get('content', '') print(content, end='', flush=True) except: pass

Image Generation with Error Handling

Code(python)
def generate_image_safe(): try: response = client.request("/ai-image/generate", "POST", { "prompt": "A serene Japanese garden with cherry blossoms", "model": "dall-e-3", "size": "square", "quality": "hd", "style": "photorealistic" }) image_url = response["data"]["data"][0]["url"] credits_used = response["data"]["usage"]["credits_consumed"] print(f"Image generated: {image_url}") print(f"Credits used: {credits_used}") # Download the image import urllib.request urllib.request.urlretrieve(image_url, "generated_image.png") except Exception as e: print(f"Error generating image: {e}")

Usage Monitoring

Track Your Usage

Code(javascript)
// JavaScript async function getUsageStats() { const today = new Date().toISOString().split('T')[0]; const response = await client.request(`/usage?start_date=${today}`); const { totalRequests, totalCreditsUsed, creditsRemaining } = response.data; console.log(` Today's Usage: - Requests: ${totalRequests} - Credits Used: ${totalCreditsUsed} - Credits Remaining: ${creditsRemaining} `); }
Code(python)
# Python from datetime import datetime def get_usage_stats(): today = datetime.now().strftime("%Y-%m-%d") response = client.request(f"/usage?start_date={today}") data = response["data"] print(f""" Today's Usage: - Requests: {data['totalRequests']} - Credits Used: {data['totalCreditsUsed']} - Credits Remaining: {data['creditsRemaining']} """)

Error Handling Best Practices

Comprehensive Error Handler

Code(javascript)
class APIError extends Error { constructor(code, message, details) { super(message); this.code = code; this.details = details; } } async function makeAPICall(endpoint, options) { try { const response = await fetch(`${API_BASE_URL}${endpoint}`, { ...options, headers: { 'Authorization': `Bearer ${AIMAGICX_API_KEY}`, 'Content-Type': 'application/json', ...options.headers } }); const data = await response.json(); if (!response.ok) { throw new APIError( data.error.code, data.error.message, data.error.details ); } return data; } catch (error) { if (error instanceof APIError) { switch (error.code) { case 'RATE_LIMIT_EXCEEDED': console.log('Rate limit hit. Waiting...'); // Implement exponential backoff break; case 'INSUFFICIENT_CREDITS': console.log('Need more credits:', error.details); // Handle credit purchase flow break; case 'INVALID_REQUEST': console.log('Invalid request:', error.message); // Fix request parameters break; default: console.error('API Error:', error.message); } } else { console.error('Network error:', error); } throw error; } }

OpenAI SDK Compatibility

The chat endpoint is compatible with the OpenAI SDK:

Code(javascript)
import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.AIMAGICX_API_KEY, baseURL: 'https://beta.aimagicx.com/api/v1', }); async function chatWithOpenAISDK() { const completion = await openai.chat.completions.create({ messages: [{ role: 'user', content: 'Hello!' }], model: '4o-mini', }); console.log(completion.choices[0].message.content); }

Rate Limiting and Retries

Exponential Backoff

Code(javascript)
async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 'RATE_LIMIT_EXCEEDED' && i < maxRetries - 1) { const delay = Math.pow(2, i) * 1000; // Exponential backoff console.log(`Rate limited. Waiting ${delay}ms...`); await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } } // Usage const result = await callWithRetry(() => client.request('/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', model: '4o-mini' }) }) );

Webhook Integration (Coming Soon)

Code(javascript)
// Future webhook handler example app.post('/webhooks/aimagicx', (req, res) => { const event = req.body; switch (event.type) { case 'credits.low': console.log('Low credits alert:', event.data); // Send notification break; case 'usage.limit_approaching': console.log('Approaching usage limit:', event.data); // Take action break; } res.status(200).json({ received: true }); });

Next Steps

Last modified on