Skip to content

JavaScript/TypeScript SDK

Official JavaScript SDK for the Inspira API.

Installation

NPM

bash
npm install @inspirahub/sdk

Yarn

bash
yarn add @inspirahub/sdk

PNPM

bash
pnpm add @inspirahub/sdk

Quick Start

Initialize Client

javascript
import { InspiraClient } from '@inspirahub/sdk';

const client = new InspiraClient({
  apiKey: process.env.INSPIRA_API_KEY,
  // Optional configuration
  baseUrl: 'https://app.inspirahub.net/api/rest',
  timeout: 30000,
  maxRetries: 3
});

TypeScript Configuration

The SDK includes TypeScript definitions out of the box:

typescript
import { InspiraClient, ImageGenerationOptions, ChatMessage } from '@inspirahub/sdk';

const client = new InspiraClient({
  apiKey: process.env.INSPIRA_API_KEY!
});

Core Features

Chat Completions

javascript
// Simple chat
const response = await client.chat.complete({
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What is quantum computing?' }
  ]
});

console.log(response.message);

// Advanced options
const response = await client.chat.complete({
  messages: messages,
  temperature: 0.7,
  maxTokens: 1000,
  topP: 0.9,
  stream: true,
  onToken: (token) => {
    process.stdout.write(token);
  }
});

Image Generation

javascript
// Generate single image
const image = await client.images.generate({
  prompt: 'A futuristic city at sunset',
  size: '1024x1024',
  quality: 'high',
  style: 'photorealistic'
});

console.log(image.url);

// Generate multiple variations
const images = await client.images.generate({
  prompt: 'Abstract art',
  n: 4,
  size: '512x512'
});

images.forEach((img, index) => {
  console.log(`Image ${index + 1}: ${img.url}`);
});

// Save image locally
await client.images.download(image.url, './output/city.png');

Video Generation

javascript
// Generate video
const video = await client.videos.generate({
  prompt: 'A spaceship landing on Mars',
  duration: 5,
  resolution: '1080p',
  fps: 30
});

// Check generation status
const status = await client.videos.getStatus(video.id);

if (status.complete) {
  console.log(`Video URL: ${status.url}`);
}

// Download video
await client.videos.download(video.id, './output/spaceship.mp4');

Book Grading

javascript
// Grade written content
const result = await client.education.gradeBook({
  content: essayText,
  gradeLevel: 'high school',
  subject: 'english',
  rubric: {
    grammar: 25,
    content: 40,
    structure: 20,
    creativity: 15
  }
});

console.log(`Overall Grade: ${result.overallGrade}`);
console.log(`Feedback: ${result.feedback}`);

// Get detailed analysis
result.categories.forEach(category => {
  console.log(`${category.name}: ${category.score}/${category.maxScore}`);
  console.log(`Comments: ${category.comments}`);
});

EduFi Tutoring

US Education System

javascript
// AP Course Assistant
const apResponse = await client.edufi.us.ap({
  message: 'Explain the Krebs cycle for AP Biology',
  conversationHistory: []
});

// College Prep Assistant
const collegeResponse = await client.edufi.us.collegePrep({
  message: 'Help me prepare for SAT math',
  subject: 'mathematics',
  conversationHistory: []
});

UK Education System

javascript
// GCSE Assistant
const gcseResponse = await client.edufi.uk.gcse({
  message: 'Explain photosynthesis for GCSE Biology',
  conversationHistory: []
});

// A-Level Assistant
const aLevelResponse = await client.edufi.uk.aLevel({
  message: 'Discuss themes in Shakespeare\'s Hamlet',
  subject: 'english literature',
  conversationHistory: []
});

European Education System

javascript
// European Baccalaureate
const bacResponse = await client.edufi.europe.baccalaureate({
  message: 'Expliquez la Révolution française',
  language: 'fr',
  conversationHistory: []
});

// University Prep
const uniResponse = await client.edufi.europe.universityPrep({
  message: 'Prepare me for engineering entrance exams',
  country: 'Germany',
  conversationHistory: []
});

Global Education

javascript
// International Baccalaureate
const ibResponse = await client.edufi.global.ib({
  message: 'Explain Theory of Knowledge concepts',
  subject: 'TOK',
  conversationHistory: []
});

// Language Preparation
const langResponse = await client.edufi.global.languagePrep({
  message: 'Help me prepare for IELTS speaking',
  targetScore: 7.5,
  conversationHistory: []
});

Detection Tools

Image Analysis

javascript
// Deepfake Detection
const deepfakeResult = await client.detection.deepfake({
  imageUrl: 'https://example.com/image.jpg',
  sensitivity: 'high'
});

console.log(`Deepfake probability: ${deepfakeResult.probability}%`);
console.log(`Confidence: ${deepfakeResult.confidence}`);

// Explicit Content Detection
const explicitResult = await client.detection.explicitContent({
  imageUrl: imageUrl,
  categories: ['violence', 'adult', 'gore']
});

explicitResult.detections.forEach(detection => {
  console.log(`${detection.category}: ${detection.probability}%`);
});

// Label Detection
const labels = await client.detection.labels({
  imageUrl: imageUrl,
  maxLabels: 10,
  minConfidence: 0.7
});

labels.forEach(label => {
  console.log(`${label.name}: ${label.confidence}%`);
});

// Logo Detection
const logos = await client.detection.logos({
  imageUrl: imageUrl,
  brands: ['Nike', 'Apple', 'Google']
});

logos.detected.forEach(logo => {
  console.log(`Found ${logo.brand} logo at ${logo.location}`);
});

Writing Tools

Text Analysis

javascript
// AI Detection
const aiDetection = await client.writing.detectAI({
  text: 'Text to analyze...',
  model: 'advanced'
});

console.log(`AI Generated: ${aiDetection.isAI ? 'Yes' : 'No'}`);
console.log(`Confidence: ${aiDetection.confidence}%`);

// Grammar Checking
const grammar = await client.writing.checkGrammar({
  text: 'Text with erors to check',
  language: 'en',
  style: 'formal'
});

grammar.corrections.forEach(correction => {
  console.log(`Error at position ${correction.offset}: ${correction.message}`);
  console.log(`Suggestion: ${correction.suggestion}`);
});

// Text Rephrasing
const rephrased = await client.writing.rephrase({
  text: 'Original text to rephrase',
  tone: 'professional',
  length: 'similar'
});

console.log(`Rephrased: ${rephrased.text}`);

// Summarization
const summary = await client.writing.summarize({
  text: longArticle,
  length: 'medium',
  format: 'bullet_points'
});

console.log('Summary:');
summary.points.forEach(point => {
  console.log(`• ${point}`);
});

Blockchain Tools

Smart Contract Operations

javascript
// Audit Smart Contract
const audit = await client.blockchain.audit({
  contractCode: solidityCode,
  blockchain: 'ethereum',
  auditLevel: 'comprehensive'
});

console.log(`Security Score: ${audit.securityScore}/100`);
audit.vulnerabilities.forEach(vuln => {
  console.log(`${vuln.severity}: ${vuln.description}`);
  console.log(`Line ${vuln.line}: ${vuln.recommendation}`);
});

// Generate Contract Code
const contract = await client.blockchain.generateContract({
  description: 'ERC-20 token with burn function',
  blockchain: 'ethereum',
  features: ['mintable', 'burnable', 'pausable']
});

console.log(contract.code);

// Launch Advisor
const launchAdvice = await client.blockchain.launchAdvisor({
  projectType: 'DeFi',
  stage: 'pre-launch',
  budget: 'medium'
});

launchAdvice.recommendations.forEach(rec => {
  console.log(`${rec.priority}: ${rec.action}`);
});

// Marketing Advisor
const marketingPlan = await client.blockchain.marketingAdvisor({
  projectName: 'MyDeFi Protocol',
  targetAudience: 'DeFi enthusiasts',
  budget: '$50,000'
});

console.log(`Strategy: ${marketingPlan.strategy}`);
console.log(`Timeline: ${marketingPlan.timeline}`);

Advanced Features

Streaming Responses

javascript
// Stream chat responses
const stream = await client.chat.stream({
  messages: messages,
  onToken: (token) => {
    process.stdout.write(token);
  },
  onComplete: (fullResponse) => {
    console.log('\nComplete response received');
  },
  onError: (error) => {
    console.error('Stream error:', error);
  }
});

// Stream with React
function ChatComponent() {
  const [response, setResponse] = useState('');
  
  const handleChat = async () => {
    await client.chat.stream({
      messages: messages,
      onToken: (token) => {
        setResponse(prev => prev + token);
      }
    });
  };
}

Batch Operations

javascript
// Batch image generation
const batchImages = await client.images.generateBatch([
  { prompt: 'Sunset over mountains' },
  { prompt: 'Ocean waves' },
  { prompt: 'Forest path' }
]);

// Batch detection
const batchDetections = await client.detection.batchProcess({
  images: imageUrls,
  operations: ['deepfake', 'explicit', 'labels']
});

Error Handling

javascript
import { InspiraError, RateLimitError, InsufficientCreditsError } from '@inspirahub/sdk';

try {
  const result = await client.images.generate({ prompt });
} catch (error) {
  if (error instanceof InsufficientCreditsError) {
    console.log(`Need ${error.required} credits, have ${error.available}`);
    // Redirect to purchase credits
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
    // Implement retry logic
  } else if (error instanceof InspiraError) {
    console.error(`API Error: ${error.code} - ${error.message}`);
  } else {
    console.error('Unexpected error:', error);
  }
}

Credit Management

javascript
// Check credit balance
const balance = await client.credits.getBalance();
console.log(`Current balance: ${balance.credits} credits`);

// Get usage history
const usage = await client.credits.getUsage({
  startDate: '2025-01-01',
  endDate: '2025-01-31',
  limit: 100
});

// Monitor credit usage
client.on('creditsUsed', (event) => {
  console.log(`Used ${event.credits} credits on ${event.endpoint}`);
  console.log(`Remaining: ${event.remaining}`);
});

// Set low balance alert
client.credits.setAlert({
  threshold: 50,
  callback: (balance) => {
    console.warn(`Low balance warning: ${balance} credits remaining`);
  }
});

WebSocket Support

javascript
// Real-time updates
const ws = client.realtime.connect();

ws.on('generation.complete', (data) => {
  console.log(`Generation ${data.id} completed`);
});

ws.on('credit.update', (data) => {
  console.log(`Credit balance updated: ${data.balance}`);
});

// Subscribe to specific events
ws.subscribe('image.generation.*');
ws.subscribe('credit.*');

Configuration Options

Client Configuration

javascript
const client = new InspiraClient({
  // Required
  apiKey: process.env.INSPIRA_API_KEY,
  
  // Optional
  baseUrl: 'https://app.inspirahub.net/api/rest',
  timeout: 30000, // 30 seconds
  maxRetries: 3,
  retryDelay: 1000,
  exponentialBackoff: true,
  
  // Headers
  headers: {
    'X-Custom-Header': 'value'
  },
  
  // Hooks
  onRequest: (config) => {
    console.log(`Making request to ${config.url}`);
  },
  onResponse: (response) => {
    console.log(`Response received: ${response.status}`);
  },
  onError: (error) => {
    console.error(`Request failed: ${error.message}`);
  }
});

Environment Variables

javascript
// .env file
INSPIRA_API_KEY=inspira_your_api_key
INSPIRA_BASE_URL=https://app.inspirahub.net/api/rest
INSPIRA_TIMEOUT=30000
INSPIRA_DEBUG=true

// Usage
const client = new InspiraClient({
  apiKey: process.env.INSPIRA_API_KEY,
  baseUrl: process.env.INSPIRA_BASE_URL,
  timeout: parseInt(process.env.INSPIRA_TIMEOUT),
  debug: process.env.INSPIRA_DEBUG === 'true'
});

TypeScript Support

Type Definitions

typescript
import type {
  ChatCompletionOptions,
  ImageGenerationOptions,
  VideoGenerationOptions,
  DetectionResult,
  CreditBalance,
  ApiError
} from '@inspirahub/sdk';

// Strongly typed responses
const response: ChatCompletionResponse = await client.chat.complete(options);
const image: GeneratedImage = await client.images.generate(options);

// Type guards
if (isApiError(error)) {
  console.error(`API Error: ${error.code}`);
}

Custom Types

typescript
// Extend SDK types
interface CustomImageOptions extends ImageGenerationOptions {
  customField: string;
}

// Type-safe event handlers
client.on<ImageGeneratedEvent>('image.generated', (event) => {
  console.log(event.image.url);
});

Testing

Mock Client

javascript
import { MockInspiraClient } from '@inspirahub/sdk/testing';

const mockClient = new MockInspiraClient({
  responses: {
    'chat.complete': { message: 'Mocked response' },
    'images.generate': { url: 'https://example.com/mock.jpg' }
  }
});

// Use in tests
describe('MyComponent', () => {
  it('should generate image', async () => {
    const result = await myFunction(mockClient);
    expect(result.url).toBe('https://example.com/mock.jpg');
  });
});

Migration Guide

From REST API to SDK

javascript
// Before (REST API)
const response = await fetch('https://app.inspirahub.net/api/rest/chat', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ messages })
});
const data = await response.json();

// After (SDK)
const data = await client.chat.complete({ messages });

Resources

Revolutionizing Education with AI and Web3