### Send Chat Completion Request with GPT-4 (Python) Source: https://docs.electronhub.ai/getting-started/quickstart This example shows how to make a chat completion request using the more capable `gpt-4` model. It illustrates sending a specific prompt to explain quantum computing, demonstrating model selection for different tasks. ```Python response = requests.post( 'https://api.electronhub.ai/v1/chat/completions', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'model': 'gpt-4', 'messages': [ {'role': 'user', 'content': 'Explain quantum computing in simple terms'} ] } ) ``` -------------------------------- ### Electron Hub Get Usage API Example Response Source: https://docs.electronhub.ai/api-reference/usage Illustrates a typical JSON response from the Get Usage API endpoint with example values for subscription, credits, token usage, and endpoint-specific usage. ```JSON { "subscription": "pro", "credits": 1250, "usage": { "input_tokens": 45230, "output_tokens": 12870 }, "history": [ { "date": "2024-12-26", "requests": 142 }, { "date": "2024-12-25", "requests": 98 } ], "endpoints": { "chat.completions": 95, "images.generations": 23, "images.edits": 5, "videos.generations": 2 } } ``` -------------------------------- ### Generate Code Assistance using ElectronHub AI API Source: https://docs.electronhub.ai/examples/chat-examples This JavaScript function demonstrates how to use the ElectronHub AI API to get programming assistance. It sends a code question and desired language to the API, receiving well-commented code examples and explanations. Requires an ElectronHub API key for authentication. ```JavaScript async function codeAssistant(codeQuestion, programmingLanguage = 'JavaScript') { const systemPrompt = `You are an expert ${programmingLanguage} developer. Provide clear, well-commented code examples. Explain complex concepts in simple terms. Always include error handling when appropriate.`; const response = await fetch('https://api.electronhub.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4', messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: codeQuestion } ], max_tokens: 1000, temperature: 0.2 }) }); const data = await response.json(); return data.choices[0].message.content; } // Usage const codeHelp = await codeAssistant( "How do I implement a binary search algorithm?", "Python" ); ``` -------------------------------- ### Implement a Customer Support Bot with System Prompt Source: https://docs.electronhub.ai/examples/chat-examples Shows how to create a specialized chat application, like a customer support bot, by using a detailed system prompt that includes customer-specific information. This guides the AI's behavior and response style for tailored interactions. ```Node.js async function customerSupportChat(userMessage, customerData) { const systemPrompt = `You are a helpful customer support agent for TechCorp. Customer Info: - Name: ${customerData.name} - Account Type: ${customerData.accountType} - Recent Orders: ${customerData.recentOrders} Provide helpful, professional responses. If you need to escalate, say "Let me connect you with a specialist."`; const response = await fetch('https://api.electronhub.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4', messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: userMessage } ], max_tokens: 300, temperature: 0.3 }) }); const data = await response.json(); return data.choices[0].message.content; } // Usage const response = await customerSupportChat( "I can't access my account", { name: "John Doe", accountType: "Premium", recentOrders: ["Order #12345", "Order #12346"] } ); ``` -------------------------------- ### Python Example for Basic Chat Completions Request Source: https://docs.electronhub.ai/api-reference/chat/completions This Python example demonstrates how to make a simple POST request to the Electron Hub chat completions API using the `requests` library. It shows how to set the Authorization header and send a basic message payload to get a chat completion. ```Python import requests response = requests.post( 'https://api.electronhub.ai/v1/chat/completions', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'model': 'gpt-3.5-turbo', 'messages': [ {'role': 'user', 'content': 'Hello!'} ] } ) ``` -------------------------------- ### Generate Text Embeddings (Python) Source: https://docs.electronhub.ai/getting-started/quickstart This example illustrates how to convert text into numerical vector embeddings using the Electron Hub API. It sends an input text to the `text-embedding-3-small` model, which is useful for tasks like semantic search or text similarity. ```Python response = requests.post( 'https://api.electronhub.ai/v1/embeddings', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'input': 'Your text to embed', 'model': 'text-embedding-3-small' } ) embedding = response.json()['data'][0]['embedding'] ``` -------------------------------- ### Example Response with Multiple User Log Entries Source: https://docs.electronhub.ai/api-reference/user-logs Provides a comprehensive JSON array example showing multiple log entries from the 'Get User Logs' endpoint. It demonstrates various request types, including chat completions and image generations, with their respective details and costs. ```JSON [ { "key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567", "model": "gpt-4o", "route": "chat.completions", "credits": 0.001475, "timestamp": 1747802046, "status": "success", "input_tokens": 23, "output_tokens": 9, "ip": "14.161.20.81" }, { "key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567", "model": "dall-e-3", "route": "images.generations", "credits": 0.2, "timestamp": 1747245603, "status": "success", "ip": "2001:ee0:d781:2280:e9d8:c4d6:c683:e48" }, { "key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567", "model": "claude-3-5-sonnet-20241022", "route": "chat.completions", "credits": 0.000609, "timestamp": 1747802047, "status": "success", "input_tokens": 23, "output_tokens": 36, "ip": "14.161.20.81" } ] ``` -------------------------------- ### Install OpenAI SDK for JavaScript/Node.js Source: https://docs.electronhub.ai/guides/openai-sdks Installs the official OpenAI SDK for JavaScript and Node.js using npm, a prerequisite for interacting with Electron Hub's API. ```JavaScript npm install openai ``` -------------------------------- ### Perform Basic Chat Completion for Simple Q&A Source: https://docs.electronhub.ai/examples/chat-examples Demonstrates how to send a single user message to the Electron Hub API's chat completions endpoint to get a direct answer. This example uses 'gpt-3.5-turbo' and sets a maximum token limit for the response. ```Node.js const response = await fetch('https://api.electronhub.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: [ { role: 'user', content: 'What is the capital of France?' } ], max_tokens: 100 }) }); const data = await response.json(); console.log(data.choices[0].message.content); ``` -------------------------------- ### Install OpenAI SDK for Python Source: https://docs.electronhub.ai/guides/openai-sdks Installs the official OpenAI SDK for Python using pip, a prerequisite for interacting with Electron Hub's API. ```Python pip install openai ``` -------------------------------- ### Example Request: List Proxy Keys Source: https://docs.electronhub.ai/api-reference/proxy-keys Demonstrates how to make a GET request to the List Proxy Keys endpoint using cURL, requiring an API key for authorization. ```cURL curl https://api.electronhub.ai/v1/auth/proxy \ -H "Authorization: Bearer $ELECTRONHUB_API_KEY" ``` -------------------------------- ### Basic Text-to-Speech Example (Node.js) Source: https://docs.electronhub.ai/api-reference/audio/speech This Node.js example demonstrates how to call the Electron Hub Text-to-Speech API to generate an MP3 audio file from text. It uses the `fetch` API to send a POST request and the `fs` module to save the resulting audio buffer to a local file named 'speech.mp3'. ```JavaScript const response = await fetch('https://api.electronhub.ai/v1/audio/speech', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'tts-1', input: 'Hello! Welcome to Electron Hub text-to-speech.', voice: 'alloy', response_format: 'mp3' }) }); const audioBuffer = await response.arrayBuffer(); const fs = require('fs'); fs.writeFileSync('speech.mp3', Buffer.from(audioBuffer)); ``` -------------------------------- ### Electron Hub Get Model API Endpoint Documentation Source: https://docs.electronhub.ai/api-reference/model Comprehensive API documentation for the GET /v1/models/{model} endpoint, detailing its path parameters, expected successful response schema, an example response, and the structure of error responses. ```APIDOC Path Parameters: model: string (required) Description: Model ID ``` ```APIDOC { "name": "", "description": "", "id": "", "object": "model", "created": 123, "owned_by": "", "tokens": 123, "pricing": { "input": 123, "output": 123 }, "endpoints": [ "" ], "premium_model": true, "voices": [ "" ], "sizes": [ "" ], "qualities": [ "" ], "tags": [ "" ], "styles": [ "" ], "metadata": {} } ``` ```APIDOC { "name": "OpenAI: GPT-4o", "description": "GPT-4o (\"o\" for \"omni\") is OpenAI's latest AI model, supporting both text and image inputs with text outputs. It maintains the intelligence level of GPT-4 Turbo while being twice as fast and 50% more cost-effective. GPT-4o also offers improved performance in processing non-English languages and enhanced visual capabilities.", "id": "gpt-4o", "object": "model", "created": 1748957251, "owned_by": "openai", "tokens": 128000, "pricing": { "type": "per_million_tokens", "input": 2.5, "output": 10 }, "endpoints": [ "/v1/chat/completions", "/v1/responses" ], "premium_model": false, "metadata": { "vision": true, "function_call": true, "web_search": false, "reasoning": false } } ``` ```APIDOC { "error": { "message": "Model not found", "type": "invalid_request_error", "code": "model_not_found" } } ``` ```APIDOC Response: 200 - application/json Description: Success Type: object ``` -------------------------------- ### Install Anthropic SDK for JavaScript/TypeScript Source: https://docs.electronhub.ai/guides/anthropic-sdks This snippet shows how to install the official Anthropic SDK using npm for JavaScript and TypeScript projects. ```JavaScript npm install @anthropic-ai/sdk ``` -------------------------------- ### Install Anthropic SDK for Python Source: https://docs.electronhub.ai/guides/anthropic-sdks This snippet shows how to install the official Anthropic SDK using pip for Python projects. ```Python pip install anthropic ``` -------------------------------- ### Generate Image from Text Prompt (Python) Source: https://docs.electronhub.ai/getting-started/quickstart This snippet demonstrates how to use the Electron Hub API's image generation endpoint. It sends a text prompt to the `dall-e-3` model to create an image, specifying the desired size, and then retrieves and prints the URL of the generated image. ```Python response = requests.post( 'https://api.electronhub.ai/v1/images/generations', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'prompt': 'A futuristic cityscape at sunset', 'model': 'dall-e-3', 'size': '1024x1024' } ) image_url = response.json()['data'][0]['url'] print(f"Generated image: {image_url}") ``` -------------------------------- ### Client-Side Example: Create Response (Node.js) Source: https://docs.electronhub.ai/api-reference/responses Provides a practical code example for invoking the Responses API to create a text response using Node.js. The example demonstrates how to set up the request body, headers, and handle the API response. ```Node.js const response = await fetch('https://api.electronhub.ai/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4o', input: 'Write a short story about a robot:', instructions: 'Write in a creative and engaging style', max_output_tokens: 500, temperature: 0.7 }) }); const data = await response.json(); console.log(data); ``` -------------------------------- ### Create Message API Request Example Source: https://docs.electronhub.ai/api-reference/messages Examples demonstrating how to send a POST request to the Electron Hub Messages API to create a message completion. Includes cURL for a comprehensive request body and Node.js for a basic example. ```cURL curl --request POST \ --url https://api.electronhub.ai/v1/messages \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "model": "claude-3-5-sonnet-20241022", "messages": [ { "role": "user", "content": "" } ], "max_tokens": 123, "temperature": 0.5, "top_p": 123, "top_k": 123, "stream": false, "system": "", "tools": [ { "name": "", "description": "", "input_schema": {} } ], "tool_choice": "auto", "thinking": { "type": "enabled", "budget_tokens": 123 }, "reasoning_effort": "low" }' ``` ```Node.js const response = await fetch('https://api.electronhub.ai/v1/messages', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'claude-3-sonnet-20240229', max_tokens: 1000, messages: [ { role: 'user', content: 'Hello, Claude!' } ] }) }); const data = await response.json(); console.log(data); ``` -------------------------------- ### JavaScript Implementation of Robust Image Generation Service Source: https://docs.electronhub.ai/examples/image-examples Provides a comprehensive JavaScript class, `ImageGenerationService`, for interacting with the Electronhub AI image generation API. This includes methods for generating images with retry logic, downloading images, and validating user prompts, followed by a practical usage example. ```javascript class ImageGenerationService { constructor(apiKey) { this.apiKey = apiKey; this.baseURL = 'https://api.electronhub.ai/v1'; } async generateImage(prompt, options = {}) { const { model = 'dall-e-3', size = '1024x1024', quality = 'standard', style = 'vivid', retries = 3 } = options; for (let attempt = 1; attempt <= retries; attempt++) { try { const response = await fetch(`${this.baseURL}/images/generations`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, model, size, quality, style, n: 1 }) }); if (!response.ok) { if (response.status === 400) { const error = await response.json(); throw new Error(`Content policy violation: ${error.error.message}`); } if (response.status === 429) { // Rate limited const delay = Math.pow(2, attempt) * 1000; console.log(`Rate limited, waiting ${delay}ms before retry ${attempt}`); await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { success: true, imageUrl: data.data[0].url, revisedPrompt: data.data[0].revised_prompt }; } catch (error) { if (attempt === retries) { return { success: false, error: error.message }; } console.warn(`Attempt ${attempt} failed:`, error.message); } } } async downloadImage(imageUrl, filename) { try { const response = await fetch(imageUrl); const blob = await response.blob(); // Create download link const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename || 'generated-image.png'; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(url); return true; } catch (error) { console.error('Download failed:', error); return false; } } validatePrompt(prompt) { if (!prompt || prompt.trim().length === 0) { throw new Error('Prompt cannot be empty'); } if (prompt.length > 1000) { throw new Error('Prompt too long (max 1000 characters)'); } // Check for potentially problematic content const restrictedTerms = ['violence', 'harmful', 'illegal']; const lowerPrompt = prompt.toLowerCase(); for (const term of restrictedTerms) { if (lowerPrompt.includes(term)) { throw new Error(`Prompt contains restricted content: ${term}`); } } return true; } } ``` ```javascript // Usage const imageService = new ImageGenerationService('YOUR_API_KEY'); try { imageService.validatePrompt('A beautiful landscape painting'); const result = await imageService.generateImage( 'A serene Japanese garden with cherry blossoms', { model: 'dall-e-3', size: '1024x1024', quality: 'hd' } ); if (result.success) { console.log('Generated image:', result.imageUrl); console.log('Revised prompt:', result.revisedPrompt); // Download the image await imageService.downloadImage(result.imageUrl, 'japanese-garden.png'); } else { console.error('Generation failed:', result.error); } } catch (error) { console.error('Validation failed:', error.message); } ``` -------------------------------- ### JavaScript Content Recommendation Engine using ElectronHub AI Embeddings Source: https://docs.electronhub.ai/examples/embedding-examples This comprehensive JavaScript code defines a `ContentRecommendationEngine` class that interacts with the ElectronHub AI embeddings API. It includes methods for adding content items (generating their embeddings), retrieving content recommendations based on user preferences, and finding content similar to a given item. The class uses cosine similarity for ranking. The snippet also provides a full usage example demonstrating how to initialize the engine, add content, and fetch recommendations or similar items. ```javascript class ContentRecommendationEngine { constructor(apiKey) { this.apiKey = apiKey; this.contentItems = []; } async addContent(items) { // Items should be objects with id, title, description, category const descriptions = items.map(item => `${item.title}. ${item.description}. Category: ${item.category}` ); const response = await fetch('https://api.electronhub.ai/v1/embeddings', { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: descriptions, model: 'text-embedding-3-small' }) }); const data = await response.json(); items.forEach((item, index) => { this.contentItems.push({ ...item, embedding: data.data[index].embedding }); }); } async getRecommendations(userPreferences, count = 5) { // Get embedding for user preferences const response = await fetch('https://api.electronhub.ai/v1/embeddings', { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: userPreferences, model: 'text-embedding-3-small' }) }); const data = await response.json(); const userEmbedding = data.data[0].embedding; // Calculate similarities and rank content const recommendations = this.contentItems.map(item => ({ ...item, similarity: this.cosineSimilarity(userEmbedding, item.embedding) })); return recommendations .sort((a, b) => b.similarity - a.similarity) .slice(0, count); } async findSimilarContent(contentId, count = 5) { const targetContent = this.contentItems.find(item => item.id === contentId); if (!targetContent) return []; const similarities = this.contentItems .filter(item => item.id !== contentId) .map(item => ({ ...item, similarity: this.cosineSimilarity(targetContent.embedding, item.embedding) })); return similarities .sort((a, b) => b.similarity - a.similarity) .slice(0, count); } cosineSimilarity(a, b) { const dotProduct = a.reduce((sum, ai, i) => sum + ai * b[i], 0); const magnitudeA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0)); const magnitudeB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0)); return dotProduct / (magnitudeA * magnitudeB); } } // Usage const recommender = new ContentRecommendationEngine('YOUR_API_KEY'); const contentCatalog = [ { id: 1, title: 'Introduction to Machine Learning', description: 'Learn the basics of ML algorithms and applications', category: 'Technology' }, { id: 2, title: 'Cooking Italian Pasta', description: 'Traditional recipes for authentic Italian pasta dishes', category: 'Food' }, { id: 3, title: 'JavaScript for Beginners', description: 'Complete guide to learning JavaScript programming', category: 'Technology' }, { id: 4, title: 'Yoga and Meditation', description: 'Mindfulness practices for physical and mental wellness', category: 'Health' }, { id: 5, title: 'Data Science with Python', description: 'Analyze data and build predictive models using Python', category: 'Technology' } ]; await recommender.addContent(contentCatalog); // Get recommendations based on user preferences const userPrefs = 'I am interested in programming and software development'; const recommendations = await recommender.getRecommendations(userPrefs, 3); console.log('Recommended content:'); recommendations.forEach((rec, index) => { console.log(`${index + 1}. ${rec.title} (${rec.similarity.toFixed(3)})`); }); // Find similar content to a specific item const similar = await recommender.findSimilarContent(3, 2); // Similar to JavaScript course console.log('\nSimilar to JavaScript course:'); similar.forEach((item, index) => { console.log(`${index + 1}. ${item.title} (${item.similarity.toFixed(3)})`); }); ``` -------------------------------- ### List Models API Example Response Source: https://docs.electronhub.ai/api-reference/models This snippet provides an example of the actual JSON response returned by the Electron Hub API's List Models endpoint, showing a few sample model entries with their IDs, object types, and owners, demonstrating the typical data format. ```APIDOC { "object": "list", "data": [ { "id": "gpt-4o", "object": "model", "owned_by": "openai" }, { "id": "claude-3-5-sonnet-20241022", "object": "model", "owned_by": "anthropic" }, { "id": "gemini-pro", "object": "model", "owned_by": "google" } ] } ``` -------------------------------- ### Electron Hub Get Usage API Response Field Definitions Source: https://docs.electronhub.ai/api-reference/usage Detailed documentation for each field within the Get Usage API response, explaining their purpose and structure. ```APIDOC subscription: string Your current subscription plan (e.g., “free”, “starter”, “pro”, “enterprise”) credits: number Number of credits remaining in your account usage: object Token usage statistics: input_tokens: number - Total input tokens consumed output_tokens: number - Total output tokens generated history: array Array of daily usage records showing request counts by date endpoints: object Usage breakdown by API endpoint: chat.completions: number - Chat completion requests images.generations: number - Image generation requests images.edits: number - Image editing requests videos.generations: number - Video generation requests ``` -------------------------------- ### Example Proxy Key API Response Source: https://docs.electronhub.ai/api-reference/proxy-keys Illustrative JSON response showing the structure and typical values for multiple proxy key entries, demonstrating the data format returned by the API. ```json [ { "name": "Production API Key", "key": "ek-proxy-1234567890abcdef", "expires_at": 1735689600, "allocated_ammount": 100.0, "used_ammount": 25.5, "is_active": true, "model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"], "ip_whitelist": ["192.168.1.0/24"], "created_at": 1704067200, "last_used": 1704153600 }, { "name": "Development Key", "key": "ek-proxy-abcdef1234567890", "expires_at": -1, "allocated_ammount": 10.0, "used_ammount": 2.1, "is_active": true, "model_whitelist": [], "ip_whitelist": [], "created_at": 1704067200, "last_used": 1704139200 } ] ``` -------------------------------- ### Example Response: List Proxy Keys Source: https://docs.electronhub.ai/api-reference/proxy-keys Provides a sample JSON response showing the structure and typical data returned when successfully listing proxy keys, including details like key name, expiration, usage, and access controls. ```JSON [ { "name": "Production API Key", "key": "ek-proxy-1234567890abcdef", "expires_at": 1735689600, "allocated_ammount": 100.0, "used_ammount": 25.5, "is_active": true, "model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"], "ip_whitelist": ["192.168.1.0/24"], "created_at": 1704067200, "last_used": 1704153600 }, { "name": "Development Key", "key": "ek-proxy-abcdef1234567890", "expires_at": -1, "allocated_ammount": 10.0, "used_ammount": 2.1, "is_active": true, "model_whitelist": [], "ip_whitelist": [], "created_at": 1704067200, "last_used": 1704139200 } ] ``` -------------------------------- ### APIDOC: Example Proxy Key Toggle Response Source: https://docs.electronhub.ai/api-reference/proxy-toggle Shows an example JSON response body for a successful proxy key status update, indicating a message and the new status (true for enabled). ```APIDOC { "message": "Proxy key status updated", "status": true } ``` -------------------------------- ### Example JSON Response for Chat Completions API Source: https://docs.electronhub.ai/api-reference/chat/completions This JSON example illustrates the typical structure of a successful response from the chat completions endpoint, including the completion ID, object type, creation timestamp, model used, a list of choices with message content and finish reason, and token usage statistics. ```JSON { "id": "", "object": "chat.completion", "created": 123, "model": "", "choices": [ { "index": 123, "message": { "role": "system", "content": "", "name": "", "tool_calls": [ { "id": "", "type": "function", "function": { "name": "", "arguments": "" } } ] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 123, "completion_tokens": 123, "total_tokens": 123 } } ``` -------------------------------- ### JavaScript Document Clustering Implementation with Electronhub AI Source: https://docs.electronhub.ai/examples/embedding-examples This JavaScript class, `DocumentClusterer`, demonstrates how to perform document clustering. It fetches document embeddings from the Electronhub AI API, then applies a k-means algorithm to group documents into a specified number of clusters. The class includes methods for calculating Euclidean distance and centroids, and requires an Electronhub AI API key for embedding generation. The usage example shows how to initialize the clusterer, provide documents, and print the resulting clusters. ```JavaScript class DocumentClusterer { constructor(apiKey) { this.apiKey = apiKey; } async clusterDocuments(documents, numClusters = 3) { // Get embeddings for all documents const response = await fetch('https://api.electronhub.ai/v1/embeddings', { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: documents, model: 'text-embedding-3-small' }) }); const data = await response.json(); const embeddings = data.data.map(item => item.embedding); // Simple k-means clustering const clusters = await this.kMeansClustering(embeddings, numClusters); // Group documents by cluster const clusteredDocs = {}; clusters.forEach((clusterIndex, docIndex) => { if (!clusteredDocs[clusterIndex]) { clusteredDocs[clusterIndex] = []; } clusteredDocs[clusterIndex].push({ index: docIndex, text: documents[docIndex], embedding: embeddings[docIndex] }); }); return clusteredDocs; } async kMeansClustering(embeddings, k, maxIterations = 100) { const dimensions = embeddings[0].length; // Initialize centroids randomly let centroids = Array.from({ length: k }, () => Array.from({ length: dimensions }, () => Math.random() * 2 - 1) ); let assignments = new Array(embeddings.length); for (let iteration = 0; iteration < maxIterations; iteration++) { // Assign points to closest centroids const newAssignments = embeddings.map(embedding => { let closestCentroid = 0; let closestDistance = this.euclideanDistance(embedding, centroids[0]); for (let i = 1; i < k; i++) { const distance = this.euclideanDistance(embedding, centroids[i]); if (distance < closestDistance) { closestDistance = distance; closestCentroid = i; } } return closestCentroid; }); // Check for convergence if (JSON.stringify(assignments) === JSON.stringify(newAssignments)) { break; } assignments = newAssignments; // Update centroids for (let i = 0; i < k; i++) { const clusterPoints = embeddings.filter((_, index) => assignments[index] === i); if (clusterPoints.length > 0) { centroids[i] = this.calculateCentroid(clusterPoints); } } } return assignments; } euclideanDistance(a, b) { return Math.sqrt(a.reduce((sum, ai, i) => sum + Math.pow(ai - b[i], 2), 0)); } calculateCentroid(points) { const dimensions = points[0].length; const centroid = new Array(dimensions).fill(0); points.forEach(point => { point.forEach((value, i) => { centroid[i] += value; }); }); return centroid.map(sum => sum / points.length); } } // Usage const clusterer = new DocumentClusterer('YOUR_API_KEY'); const documents = [ 'Machine learning algorithms learn from data to make predictions', 'Deep neural networks have multiple hidden layers for complex patterns', 'Pizza is a traditional Italian dish with tomato sauce and cheese', 'Pasta comes in many shapes and is often served with various sauces', 'Basketball is played by two teams of five players each', 'Soccer is the most popular sport worldwide with billions of fans', 'Artificial intelligence aims to create machines that can think', 'Lasagna is a layered pasta dish baked in the oven', 'Tennis is played on a rectangular court with a net in the middle' ]; const clusters = await clusterer.clusterDocuments(documents, 3); console.log('Document Clusters:'); Object.entries(clusters).forEach(([clusterIndex, docs]) => { console.log(`\nCluster ${parseInt(clusterIndex) + 1}:`); docs.forEach(doc => { console.log(` - ${doc.text}`); }); }); ``` -------------------------------- ### cURL Example for Streaming Chat Completions Source: https://docs.electronhub.ai/api-reference/chat/completions This cURL example illustrates how to enable real-time streaming responses from the chat completions endpoint. By setting the 'stream' parameter to true in the request body, the API will send responses incrementally as they are generated. ```cURL curl https://api.electronhub.ai/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-3.5-turbo", "messages": [ {"role": "user", "content": "Tell me a story"} ], "stream": true }' ``` -------------------------------- ### Manage Multi-turn Conversations with Context Source: https://docs.electronhub.ai/examples/chat-examples Illustrates how to maintain conversation history by sending an array of messages, including system, user, and assistant roles, to the chat completions API. This allows the model to understand the ongoing context and provide relevant responses. ```Node.js const conversationHistory = [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Hello! Can you help me with math?' }, { role: 'assistant', content: 'Of course! I\'d be happy to help you with math. What would you like to work on?' }, { role: 'user', content: 'What is 25 * 4?' } ]; const response = await fetch('https://api.electronhub.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: conversationHistory, max_tokens: 150, temperature: 0.7 }) }); const data = await response.json(); console.log(data.choices[0].message.content); ``` -------------------------------- ### JavaScript Chat Service with Retry Logic Source: https://docs.electronhub.ai/examples/chat-examples This JavaScript `ChatService` class demonstrates how to build a robust client for the ElectronHub AI chat completion API. It includes a `sendMessage` method that handles API requests, implements exponential backoff for rate limiting (HTTP 429), and retries for server errors (HTTP 5xx). The class manages common chat parameters like model, max tokens, and temperature, and provides a usage example for sending a user message and handling potential errors. ```JavaScript class ChatService { constructor(apiKey) { this.apiKey = apiKey; this.baseURL = 'https://api.electronhub.ai/v1'; } async sendMessage(messages, options = {}) { const { model = 'gpt-3.5-turbo', maxTokens = 500, temperature = 0.7, retries = 3 } = options; for (let attempt = 1; attempt <= retries; attempt++) { try { const response = await fetch(`${this.baseURL}/chat/completions`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model, messages, max_tokens: maxTokens, temperature }) }); if (!response.ok) { if (response.status === 429) { // Rate limited - wait and retry const delay = Math.pow(2, attempt) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); continue; } if (response.status >= 500) { // Server error - retry if (attempt < retries) continue; } throw new Error(`API request failed: ${response.status}`); } const data = await response.json(); return data.choices[0].message.content; } catch (error) { if (attempt === retries) { throw new Error(`Failed to get response after ${retries} attempts: ${error.message}`); } console.warn(`Attempt ${attempt} failed:`, error.message); } } } } // Usage const chatService = new ChatService('YOUR_API_KEY'); try { const response = await chatService.sendMessage([ { role: 'user', content: 'Hello, how are you?' } ]); console.log(response); } catch (error) { console.error('Chat failed:', error.message); // Handle error appropriately } ``` -------------------------------- ### Implement Semantic Search Engine with Electronhub AI in JavaScript Source: https://docs.electronhub.ai/examples/embedding-examples This JavaScript class, `SemanticSearchEngine`, demonstrates how to build a document search system. It uses the Electronhub AI embeddings API to convert text documents and queries into vector embeddings. The `addDocuments` method sends text to the API for embedding, while the `search` method calculates cosine similarity between a query's embedding and stored document embeddings to retrieve the most relevant results. The example usage shows how to initialize the engine, populate a knowledge base, and perform a search. ```JavaScript class SemanticSearchEngine { constructor(apiKey) { this.apiKey = apiKey; this.documents = []; this.embeddings = []; } async addDocuments(documents) { const response = await fetch('https://api.electronhub.ai/v1/embeddings', { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: documents, model: 'text-embedding-3-small' }) }); const data = await response.json(); documents.forEach((doc, index) => { this.documents.push({ id: this.documents.length, text: doc, embedding: data.data[index].embedding }); }); console.log(`Added ${documents.length} documents to search index`); } async search(query, topK = 5) { // Get query embedding const response = await fetch('https://api.electronhub.ai/v1/embeddings', { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: query, model: 'text-embedding-3-small' }) }); const data = await response.json(); const queryEmbedding = data.data[0].embedding; // Calculate similarities const similarities = this.documents.map(doc => ({ ...doc, similarity: this.cosineSimilarity(queryEmbedding, doc.embedding) })); // Sort by similarity and return top results return similarities .sort((a, b) => b.similarity - a.similarity) .slice(0, topK); } cosineSimilarity(a, b) { const dotProduct = a.reduce((sum, ai, i) => sum + ai * b[i], 0); const magnitudeA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0)); const magnitudeB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0)); return dotProduct / (magnitudeA * magnitudeB); } } // Usage const searchEngine = new SemanticSearchEngine('YOUR_API_KEY'); // Add knowledge base const knowledgeBase = [ 'Python is a high-level programming language known for its simplicity', 'JavaScript is the language of the web, used for both frontend and backend', 'Machine learning algorithms can learn patterns from data', 'APIs enable different software applications to communicate', 'Databases store and organize large amounts of structured data', 'Cloud computing provides on-demand computing resources', 'Cybersecurity protects systems from digital attacks and threats' ]; await searchEngine.addDocuments(knowledgeBase); // Search for relevant documents const results = await searchEngine.search('web development programming', 3); console.log('Search Results:'); results.forEach((result, index) => { console.log(`${index + 1}. [${result.similarity.toFixed(3)}] ${result.text}`); }); ``` -------------------------------- ### Efficient AI Model Selection Guide Source: https://docs.electronhub.ai/getting-started/rate-limits Provides guidance on selecting the appropriate AI model for specific tasks based on performance, cost, and capability, including recommendations for GPT-3.5-turbo, GPT-4o, Claude-3-haiku, and Claude-3-5-sonnet. ```APIDOC - GPT-3.5-turbo: Fast and cost-effective for simple tasks - GPT-4o: Best for complex reasoning and analysis - Claude-3-haiku: Fastest for quick responses - Claude-3-5-sonnet: Balanced performance and capability ``` -------------------------------- ### Image Generation API Success Response Example Source: https://docs.electronhub.ai/api-reference/images/generations This snippet provides an example of the successful JSON response returned by the Electron Hub Image Generation API, detailing the structure of the generated image data including creation timestamp, URLs, and base64-encoded images. ```JSON { "created": 123, "data": [ { "url": "", "b64_json": "", "revised_prompt": "" } ] } ``` -------------------------------- ### Integrate Content Moderation with ElectronHub AI in JavaScript Source: https://docs.electronhub.ai/examples/chat-examples This JavaScript example illustrates how to integrate content moderation into a chat application using the ElectronHub AI Moderations API. It first checks user messages for inappropriate content before proceeding to the chat completions API, ensuring a safe conversational environment. It requires an ElectronHub API key and uses 'fetch' for API interactions. ```javascript async function moderatedChat(userMessage, conversationHistory = []) { // First, check if the user message is appropriate const moderationResponse = await fetch('https://api.electronhub.ai/v1/moderations', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ input: userMessage, model: 'text-moderation-latest' }) }); const moderationData = await moderationResponse.json(); if (moderationData.results[0].flagged) { return { response: "I'm sorry, but I can't respond to that type of content. Please keep our conversation respectful.", flagged: true }; } // If content is safe, proceed with chat const messages = [ ...conversationHistory, { role: 'user', content: userMessage } ]; const chatResponse = await fetch('https://api.electronhub.ai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: messages, max_tokens: 300 }) }); const chatData = await chatResponse.json(); return { response: chatData.choices[0].message.content, flagged: false }; } ``` -------------------------------- ### API Call Example: Create Response (cURL & JSON) Source: https://docs.electronhub.ai/api-reference/responses Demonstrates how to make a POST request to the /v1/responses endpoint using cURL, including the required headers and a sample JSON request body. Also shows the expected JSON response structure for a successful call. ```cURL curl --request POST \ --url https://api.electronhub.ai/v1/responses \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "model": "gpt-4o", "input": "", "instructions": "", "max_output_tokens": 123, "temperature": 1, "top_p": 1, "stream": false, "tools": [ { "type": "function", "function": { "name": "", "description": "", "parameters": {} } } ], "tool_choice": "auto", "web_search": false, "reasoning": { "effort": "low", "summary": true }, "metadata": {} }' ``` ```JSON { "id": "", "object": "response", "created_at": 123, "status": "in_progress", "model": "", "output": [ { "id": "", "type": "message", "status": "in_progress", "role": "assistant", "content": [ { "type": "output_text", "text": "", "annotations": [ "" ] } ] } ], "usage": { "input_tokens": 123, "input_tokens_details": {}, "output_tokens": 123, "output_tokens_details": {}, "total_tokens": 123 } } ``` -------------------------------- ### Make First Chat Completion Request (Python) Source: https://docs.electronhub.ai/getting-started/quickstart This snippet demonstrates how to send a basic chat completion request to the Electron Hub API using Python's `requests` library. It includes setting up authorization with your API key and sending a simple user message to the `gpt-3.5-turbo` model. ```Python import requests response = requests.post( 'https://api.electronhub.ai/v1/chat/completions', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'model': 'gpt-3.5-turbo', 'messages': [ {'role': 'user', 'content': 'Hello! How are you?'} ] } ) print(response.json()['choices'][0]['message']['content']) ``` -------------------------------- ### Get User Logs with cURL Source: https://docs.electronhub.ai/api-reference/user-logs Demonstrates how to make a GET request to the Electron Hub API's /v1/user/logs endpoint using cURL. This example includes the necessary 'Authorization' header with a Bearer token for authentication. ```cURL curl --request GET \ --url https://api.electronhub.ai/v1/user/logs \ --header 'Authorization: Bearer ' ```