NexusAI SDK Documentation v2.4.1

The official NexusAI SDK provides a type-safe, high-performance interface to interact with our AI models. Supports Python, JavaScript/TypeScript, and Go with unified APIs for generation, analysis, and real-time inference.

ℹ️
Version Compatibility This documentation covers SDK v2.x. Upgrading from v1.x? Check the migration guide for breaking changes.

Installation

Install the SDK using your preferred package manager. Ensure you have Node.js 18+ or Python 3.9+.

# Install via npm or yarn
npm install @nexusai/sdk

# For TypeScript types
npm install -D @types/nexusai__sdk
# Install via pip
pip install nexusai

# Optional: async & streaming extras
pip install nexusai[async,streaming]
# Go 1.20+
go get github.com/nexusai/sdk-go/v2

Quick Start

Initialize the client and make your first request. The SDK handles retries, timeouts, and rate limiting automatically.

import { NexusAI } from '@nexusai/sdk';

// Initialize with API key
const client = new NexusAI({
  apiKey: process.env.NEXUS_API_KEY,
  timeout: 30000,
  maxRetries: 3
});

async function generate() {
  const response = await client.generate({
    model: 'nexus-v3-ultra',
    prompt: 'Explain quantum computing in simple terms.',
    temperature: 0.7
  });

  console.log(response.text);
  console.log(response.usage.tokens); // 142
}

generate();
from nexusai import NexusAI

# Initialize client
client = NexusAI(
    api_key=os.environ["NEXUS_API_KEY"],
    timeout=30.0,
    max_retries=3
)

def generate():
    response = client.generate(
        model="nexus-v3-ultra",
        prompt="Explain quantum computing in simple terms.",
        temperature=0.7
    )
    
    print(response.text)
    print(response.usage.tokens) # 142

generate()

API Reference

Client Configuration

The NexusAI client manages authentication, HTTP pooling, and request lifecycle.

ParameterTypeDefaultDescription
apiKeystringRequiredYour secret API key from dashboard
baseUrlstringhttps://api.nexusai.com/v2Override endpoint for custom regions
timeoutnumber30000Request timeout in milliseconds
maxRetriesnumber2Automatic retry attempts on 429/5xx
logLevel'silent' | 'error' | 'debug''error'SDK verbosity level

Generate Request Schema

ParameterTypeOptionalDescription
modelstringNoModel identifier (e.g., nexus-v3-ultra)
promptstring | string[]NoInput text or multi-turn conversation
temperaturenumberYes0.0 to 2.0. Higher = more creative
top_pnumberYesNucleus sampling cutoff (0.0-1.0)
max_tokensnumberYesMaximum output tokens (default: 2048)
streambooleanYesEnable SSE streaming response
⚠️
Security Notice Never hardcode API keys in client-side code. Use environment variables or a secrets manager. Keys exposed in public repos will be revoked.

Advanced Examples

Streaming Responses

Stream tokens as they're generated using async iterators or event listeners.

// JavaScript Async Iteration
const stream = await client.generate({
  model: 'nexus-v3-ultra',
  prompt: 'Write a short story about AI.',
  stream: true
});

for await (const chunk of stream) {
  process.stdout.write(chunk.delta);
}

// Python Async for loop
# async for chunk in await client.generate(..., stream=True):
#     print(chunk.delta, end='', flush=True)

Error Handling

SDK throws typed errors. Catch and handle gracefully.

try {
  const res = await client.generate({ prompt: 'test' });
} catch (err) {
  if (err instanceof NexusAI.APIError) {
    console.error(`Rate limited: ${err.retryAfter}ms`);
  } else if (err instanceof NexusAI.AuthError) {
    console.error('Invalid or expired API key');
  }
}

Configuration & Best Practices

  • Caching: Enable cache: true for repeated prompts to reduce latency and cost.
  • Context Window: v3-ultra supports 128K tokens. Monitor response.usage.input_tokens to avoid truncation.
  • Backoff Strategy: SDK implements exponential backoff with jitter. Override via retryStrategy: 'linear' if needed.