npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cognitiveai-sdk

v0.2.0

Published

JavaScript/TypeScript SDK for CognitiveAI API

Readme

CognitiveAI JavaScript/TypeScript SDK

npm version TypeScript Node.js License: MIT

A comprehensive JavaScript/TypeScript SDK for the Neural Multi-Level Reasoning (CognitiveAI) API. Provides async support, error handling, and easy integration with web applications and Node.js projects.

Features

  • 🚀 Async/Await: Modern async patterns with full TypeScript support
  • 🔄 Auto Retry: Intelligent retry logic with exponential backoff
  • 🛡️ Error Handling: Comprehensive error handling with custom exception types
  • 📊 Job Management: Full support for async job monitoring and cancellation
  • 🔑 API Key Management: Create, list, and manage API keys programmatically
  • 📈 Grid Search: Efficient parameter optimization across beam/step combinations
  • 🌐 Isomorphic: Works in both browser and Node.js environments
  • 📦 Tree Shakeable: Only bundle what you use with ES modules

Installation

npm install cognitiveai-sdk
# or
yarn add cognitiveai-sdk
# or
pnpm add cognitiveai-sdk

Quick Start

Browser Usage

<!DOCTYPE html>
<html>
<head>
  <title>CognitiveAI SDK Example</title>
</head>
<body>
  <script type="module">
    import { CognitiveAIClient } from 'https://esm.sh/cognitiveai-sdk';

    async function main() {
      const client = new CognitiveAIClient({
        apiKey: 'your-api-key-here',
        baseUrl: 'http://localhost:8000' // For local development
      });

      try {
        const result = await client.search({
          prompt: 'What are the three laws of thermodynamics?',
          provider: 'mock'
        });

        console.log('Response:', result.response);
        console.log('Tokens used:', result.tokensUsed);
        console.log('Cost:', `$${result.cost}`);
      } catch (error) {
        console.error('Error:', error.message);
      }
    }

    main();
  </script>
</body>
</html>

Node.js Usage

import { CognitiveAIClient } from 'cognitiveai-sdk';

async function main() {
  // Configure the client
  const client = new CognitiveAIClient({
    apiKey: process.env.CognitiveAI_API_KEY!,
    baseUrl: 'http://localhost:8000', // Local development
    timeout: 60 // 60 seconds
  });

  // Perform search reasoning
  const result = await client.search({
    prompt: 'Explain quantum entanglement in simple terms',
    provider: 'mock',
    beam: 2,
    steps: 1
  });

  console.log(`Response: ${result.response}`);
  console.log(`Cost: $${result.cost}`);
}

main().catch(console.error);

Grid Search for Parameter Optimization

import { CognitiveAIClient, GridRequest } from 'cognitiveai-sdk';

async function optimizeParameters() {
  const client = new CognitiveAIClient({
    apiKey: process.env.CognitiveAI_API_KEY!,
    baseUrl: 'http://localhost:8000'
  });

  const request: GridRequest = {
    beams: [2, 3, 4],
    steps: [1, 2, 3],
    prompt: 'Solve this complex reasoning problem...',
    provider: 'mock'
  };

  const result = await client.gridSearch(request);

  console.log(`Tested ${result.results.length} combinations`);
  console.log(`Best result:`, result.bestResult);
  console.log(`Total cost: $${result.totalCost}`);
}

optimizeParameters().catch(console.error);

Convenience Functions

import { search, gridSearch } from 'cognitiveai-sdk';

// Quick search
const result = await search(
  'What is the capital of France?',
  process.env.CognitiveAI_API_KEY!,
  {
    provider: 'mock',
    baseUrl: 'http://localhost:8000'
  }
);
console.log(result.response);

// Quick grid search
const gridResult = await gridSearch(
  [2, 3], // beams
  [1, 2], // steps
  process.env.CognitiveAI_API_KEY!,
  'Test prompt', // optional
  {
    provider: 'mock',
    baseUrl: 'http://localhost:8000'
  }
);
console.log(gridResult.bestResult);

Advanced Usage

Custom Configuration

const client = new CognitiveAIClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://cognitiveai-api.fly.dev', // Production API
  timeout: 600, // 10 minutes
  maxRetries: 5,
  retryDelay: 2, // 2 seconds base delay
});

Job Management

import { CognitiveAIClient } from 'cognitiveai-sdk';

async function manageJobs() {
  const client = new CognitiveAIClient({
    apiKey: process.env.CognitiveAI_API_KEY!
  });

  // Start a long-running job
  const result = await client.search({
    prompt: 'Complex reasoning task that takes time...',
    beam: 4,
    steps: 3,
    provider: 'openai'
  });

  const jobId = result.jobId;
  console.log(`Job started: ${jobId}`);

  // Monitor progress
  while (true) {
    const status = await client.getJobStatus(jobId);
    console.log(`Status: ${status.status}`);

    if (status.progress !== undefined) {
      console.log(`Progress: ${(status.progress * 100).toFixed(1)}%`);
    }

    if (status.status === 'completed') {
      console.log('Job completed!');
      break;
    } else if (status.status === 'failed') {
      console.error(`Job failed: ${status.error}`);
      break;
    }

    // Wait before checking again
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
}

API Key Management

async function manageAPIKeys() {
  const client = new CognitiveAIClient({
    apiKey: process.env.CognitiveAI_MASTER_KEY!
  });

  // List existing keys
  const keys = await client.getAPIKeys();
  console.log('API Keys:');
  keys.forEach(key => {
    console.log(`- ${key.name} (${key.id})`);
  });

  // Create a new key
  const newKey = await client.createAPIKey(
    'My New SDK Key',
    ['read', 'write']
  );
  console.log(`Created key: ${newKey.key}`);

  // Delete a key
  // await client.deleteAPIKey(newKey.id);
}

Error Handling

import {
  CognitiveAIClient,
  CognitiveAIError,
  CognitiveAIAuthenticationError,
  CognitiveAIRateLimitError,
  CognitiveAIServerError
} from 'cognitiveai-sdk';

async function handleErrors() {
  const client = new CognitiveAIClient({
    apiKey: 'invalid-key'
  });

  try {
    await client.search('Test prompt');
  } catch (error) {
    if (error instanceof CognitiveAIAuthenticationError) {
      console.error('Invalid API key');
    } else if (error instanceof CognitiveAIRateLimitError) {
      console.error('Rate limit exceeded, please wait');
    } else if (error instanceof CognitiveAIServerError) {
      console.error('Server error, please try again later');
    } else if (error instanceof CognitiveAIError) {
      console.error(`CognitiveAI error: ${error.message}`);
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

API Reference

CognitiveAIClient

Main client class for interacting with the CognitiveAI API.

Constructor

new CognitiveAIClient(config: CognitiveAIConfig)

Methods

  • search(request: SearchRequest | string): Promise<SearchResult>
  • gridSearch(request: GridRequest): Promise<GridResult>
  • getJobStatus(jobId: string): Promise<JobStatus>
  • listJobs(options?: { limit?, offset?, status? }): Promise<JobStatus[]>
  • cancelJob(jobId: string): Promise<boolean>
  • getAPIKeys(): Promise<APIKey[]>
  • createAPIKey(name: string, permissions?: string[]): Promise<APIKey & { key: string }>
  • deleteAPIKey(keyId: string): Promise<boolean>

Interfaces

CognitiveAIConfig

interface CognitiveAIConfig {
  apiKey: string;
  baseUrl?: string;
  timeout?: number;
  maxRetries?: number;
  retryDelay?: number;
}

SearchRequest

interface SearchRequest {
  prompt: string;
  provider?: string;
  beam?: number;
  steps?: number;
  temperature?: number;
  maxTokens?: number;
  model?: string;
}

GridRequest

interface GridRequest {
  beams: number[];
  steps: number[];
  prompt?: string;
  provider?: string;
  temperature?: number;
  maxTokens?: number;
  model?: string;
}

Exception Classes

  • CognitiveAIError: Base exception for all CognitiveAI errors
  • CognitiveAIAuthenticationError: Invalid API key (401)
  • CognitiveAIRateLimitError: Rate limit exceeded (429)
  • CognitiveAIServerError: Server errors (5xx)

Development

Setup

git clone https://github.com/cognitiveai/cognitiveai-javascript-sdk.git
cd cognitiveai-javascript-sdk
npm install

Build

npm run build

Test

npm test

Type Checking

npm run typecheck

Linting

npm run lint
npm run lint:fix

Examples

See the examples/ directory for more comprehensive examples:

  • Basic usage patterns
  • Error handling
  • Job management
  • API key management
  • Integration with popular frameworks

Browser Support

  • Chrome 80+
  • Firefox 74+
  • Safari 13+
  • Edge 80+

Node.js Support

  • Node.js 14+

Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

See CHANGELOG.md for version history and updates.