cognitiveai-sdk
v0.2.0
Published
JavaScript/TypeScript SDK for CognitiveAI API
Maintainers
Readme
CognitiveAI JavaScript/TypeScript SDK
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-sdkQuick 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 errorsCognitiveAIAuthenticationError: 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 installBuild
npm run buildTest
npm testType Checking
npm run typecheckLinting
npm run lint
npm run lint:fixExamples
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.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- 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.
