Neurons can be called using either the REST API directly or our official TypeScript SDK. This guide explains both methods and their options.

REST API

Each Neuron has a unique API URL in the format:

https://run.prompteus.com/<organization-slug>/<neuron-slug>

Authentication Requirements

Authentication is only required if enforced by the Neuron’s access control settings. A Neuron can be configured with:

When authentication is required, provide it using the Authorization header:

Authorization: Bearer <your-jwt-or-api-key>

If your Neuron has public access enabled, you can skip the authentication step entirely. See the Access Control documentation for detailed configuration options.

Basic Usage

To call a Neuron, send a POST request to its API URL with your input in JSON format:

curl -X POST https://run.prompteus.com/<organization-slug>/<neuron-slug> \
  -H "Content-Type: application/json" \
  -d '{"input": "What is the meaning of life?"}'

Complete Examples

Here are complete examples showing how to call Neurons with error handling and authentication:

async function callNeuron(orgSlug, neuronSlug, input, apiKey = null) {
  const url = `https://run.prompteus.com/${orgSlug}/${neuronSlug}`;
  const headers = {
    'Content-Type': 'application/json'
  };
  
  // Add authentication if provided
  if (apiKey) {
    headers['Authorization'] = `Bearer ${apiKey}`;
  }

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: JSON.stringify({ input }),
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error: ${error.error} (${response.status})`);
    }

    const data = await response.json();
    
    // Log if response was from cache
    if (data.fromCache) {
      console.log('Response served from cache');
    }

    return data;
  } catch (error) {
    console.error('Failed to call neuron:', error);
    throw error;
  }
}

// Example usage
async function example() {
  try {
    // Call without authentication
    const publicResponse = await callNeuron(
      'my-org',
      'my-neuron',
      'What is the meaning of life?'
    );
    console.log('Public response:', publicResponse);

    // Call with authentication
    const authenticatedResponse = await callNeuron(
      'my-org',
      'my-neuron',
      'What is the meaning of life?',
      'your-api-key'
    );
    console.log('Authenticated response:', authenticatedResponse);

    // Call with cache bypass
    const url = new URL('https://run.prompteus.com/my-org/my-neuron');
    url.searchParams.append('bypassCache', 'true');
    
    const noCacheResponse = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ input: 'Fresh response please' })
    });
    console.log('No cache response:', await noCacheResponse.json());

  } catch (error) {
    console.error('Example failed:', error);
  }
}

Query Parameters

The API supports the following query parameters:

ParameterTypeDescription
bypassCachebooleanWhen true, forces a new execution and bypasses both exact and semantic caching
rawOutputbooleanWhen true, returns the raw text output without any processing

Example with query parameters:

https://run.prompteus.com/<organization-slug>/<neuron-slug>?bypassCache=true&rawOutput=true

Authentication

If your Neuron requires authentication, you can provide it using the Authorization header:

Authorization: Bearer <your-jwt-or-api-key>

See Access Control for more details about authentication methods.

Response Format

A successful response will have this structure:

{
  output?: string;         // The generated output
  fromCache?: boolean;     // Whether the response was served from cache
  executionStopped?: boolean; // Whether execution was stopped prematurely
}

Error Handling

Errors are returned with appropriate HTTP status codes and a JSON response:

{
  error: string;      // Error message
  statusCode: number; // HTTP status code
}

The API uses standard HTTP status codes to indicate the success or failure of requests:

Status CodeDescriptionCommon Causes
400 Bad RequestInvalid request parameters• Malformed input JSON
• Missing required fields
401 UnauthorizedAuthentication failed• Invalid/expired token
• Malformed API key
• Missing authentication
403 ForbiddenAccess deniedAccess control restrictions
• IP not in allowed list
• Domain not in allowed referers
404 Not FoundResource not found• Neuron not found
• Deployment not found
• Organization not found
• Invalid neuron configuration
422 Unprocessable EntityValidation failed• Input validation failed
• Invalid parameter format
429 Too Many RequestsRate limit exceededRate limits exceeded
• Account paused (billing)
• Usage limits exceeded
500 Internal Server ErrorServer-side error• Unexpected server errors
• Missing deployment
• Configuration issues
503 Service UnavailableService down• Maintenance mode
• System overload
• Upstream service failures

For 429 responses, check the Retry-After header for the number of seconds to wait before retrying:

Retry-After: 120  # Seconds until the block expires

Error Handling Examples

Here’s how to handle errors in different languages:

try {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ input: 'Hello' })
  });

  if (!response.ok) {
    const error = await response.json();
    
    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After');
      console.log(`Rate limited. Retry after ${retryAfter} seconds`);
    }
    
    throw new Error(`API Error: ${error.error} (${response.status})`);
  }

  const data = await response.json();
  // Process successful response...

} catch (error) {
  console.error('Request failed:', error);
}

For production applications, we recommend implementing proper retry logic with exponential backoff, especially for 429 and 503 errors. See Rate Limiting for more details about handling rate limits.

TypeScript SDK

We provide an official TypeScript SDK for a more convenient integration experience.

Installation

npm install @prompteus-ai/neuron-runner

Authentication

The SDK supports both authenticated and unauthenticated calls, depending on your Neuron’s access control settings. Authentication is only required if your Neuron is configured to use API Key or JWT authentication.

If authentication is needed, you can provide it in multiple ways:

  1. During client creation:
const client = new Prompteus({ jwtOrApiKey: 'your-token' });
  1. Using the setter method:
client.setJwtOrApiKey('your-token');
  1. Per request:
await client.callNeuron('org', 'neuron', {
  input: 'Hello',
  jwtOrApiKey: 'your-token'
});

If your Neuron has public access enabled, you can omit the authentication token. The SDK will work without authentication for public Neurons.

Basic Usage

import { Prompteus } from '@prompteus-ai/neuron-runner';

// Create a client instance
const client = new Prompteus({
  jwtOrApiKey: 'your-jwt-token', // Optional
  baseURL: 'https://run.prompteus.com' // Optional, defaults to this value
});

// Call a neuron
try {
  const response = await client.callNeuron('your-org', 'your-neuron', {
    input: 'Hello, world!'
  });
  console.log(response);
} catch (error) {
  console.error(error);
}

Complete Example

Here’s a comprehensive example showing different ways to use the SDK:

import { Prompteus } from '@prompteus-ai/neuron-runner';

async function example() {
  // Create a client instance
  const client = new Prompteus({
    jwtOrApiKey: 'your-api-key', // Optional
    baseURL: 'https://run.prompteus.com' // Optional
  });

  try {
    // Basic call
    const basicResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'What is the meaning of life?'
      }
    );
    console.log('Basic response:', basicResponse);

    // Call with cache bypass and raw output
    const advancedResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Fresh response please',
        bypassCache: true,
        rawOutput: true
      }
    );
    console.log('Advanced response:', advancedResponse);

    // Call with different authentication
    const authenticatedResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Hello with different auth',
        jwtOrApiKey: 'different-api-key'
      }
    );
    console.log('Authenticated response:', authenticatedResponse);

    // Call with custom headers
    const customResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Hello with custom headers',
        headers: {
          'Custom-Header': 'value'
        }
      }
    );
    console.log('Custom response:', customResponse);

  } catch (error) {
    if ('statusCode' in error) {
      console.error(
        `API Error ${error.statusCode}: ${error.error}`
      );
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

Advanced Options

The callNeuron method accepts these options:

interface CallNeuronOptions {
  bypassCache?: boolean;  // Force new execution, bypass caching
  input?: string;        // Input text for the neuron
  rawOutput?: boolean;   // Return raw text output
  headers?: Record<string, string>; // Additional headers
  jwtOrApiKey?: string;  // Auth token for this request
}

Example with options:

const response = await client.callNeuron('org', 'neuron', {
  input: 'Hello',
  bypassCache: true,
  rawOutput: true,
  headers: {
    'Custom-Header': 'value'
  }
});

Type Safety

The SDK provides TypeScript types for all responses:

interface NeuronSuccessResponse {
  output?: string;
  fromCache?: boolean;
  executionStopped?: boolean;
}

interface NeuronErrorResponse {
  error: string;
  statusCode: number;
}

Error Handling

The SDK provides built-in error handling with TypeScript types, and exposes the error status code and message from the API. Here’s how to handle different error scenarios:

try {
  const response = await client.callNeuron('org', 'neuron', {
    input: 'Hello'
  });
  // Process successful response...

} catch (error) {
  if ('statusCode' in error) {
    // Handle specific error types
    switch (error.statusCode) {
      case 429:
        console.error('Rate limited:', error.error);
        // Implement retry logic
        break;
      case 401:
        console.error('Authentication failed:', error.error);
        // Refresh authentication
        break;
      default:
        console.error(`API Error ${error.statusCode}:`, error.error);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

The SDK throws typed errors that include both the error message and status code, making it easy to implement specific error handling logic for different scenarios.

Complete Example

Here’s a comprehensive example showing different ways to use the SDK:

import { Prompteus } from '@prompteus-ai/neuron-runner';

async function example() {
  // Create a client instance
  const client = new Prompteus({
    jwtOrApiKey: 'your-api-key', // Optional
    baseURL: 'https://run.prompteus.com' // Optional
  });

  try {
    // Basic call
    const basicResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'What is the meaning of life?'
      }
    );
    console.log('Basic response:', basicResponse);

    // Call with cache bypass and raw output
    const advancedResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Fresh response please',
        bypassCache: true,
        rawOutput: true
      }
    );
    console.log('Advanced response:', advancedResponse);

    // Call with different authentication
    const authenticatedResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Hello with different auth',
        jwtOrApiKey: 'different-api-key'
      }
    );
    console.log('Authenticated response:', authenticatedResponse);

    // Call with custom headers
    const customResponse = await client.callNeuron(
      'my-org',
      'my-neuron',
      {
        input: 'Hello with custom headers',
        headers: {
          'Custom-Header': 'value'
        }
      }
    );
    console.log('Custom response:', customResponse);

  } catch (error) {
    if ('statusCode' in error) {
      console.error(
        `API Error ${error.statusCode}: ${error.error}`
      );
    } else {
      console.error('Unexpected error:', error);
    }
  }
}