@codeswayam/neural
v1.1.3
Published
[](https://www.npmjs.com/package/@codeswayam/neural) [](https://opensource.
Readme
@codeswayam/neural
The official SDK for integrating NeuralHub AI into any app — agents, image generation, knowledge bases, workflows, and stateless completions. Works for both internal CodeSwayam platform apps and external developers building on NeuralHub.
Table of Contents
- Overview
- Installation
- Entry Points
- Peer Dependencies
- Quick Start
- Platform Adapter API (
/platform) - NeuralClient API Reference
- React Hooks
- TypeScript Types
- Code Examples
- Error Handling
- Compatibility Matrix
Overview
@codeswayam/neural is the official TypeScript SDK for the NeuralHub platform. It ships three separate entry points for different use cases:
| Entry Point | Who Uses It | Purpose |
|---|---|---|
| @codeswayam/neural | External developers, advanced use | Core NeuralClient — full API access |
| @codeswayam/neural/react | Frontend apps | React hooks built on top of the core client |
| @codeswayam/neural/platform | Internal CodeSwayam apps (AuraFlow, PDFCraft, etc.) | Drop-in adapter replacing lib/platform/neural.ts in every app |
All entry points are available as CommonJS and ESM modules with full TypeScript declarations.
Installation
# npm
npm install @codeswayam/neural
# yarn
yarn add @codeswayam/neural
# pnpm
pnpm add @codeswayam/neuralEntry Points
// Core client — full API access for external developers
import NeuralClient from '@codeswayam/neural';
// React hooks
import { useNeuralChat, NeuralProvider } from '@codeswayam/neural/react';
// Platform adapter — for internal CodeSwayam apps (replaces lib/platform/neural.ts)
import { createPlatformNeural, buildPersonaPrompt } from '@codeswayam/neural/platform';Peer Dependencies
| Dependency | Version | Required for |
|---|---|---|
| axios | ^1.6.0 | Core HTTP transport |
| react | ^18.0.0 \|\| ^19.0.0 | React hooks (/react entry point only) |
| react-dom | ^18.0.0 \|\| ^19.0.0 | React hooks (/react entry point only) |
# Core SDK only (no React)
npm install axios
# Core SDK + React hooks
npm install axios react react-domQuick Start
Internal Platform Apps
For CodeSwayam internal apps (AuraFlow, PDFCraft, PixelForge, etc.), use the Platform Adapter.
This replaces the duplicated lib/platform/neural.ts file that used to be copied into every app.
// lib/platform/neural.ts — in any CodeSwayam app (15 lines, replaces 200+)
import { createPlatformNeural, buildPersonaPrompt } from "@codeswayam/neural/platform";
import type { ChatOptions, PlatformChatResult } from "@codeswayam/neural/platform";
const neural = createPlatformNeural({ app: "your-app-slug" });
export const PlatformNeuralService = neural; // backward compat
export { buildPersonaPrompt };
export type { ChatOptions, PlatformChatResult };
export function getNeuralClient() { return neural.raw; }
export default neural;// Usage anywhere in your app
import { PlatformNeuralService, buildPersonaPrompt } from "@/lib/platform/neural";
// AI with memory (entity-bound, auto-provisioned agent)
const reply = await PlatformNeuralService.chat(
listenerId, // entity ID — unique per automation/bot
userMessage, // incoming message text
sessionId, // conversation session ID
{
systemPrompt: buildPersonaPrompt("SALES_CLOSER", listener.prompt, { brandName: "Acme" }),
knowledgeBaseId: listener.neuralKbId,
userId: integration.userId,
fallbackReply: "Thanks! We'll get back to you shortly.",
}
);
// Stateless AI (no agent, no memory — for document processing, etc.)
const summary = await PlatformNeuralService.complete(documentText, {
systemPrompt: "Summarize in 3 bullet points.",
});External Developers
Sign up at neural.codeswayam.com, get an API key, and integrate in minutes:
import NeuralClient from '@codeswayam/neural';
const neural = new NeuralClient({
apiKey: 'nhub_live_your_api_key_here',
baseUrl: 'https://core.codeswayam.com', // production
});
// AI agent with memory — remembers conversation history per entity
const reply = await neural.chat({
app: 'my-app',
entityId: 'customer-123',
prompt: 'You are a helpful customer support agent for Acme Corp.',
message: userMessage,
sessionId: `session-${userId}`,
});
// Stateless completion — no agent, just raw LLM
const summary = await neural.complete({
message: 'Summarize: ' + documentText,
systemPrompt: 'You are a professional document summarizer.',
});Platform Adapter API (/platform)
The /platform entry point is designed for CodeSwayam internal apps. It provides a
pre-configured adapter with graceful fallbacks, singleton caching, and backward-compatible
method signatures.
createPlatformNeural
import { createPlatformNeural } from "@codeswayam/neural/platform";
const neural = createPlatformNeural({
app: "auraflow", // Your app slug (registered in core-api)
apiKey?: string, // Falls back to NEURAL_API_KEY env var
baseUrl?: string, // Falls back to NEURAL_API_URL or NEXT_PUBLIC_API_URL env var
});Returns a PlatformNeuralAdapter singleton (cached per app + baseUrl).
chat
Entity-bound chat with automatic agent provisioning and memory.
On first call for (app, entityId), core-api auto-creates an agent tagged managedByApp = app.
Subsequent calls reuse the same agent, syncing config if changed.
const reply: string = await neural.chat(
entityId, // Unique entity ID in your app (e.g. listener.id, automation.id)
message, // User's incoming message
sessionId, // Conversation session ID (for multi-turn history)
{
systemPrompt?: string, // AI persona/instructions
knowledgeBaseId?: number, // RAG knowledge base to attach
userId?: number, // End-user ID for credit attribution
name?: string, // Human-readable agent name (for auto-provisioning)
model?: string, // Override default model (e.g. "gemini-2.0-flash")
fallbackReply?: string, // Returned if AI credits are exhausted
}
);Security & Key Pool Resilience: Agents created via
createPlatformNeuralor taggedmanagedByApputilize the platform's shared API key pool. In Core-API, these agents enforce model whitelisting (allowedModels), preventing non-admin users from binding unauthorized BYOK models, while the rotation strategy automatically isolates and revokes corrupted keys.
chatWithDetails
Same as chat but returns the full result including fallback info — useful for conditional usage tracking.
const result: PlatformChatResult = await neural.chatWithDetails(entityId, message, sessionId, options);
// result.text — AI response text
// result.fallbackUsed — true if static fallback was returned (credits exhausted, error, etc.)
// result.reason — "INSUFFICIENT_CREDITS" | "ERROR" | undefinedcomplete (Stateless)
Direct LLM call — no agent, no memory, no session. Ideal for document processing, text transformation, one-off generation.
const text: string = await neural.complete(message, {
systemPrompt?: string, // Optional role/instructions
model?: string, // Override model
userId?: number, // For credit attribution
});generateImage
const img = await neural.generateImage(prompt, {
aspectRatio?: string, // "1:1" | "16:9" | "4:3" | etc.
negativePrompt?: string,
userId?: number,
});
// img.imageBase64 — base64 encoded image
// img.mimeType — "image/png"runWorkflow
Execute a multi-agent workflow by slug or numeric ID.
const result = await neural.runWorkflow("lead-qualifier", {
email: "[email protected]",
subject: "Billing question",
});getKnowledgeBaseStatus
const status = await neural.getKnowledgeBaseStatus(kbId);
// status?.kbName — "My Knowledge Base"
// status?.docCount — 42
// status?.status — "active" | "indexing" | "error"
// null if not found (safe to ignore)Persona Prompts
import {
buildPersonaPrompt,
registerPersona,
PersonaType,
} from "@codeswayam/neural/platform";
// Built-in personas
buildPersonaPrompt("DEFAULT", customPrompt);
buildPersonaPrompt("SALES_CLOSER", customPrompt, { brandName: "Acme", products: "Widget Pro" });
buildPersonaPrompt("CUSTOMER_SUPPORT", customPrompt, { brandName: "Acme" });
buildPersonaPrompt("INFLUENCER_COMPANION", customPrompt);
// Register a custom persona for your app (no SDK changes needed)
registerPersona("REAL_ESTATE_AGENT", (prompt, ctx) =>
`You are a real estate agent for ${ctx?.brandName}. ${prompt || ""}`
);
// Use it anywhere
buildPersonaPrompt("REAL_ESTATE_AGENT", listener.prompt, { brandName: "Sunrise Realty" });NeuralClient API Reference
Configuration
import NeuralClient from '@codeswayam/neural';
const client = new NeuralClient({
apiKey: 'nhub_live_your_key', // Required — get from neural.codeswayam.com
baseUrl?: 'https://core.codeswayam.com', // Default: http://localhost:3000
timeout?: 30000, // Request timeout in ms. Default: 30000
});Note: The
core-apiis on port 3000. In production, setbaseUrlto your deployment URL.
Agents
| Method | Signature | Description |
|---|---|---|
| list | (options?) => Promise<Agent[]> | List all agents in your account |
| get | (agentId: string) => Promise<Agent> | Fetch a single agent by ID |
| create | (dto: CreateAgentDto) => Promise<Agent> | Create a new agent |
| update | (agentId: string, dto) => Promise<Agent> | Update an existing agent |
| delete | (agentId: string) => Promise<void> | Delete an agent permanently |
| chat | (agentId: string, message: string, params?) => Promise<ChatResponse> | Send a message to an agent |
Entity Chat (Auto-Provisioning)
The recommended integration pattern for all apps — agents are auto-created on first use and reused on subsequent calls with no manual agent management.
// Auto-provisions an agent for (app="my-app", entityId="bot-1") on first call
const response = await client.chat({
app: 'my-app',
entityId: 'bot-1',
prompt: 'You are a helpful assistant.',
message: userMessage,
sessionId: `session-${userId}`,
knowledgeBaseId: 42, // optional RAG knowledge base
fallbackReply: 'Be right back!', // returned if credits exhausted
});
console.log(response.text); // AI reply
console.log(response.fallbackUsed); // true if fallback was usedEntityChatParams:
| Param | Type | Description |
|---|---|---|
| app | string | Your app slug (e.g. "auraflow") |
| entityId | string | Unique entity ID in your app |
| message | string | User's incoming message |
| prompt | string? | System prompt / persona instructions |
| sessionId | string? | Conversation session ID for multi-turn memory |
| knowledgeBaseId | number? | RAG knowledge base to attach |
| userId | number? | End-user ID for credit attribution |
| model | string? | Override model (e.g. "gemini-2.0-flash") |
| fallbackReply | string? | Static reply if AI credits are exhausted |
| name | string? | Human-readable name for auto-provisioned agent |
Stateless Completion
For apps that need simple "prompt in → text out" without agent lifecycle management.
const response = await client.complete({
message: 'Summarize this document: ' + documentText,
systemPrompt: 'Return 3 bullet points.',
model: 'gemini-2.0-flash', // optional
userId: 123, // optional, for credit attribution
});
console.log(response.text);Models
| Method | Signature | Description |
|---|---|---|
| list | () => Promise<Model[]> | List all available models |
| get | (modelId: string) => Promise<Model> | Get details for a specific model |
Images
| Method | Signature | Description |
|---|---|---|
| generate | (prompt: string, params?) => Promise<ImageResponse> | Generate an image from a text prompt |
ImageResponse:
| Field | Type | Description |
|---|---|---|
| imageBase64 | string? | Base64-encoded image data |
| mimeType | string? | MIME type (e.g., image/png) |
| error | string? | Error message if generation failed |
Workflows
| Method | Signature | Description |
|---|---|---|
| list | () => Promise<Workflow[]> | List all workflows |
| run | (workflowId: string \| number, input: any) => Promise<WorkflowRunResponse> | Execute a workflow |
WorkflowRunResponse:
| Field | Type | Description |
|---|---|---|
| executionId | string? | Unique ID for this workflow run |
| output | any | Workflow output data |
| status | 'completed' \| 'failed' \| 'pending' | Execution status |
| error | string? | Error message if the run failed |
Knowledge Base
| Method | Signature | Description |
|---|---|---|
| list | () => Promise<KnowledgeBase[]> | List all knowledge bases |
| get | (kbId: number) => Promise<KnowledgeBase> | Get a specific knowledge base |
| query | (kbId: number, query: string, topK?) => Promise<string> | Semantic search |
| upload | (kbId: number, file: File) => Promise<void> | Upload a document |
API Keys
Manage API keys for your account. Tenant-scoped keys can issue sub-keys for their end-users.
| Method | Signature | Description |
|---|---|---|
| list | () => Promise<ApiKey[]> | List all API keys |
| create | (name: string) => Promise<ApiKey & { key: string }> | Create a new API key (raw key shown once) |
| revoke | (keyId: string) => Promise<void> | Revoke an API key permanently |
| issue | (dto) => Promise<ApiKey & { key: string }> | Issue a tenant sub-key for an end-user |
Analytics
| Method | Signature | Description |
|---|---|---|
| getUsage | (params?) => Promise<UsageStats> | Fetch token usage, request counts, and cost data |
React Hooks
import {
NeuralProvider,
useNeuralAgent,
useNeuralChat,
useNeuralWorkflow,
useNeuralModels,
useImageGeneration,
} from '@codeswayam/neural/react';Wrap your app
// app/layout.tsx or _app.tsx
<NeuralProvider config={{ apiKey: "nhub_live_...", baseUrl: "https://core.codeswayam.com" }}>
{children}
</NeuralProvider>Hook Reference
| Hook | Description |
|---|---|
| useNeuralAgent(agentId) | Fetch and manage a single agent's state |
| useNeuralChat(agentId, options?) | Chat interface with real-time message history |
| useNeuralWorkflow(workflowId) | Run and track workflow execution state |
| useNeuralModels() | Fetch all available models |
| useImageGeneration(agentId) | Manage image generation state and results |
TypeScript Types
// Platform Adapter
interface PlatformNeuralConfig {
app: string; // App slug: "auraflow", "pdfcraft", etc.
apiKey?: string; // Falls back to NEURAL_API_KEY env var
baseUrl?: string; // Falls back to NEURAL_API_URL or NEXT_PUBLIC_API_URL
}
interface ChatOptions {
systemPrompt?: string;
knowledgeBaseId?: number;
userId?: number;
name?: string;
model?: string;
fallbackReply?: string;
}
interface PlatformChatResult {
text: string;
fallbackUsed: boolean;
reason?: string; // "INSUFFICIENT_CREDITS" | "RATE_LIMITED" | "ERROR"
}
// Entity-Bound Chat (External SDK)
interface EntityChatParams {
app: string;
entityId: string;
entityType?: string;
name?: string;
prompt?: string;
message: string;
sessionId?: string;
knowledgeBaseId?: number;
model?: string;
userId?: number;
fallbackReply?: string;
}
// Stateless Completion
interface StatelessCompletionParams {
message: string;
systemPrompt?: string;
model?: string;
userId?: number;
}
interface ChatResponse {
text: string;
usage: { tokensIn: number; tokensOut: number };
latencyMs: number;
model: string;
fallbackUsed?: boolean;
reason?: string;
}
interface ImageResponse {
imageBase64?: string;
mimeType?: string;
error?: string;
}
interface WorkflowRunResponse {
executionId?: string;
output?: any;
status: 'completed' | 'failed' | 'pending';
error?: string;
}
interface Agent {
id: string;
name: string;
app: string;
model: string;
status: 'active' | 'inactive';
managedByApp?: string; // Set when auto-created by a platform app
description?: string;
createdAt: string;
}
interface KnowledgeBase {
id: number;
name: string;
docCount: number;
status: 'active' | 'indexing' | 'error';
createdAt: string;
}
// Persona types
type PersonaType =
| 'DEFAULT'
| 'SALES_CLOSER'
| 'CUSTOMER_SUPPORT'
| 'INFLUENCER_COMPANION'
| string; // Custom registered personasCode Examples
1. Internal App Integration (Platform Adapter)
// lib/platform/neural.ts — in AuraFlow, PDFCraft, PixelForge, etc.
import { createPlatformNeural, buildPersonaPrompt } from "@codeswayam/neural/platform";
import type { ChatOptions, PlatformChatResult } from "@codeswayam/neural/platform";
const neural = createPlatformNeural({ app: "auraflow" });
export const PlatformNeuralService = neural;
export { buildPersonaPrompt };
export type { ChatOptions, PlatformChatResult };
export function getNeuralClient() { return neural.raw; }
export default neural;// In your webhook handler, server action, etc.
import { PlatformNeuralService, buildPersonaPrompt } from "@/lib/platform/neural";
const chatResult = await PlatformNeuralService.chatWithDetails(
listener.id,
incomingMessage,
`session-${conversationId}`,
{
systemPrompt: buildPersonaPrompt("SALES_CLOSER", listener.prompt, {
brandName: integration.username || "our brand",
}),
knowledgeBaseId: listener.neuralKbId ?? undefined,
userId: integration.userId,
fallbackReply: listener.dmReply || "We'll get back to you shortly!",
}
);
if (!chatResult.fallbackUsed) {
// Only track AI usage when AI actually responded
trackPlatformUsage("ai_responses", 1, userId, "async");
}
await sendDm(chatResult.text);2. Stateless Completion (No Agent, No Memory)
// Great for PDFCraft document summarization, PixelForge caption generation, etc.
import { createPlatformNeural } from "@codeswayam/neural/platform";
const neural = createPlatformNeural({ app: "pdfcraft" });
const summary = await neural.complete(documentText, {
systemPrompt: "You are a professional document summarizer. Return exactly 3 bullet points.",
model: "gemini-2.0-flash",
});
console.log(summary);
// • First key point...
// • Second key point...
// • Third key point...3. External Developer — Multi-Turn Chat
import NeuralClient from '@codeswayam/neural';
const neural = new NeuralClient({
apiKey: process.env.NEURALHUB_API_KEY!,
baseUrl: 'https://core.codeswayam.com',
});
const SESSION_ID = crypto.randomUUID();
// Turn 1
const turn1 = await neural.chat({
app: 'my-support-bot',
entityId: 'customer-456',
prompt: 'You are a friendly customer support agent for TechCorp.',
message: 'My name is Alice and I need help with my order.',
sessionId: SESSION_ID,
});
console.log(turn1.text);
// Turn 2 — agent remembers Alice and TechCorp
const turn2 = await neural.chat({
app: 'my-support-bot',
entityId: 'customer-456',
message: 'What is the return policy?',
sessionId: SESSION_ID, // same session = same memory context
});
console.log(turn2.text);4. React Hook — Chat Interface
import { NeuralProvider, useNeuralChat } from '@codeswayam/neural/react';
// Wrap your app
function App() {
return (
<NeuralProvider config={{ apiKey: "nhub_live_...", baseUrl: "https://core.codeswayam.com" }}>
<ChatPage agentId="my-support-bot" />
</NeuralProvider>
);
}
// Use the hook
function ChatPage({ agentId }: { agentId: string }) {
const { messages, sendMessage, isLoading, error } = useNeuralChat(agentId, {
sessionId: 'my-session',
});
const [input, setInput] = React.useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim()) return;
await sendMessage(input);
setInput('');
};
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{messages.map((msg, i) => (
<div key={i} className={msg.role === 'user' ? 'bg-blue-100 ml-auto p-3 rounded-lg' : 'bg-gray-100 p-3 rounded-lg'}>
{msg.content}
</div>
))}
{isLoading && <div className="text-gray-400 animate-pulse">Thinking...</div>}
{error && <div className="text-red-500">Error: {error.message}</div>}
</div>
<form onSubmit={handleSubmit} className="p-4 border-t flex gap-2">
<input value={input} onChange={e => setInput(e.target.value)} placeholder="Type a message..." className="flex-1 border rounded px-3 py-2" />
<button type="submit" disabled={isLoading} className="px-4 py-2 bg-blue-600 text-white rounded">Send</button>
</form>
</div>
);
}5. Tenant Sub-Key Management
External SaaS developers can issue sub-keys for their own end-users:
// Issue a sub-key for a specific user (charges roll up to your tenant account)
const subKey = await neural.keys.issue({
name: `user-${userId}`,
rateLimit: 500, // requests per day for this user
});
// Give subKey.key to your user — they can make API calls with it
// All charges are billed to your tenant account6. Custom Persona Registration
import { registerPersona, buildPersonaPrompt } from "@codeswayam/neural/platform";
// Register once in your app's initialization (e.g. lib/neural.ts)
registerPersona("MORTGAGE_ADVISOR", (prompt, ctx) => [
`You are an expert mortgage advisor for ${ctx?.brandName || "our firm"}.`,
"Provide clear, accurate information about mortgage products and rates.",
"Never provide specific financial advice — always recommend consulting a licensed advisor.",
prompt ? `Additional context: ${prompt}` : "",
].filter(Boolean).join("\n"));
// Use anywhere in your app
const systemPrompt = buildPersonaPrompt("MORTGAGE_ADVISOR", listener.prompt, {
brandName: "First National Bank",
});7. Image Generation
const result = await neural.generateImage(
'A futuristic cityscape at sunset with flying vehicles, cinematic lighting, 8K',
{ aspectRatio: '16:9' }
);
if (!result.error) {
const dataUrl = `data:${result.mimeType};base64,${result.imageBase64}`;
// render in <img src={dataUrl} />
}8. API Key Management
// Create a new key (save immediately — shown only once)
const { name, key } = await client.apiKeys.create('my-production-app');
console.log(`Created: ${key}`); // nhub_live_...
// List keys (raw values never returned)
const keys = await client.apiKeys.list();
keys.forEach(k => console.log(`${k.name} — last used: ${k.lastUsed ?? 'never'}`));
// Revoke
await client.apiKeys.revoke('123');9. Usage Analytics
const stats = await client.analytics.getUsage({
from: '2025-09-01',
to: '2025-09-30',
});
console.log(`Requests: ${stats.totalRequests.toLocaleString()}`);
console.log(`Tokens In: ${stats.totalTokensIn.toLocaleString()}`);
console.log(`Tokens Out: ${stats.totalTokensOut.toLocaleString()}`);
console.log(`Est. Cost: $${stats.estimatedCostUsd.toFixed(4)}`);Error Handling
import NeuralClient from '@codeswayam/neural';
const client = new NeuralClient({ apiKey: process.env.NEURALHUB_API_KEY! });
try {
const response = await client.chat({ app: 'my-app', entityId: 'bot-1', message: 'Hello' });
console.log(response.text);
} catch (error: any) {
console.error(`Error ${error?.status}: ${error?.message}`);
}Platform Adapter (
/platform) handles errors internally and returns thefallbackReplyinstead of throwing. This prevents silent failures in production webhook handlers where any thrown error could leave a user without a response.
Common HTTP status codes:
| Status | Meaning |
|---|---|
| 401 | Invalid or expired API key |
| 403 | Insufficient permissions (wrong key scope) |
| 404 | Agent / resource not found |
| 429 | Rate limit exceeded |
| 500 | NeuralHub internal server error |
API Key Scopes
NeuralHub supports three API key scopes for different integration scenarios:
| Scope | Who Uses It | Created By | Data Access |
|---|---|---|---|
| platform | Internal CodeSwayam apps (AuraFlow, PDFCraft) | Admin | Only their managed agents (managedByApp) |
| user | External developers | Self-service (Neural Web) | Only their own agents, KB, workflows |
| tenant | External SaaS builders | Admin-approved | Their own data + can issue sub-keys for their users |
Compatibility Matrix
| Environment | Supported | Notes |
|---|---|---|
| Node.js 18.x | ✅ | Full support |
| Node.js 20.x | ✅ | Full support (recommended) |
| Node.js 22.x | ✅ | Full support |
| React 18.x | ✅ | Hooks entry point |
| React 19.x | ✅ | Hooks entry point |
| Next.js 14 (App Router) | ✅ | Server Components + Client Components |
| Next.js 15 | ✅ | Full support |
| Edge Runtime | ✅ | Core client + platform adapter (no React hooks) |
| Browsers (ESM) | ✅ | Bundle with Vite / Webpack |
| CommonJS (require) | ✅ | Dual-package exports |
| TypeScript 4.x | ✅ | Minimum required |
| TypeScript 5.x | ✅ | Recommended |
Changelog
v1.1.3
- Multi-Tenant Platform Keys: Platform-scoped API keys can now execute and update managed agents across all users within that platform application.
- Resilient Key Fallback: The gateway automatically falls back to provider environment keys (
GEMINI_API_KEY) when database rotation pools are exhausted or revoked. - End-User Credit Alignment: End-user credit deduction support when platform keys invoke AI agents on behalf of a specific user.
License
MIT © CodeSwayam
