Jozie AI SDK

A lightweight, dependency-free Node.js SDK to connect your provider services to the Jozie AI marketplace. Built for speed, security, and resilience.

Zero Dependencies Secure WebSocket Auto-Reconnect Production Ready

Installation

Install the Jozie AI SDK using npm or yarn:

Terminal
npm install jozieai
Terminal
yarn add jozieai
Terminal
pnpm add jozieai

Quick Start

Get your service running in under 5 minutes.

Pro Tip: Store your API keys in environment variables for security. Never commit them to version control!

1. Get Your API Keys

Navigate to My Services → Provider Credentials in the Jozie AI dashboard to obtain your API key and service key.

2. Create Your Service

my-service.js
const JozieAI = require('jozieai);

// Initialize the service
const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  {
    wsUrl: process.env.JOZIEAI_WS || 'wss://marketplace.jozieai.com:4343',
    autoReconnect: true,
    reconnectDelay: 5000
  }
);

// Connect and set up request handler
provider.connect()
  .then(() => {
    console.log('✓ Connected to JozieAI marketplace');
    
    // Set service status to online
    provider.setStatus('online');
    
    // Handle incoming requests
    provider.onRequest(async (data, metadata) => {
      console.log('Received request:', data);
      
      // Process the request
      const result = {
        success: true,
        message: 'Request processed successfully',
        echo: data
      };
      
      return result;
    });
  })
  .catch(error => {
    console.error('Failed to connect:', error);
  });

3. Run Your Service

Terminal
JOZIEAI_API_KEY=your-api-key \
JOZIEAI_SERVICE_KEY=your-service-key \
node my-service.js

Code Examples

Real-world examples to help you build powerful services.

ES Modules

JavaScript (ESM)
import JozieAI from 'jozieai';

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY
);

await provider.connect();
console.log('Connected to marketplace');

provider.onRequest(async (data) => {
  return { 
    success: true, 
    result: data 
  };
});

TypeScript

TypeScript
import JozieAI from 'jozieai';

interface RequestData {
  query: string;
  maxResults: number;
}

interface ResponseData {
  success: boolean;
  results: string[];
}

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY!,
  process.env.JOZIEAI_SERVICE_KEY!
);

await provider.connect();

provider.onRequest<RequestData, ResponseData>(async (data) => {
  const results = await processQuery(data.query, data.maxResults);
  return { success: true, results };
});

Advanced: Error Handling & Status Management

Advanced Example
const JozieAI = require('jozieai');

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  {
    autoReconnect: true,
    reconnectDelay: 5000
  }
);

provider.connect()
  .then(() => {
    provider.setStatus('online');
    
    provider.onRequest(async (data, metadata) => {
      try {
        // Set status to busy for long-running tasks
        provider.setStatus('busy');
        
        // Process the request
        const result = await processRequest(data);
        
        // Reset status to online
        provider.setStatus('online');
        
        return {
          success: true,
          data: result,
          metadata: {
            processedAt: new Date().toISOString(),
            version: '1.0.0'
          }
        };
      } catch (error) {
        // Reset status even on error
        provider.setStatus('online');
        
        return {
          success: false,
          error: error.message
        };
      }
    });
  })
  .catch(error => {
    console.error('Connection failed:', error);
    process.exit(1);
  });

// Graceful shutdown
process.on('SIGINT', async () => {
  console.log('Shutting down...');
  await provider.disconnect();
  process.exit(0);
});

Authentication

Secure your service with API keys.

API keys authenticate your service provider account and link requests to specific services in the marketplace.

Environment Variables (Recommended)

Create a .env file in your project root:

.env
# JozieAI API Configuration
JOZIEAI_API_KEY=your-provider-api-key-here
JOZIEAI_SERVICE_KEY=your-service-key-here
JOZIEAI_WS=wss://marketplace.jozieai.com:4343

# Optional: Environment
NODE_ENV=production
Security Warning: Add .env to your .gitignore file to prevent accidentally committing your API keys!

Handling Requests

Process incoming requests from marketplace consumers.

The onRequest handler receives two parameters:

Parameter Type Description
data Object Request payload from the consumer
metadata Object Additional request metadata (requestId, timestamp, etc.)

Example: Image Processing Service

image-service.js
provider.onRequest(async (data, metadata) => {
  const { image, operation } = data;
  
  console.log(`Processing ${operation} on image from ${metadata.requestId}`);
  
  // Validate input
  if (!image || !operation) {
    return {
      success: false,
      error: 'Missing required fields: image, operation'
    };
  }
  
  // Process based on operation type
  let result;
  switch (operation) {
    case 'resize':
      result = await resizeImage(image, data.width, data.height);
      break;
    case 'filter':
      result = await applyFilter(image, data.filter);
      break;
    default:
      return {
        success: false,
        error: `Unknown operation: ${operation}`
      };
  }
  
  return {
    success: true,
    image: result,
    operation: operation,
    processedAt: new Date().toISOString()
  };
});

API Reference

Complete documentation of all available methods.

Constructor

Syntax
new JozieAI(apiKey, serviceKey, options)
Method Description Returns
connect() Connect to the marketplace and authenticate Promise<void>
disconnect() Gracefully disconnect from the marketplace Promise<void>
onRequest(handler) Register a request handler function void
setStatus(status) Update service status: 'online', 'offline', 'busy' void

Configuration Options

Customize SDK behavior with configuration options.

Option Type Default Description
wsUrl string 'wss://marketplace.jozieai.com:4343' WebSocket gateway URL
autoReconnect boolean true Automatically reconnect on disconnect
reconnectDelay number 5000 Delay between reconnection attempts (ms)
maxReconnectAttempts number Infinity Maximum reconnection attempts

Events

Listen to SDK events for monitoring and debugging.

Event Listeners
// Connection events
provider.on('connected', () => {
  console.log('Connected to marketplace');
});

provider.on('disconnected', () => {
  console.log('Disconnected from marketplace');
});

provider.on('reconnecting', (attempt) => {
  console.log(`Reconnection attempt ${attempt}`);
});

// Error events
provider.on('error', (error) => {
  console.error('Service error:', error);
});

// Request events
provider.on('request_received', (metadata) => {
  console.log('Request received:', metadata.requestId);
});

provider.on('request_completed', (metadata, result) => {
  console.log('Request completed:', metadata.requestId);
});

Troubleshooting

Common issues and solutions.

Connection Errors

Error: "Failed to connect to WebSocket"

Solution: Verify that the wsUrl is correct and the gateway is running. Check firewall settings and network connectivity.

Authentication Errors

Error: "Invalid API key"

Solution: Double-check your API key in the dashboard under My Services → Provider Credentials. Ensure you're using the provider API key, not a consumer key.

Service Not Receiving Requests

Issue: Service is online but not receiving requests

Solutions:
  • Verify service status is set to 'online'
  • Check that the service key matches the service in the dashboard
  • Ensure the service is active in the marketplace

FAQ

Can I run multiple services on one provider?

Yes! Each service needs its own serviceKey, but they can share the same provider API key. Run separate instances of the SDK for each service.

How do I handle long-running requests?

Use provider.setStatus('busy') to indicate your service is processing. This prevents new requests from being sent until you set the status back to 'online'.

What happens if my service crashes?

With autoReconnect: true, the SDK will automatically attempt to reconnect. Implement proper error handling and consider using a process manager like PM2 for production.

Can I use this in production?

Absolutely! The SDK is production-ready. Use environment variables for credentials, implement proper error handling, and monitor your service logs.

Ready-to-Run App Templates

Download a complete Node.js service project — pre-wired to the Jozie AI SDK, ready to deploy on your own hardware in minutes. Each package includes package.json, .env.example, README.md, and launch scripts.

Requirements: Node.js 18+, Ollama running locally or on a remote host, and a Jozie AI provider API key + service key.
Ollama Chat

Conversational AI service using Ollama's /api/chat. Supports full multi-turn message history and any installed chat model.

Ollama /api/chat llama3.2 mistral Multi-turn
service.js
require('dotenv').config();
const JozieAI = require('jozieai');

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  { wsUrl: process.env.JOZIEAI_WS || 'wss://marketplace.jozieai.com:4343' }
);

const OLLAMA_HOST = process.env.OLLAMA_HOST || 'http://localhost:11434';
const MODEL       = process.env.OLLAMA_MODEL || 'llama3.2';

provider.connect().then(() => {
  provider.setStatus('online');
  console.log(`✓ Ollama Chat ready — model: ${MODEL}`);

  provider.onRequest(async (data) => {
    // data.messages: [{ role, content }, ...]
    const messages = Array.isArray(data.messages)
      ? data.messages
      : [{ role: 'user', content: String(data.prompt || data) }];

    const res = await fetch(`${OLLAMA_HOST}/api/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: data.model || MODEL,
        messages,
        stream: false
      })
    });
    const json = await res.json();
    return {
      success: true,
      message: json.message,
      model: json.model,
      totalTokens: json.eval_count
    };
  });
});
Ollama Generate

Single-shot text generation via /api/generate. Perfect for summarisation, classification, extraction, and one-off prompts.

Ollama /api/generate Any model System prompt
service.js
require('dotenv').config();
const JozieAI = require('jozieai');

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  { wsUrl: process.env.JOZIEAI_WS || 'wss://marketplace.jozieai.com:4343' }
);

const OLLAMA_HOST = process.env.OLLAMA_HOST || 'http://localhost:11434';
const MODEL       = process.env.OLLAMA_MODEL || 'llama3.2';
const SYSTEM      = process.env.SYSTEM_PROMPT || 'You are a helpful assistant.';

provider.connect().then(() => {
  provider.setStatus('online');
  console.log(`✓ Ollama Generate ready — model: ${MODEL}`);

  provider.onRequest(async (data) => {
    const res = await fetch(`${OLLAMA_HOST}/api/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: data.model || MODEL,
        prompt: data.prompt || '',
        system: data.system || SYSTEM,
        options: {
          temperature: data.temperature ?? 0.7,
          num_predict: data.maxTokens ?? 1024
        },
        stream: false
      })
    });
    const json = await res.json();
    return {
      success: true,
      response: json.response,
      model: json.model,
      evalCount: json.eval_count,
      evalDuration: json.eval_duration
    };
  });
});
Ollama Vision

Image analysis & captioning using multimodal models like llava or moondream. Accepts base64-encoded images.

Ollama /api/generate llava moondream Base64 image
service.js
require('dotenv').config();
const JozieAI = require('jozieai');

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  { wsUrl: process.env.JOZIEAI_WS || 'wss://marketplace.jozieai.com:4343' }
);

const OLLAMA_HOST = process.env.OLLAMA_HOST || 'http://localhost:11434';
const MODEL       = process.env.OLLAMA_MODEL || 'llava';

provider.connect().then(() => {
  provider.setStatus('online');
  console.log(`✓ Ollama Vision ready — model: ${MODEL}`);

  provider.onRequest(async (data) => {
    // data.image: base64 string (no data-URL prefix)
    // data.prompt: question about the image
    if (!data.image) {
      return { success: false, error: 'Missing required field: image (base64)' };
    }

    // Strip data-URL prefix if present
    const imageData = data.image.replace(/^data:image\/[^;]+;base64,/, '');

    const res = await fetch(`${OLLAMA_HOST}/api/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: data.model || MODEL,
        prompt: data.prompt || 'Describe this image in detail.',
        images: [imageData],
        stream: false
      })
    });
    const json = await res.json();
    return {
      success: true,
      description: json.response,
      model: json.model
    };
  });
});
Ollama Embeddings

Generate vector embeddings for RAG, semantic search, and similarity tasks using /api/embed. Returns a float array.

Ollama /api/embed nomic-embed-text RAG Semantic search
service.js
require('dotenv').config();
const JozieAI = require('jozieai');

const provider = new JozieAI(
  process.env.JOZIEAI_API_KEY,
  process.env.JOZIEAI_SERVICE_KEY,
  { wsUrl: process.env.JOZIEAI_WS || 'wss://marketplace.jozieai.com:4343' }
);

const OLLAMA_HOST = process.env.OLLAMA_HOST || 'http://localhost:11434';
const MODEL       = process.env.OLLAMA_MODEL || 'nomic-embed-text';

provider.connect().then(() => {
  provider.setStatus('online');
  console.log(`✓ Ollama Embeddings ready — model: ${MODEL}`);

  provider.onRequest(async (data) => {
    // data.input: string or string[]
    const input = data.input || data.text || data.prompt;
    if (!input) {
      return { success: false, error: 'Missing required field: input' };
    }

    const res = await fetch(`${OLLAMA_HOST}/api/embed`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: data.model || MODEL,
        input: Array.isArray(input) ? input : [input]
      })
    });
    const json = await res.json();
    return {
      success: true,
      embeddings: json.embeddings,
      model: json.model,
      dimensions: json.embeddings?.[0]?.length
    };
  });
});

Quick Deploy

Fill in the form below and click Generate Package. You'll download a complete zip ready to unzip, run npm install, and start.

Generate Your Service Package

Creates a complete deployable Node.js project with your configuration pre-filled

Ollama Chat — Conversational multi-turn AI
  • Input: { messages: [{role, content}] }
  • Output: { message: {role, content}, model, totalTokens }
  • Default model: llama3.2
Used as the npm package name and zip folder

Register this service so buyers can discover and use it. You must be logged in — your Provider API Key is auto-filled from your session. Pricing is permanent once set and cannot be changed later. After registering, the Service Key will be auto-filled below.
Flat fee charged on every request
Fee based on response payload size
Fee for compute time used
Describe what your service expects to receive
Describe what your service returns

Registering does not start the service. Run the downloaded package on your hardware to bring it online.

Service registered!

Auto-filled when logged in
Auto-filled after Step 2 registration

Run: ollama pull llama3.2


Package ready!
Unzip, run npm install, then npm start