OpenAI ChatKit integration adapter with NeverHub and NeverAdmin support
npm install @bernierllc/chatkit-adapterOpenAI ChatKit integration adapter with NeverHub service discovery and NeverAdmin UI integration.
``bash`
npm install @bernierllc/chatkit-adapter
`typescript
import { ChatKitAdapter } from '@bernierllc/chatkit-adapter';
// Create adapter with configuration
const adapter = new ChatKitAdapter({
openai: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4',
maxTokens: 4000,
temperature: 0.7
}
});
// Initialize (auto-detects NeverHub)
await adapter.initialize();
// Send a message
const result = await adapter.sendMessage({
content: 'Hello, how can I help you?'
});
if (result.success) {
console.log(result.data.content);
}
`
- OpenAI ChatKit Integration: Full support for OpenAI chat completions
- Real-time Streaming: Server-Sent Events (SSE) streaming support
- File Attachments: Upload and process file attachments
- Thread Management: Conversation threading and context preservation
- NeverHub Integration: Optional service discovery and event publishing
- Security: Built-in rate limiting, input validation, and token management
- TypeScript: Full TypeScript support with strict typing
`typescript
import { ChatKitAdapter } from '@bernierllc/chatkit-adapter';
const adapter = new ChatKitAdapter({
openai: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4'
}
});
await adapter.initialize();
const result = await adapter.sendMessage({
content: 'What is the capital of France?'
});
if (result.success) {
console.log('Answer:', result.data?.content);
}
`
`typescript
const adapter = new ChatKitAdapter({
openai: {
apiKey: process.env.OPENAI_API_KEY || ''
},
features: {
streaming: true
}
});
await adapter.initialize();
await adapter.streamMessage({
content: 'Tell me a story',
onChunk: (chunk) => {
process.stdout.write(chunk);
},
onComplete: () => {
console.log('\nStream complete!');
},
onError: (error) => {
console.error('Stream error:', error);
}
});
`
`typescript
// Create a new thread
const threadResult = await adapter.createThread({
metadata: {
userId: 'user123',
title: 'Customer Support'
},
initialMessage: 'I need help with my account'
});
const threadId = threadResult.data?.id;
// Send messages in thread
await adapter.sendMessage({
content: 'My account is locked',
threadId
});
await adapter.sendMessage({
content: 'Can you help me unlock it?',
threadId
});
// Get thread history
const thread = adapter.getThread(threadId!);
console.log('Messages:', thread.data?.messages);
`
`typescript
const file = new File(['content'], 'document.pdf', { type: 'application/pdf' });
const uploadResult = await adapter.uploadFile({
file,
purpose: 'assistants'
});
if (uploadResult.success) {
console.log('File uploaded:', uploadResult.data?.id);
}
`
`typescript
const adapter = new ChatKitAdapter({
openai: {
apiKey: process.env.OPENAI_API_KEY || ''
},
neverhub: {
enabled: true,
serviceName: 'chatkit-adapter',
capabilities: [
{ type: 'chat', name: 'openai-chatkit', version: '1.0.0' }
],
dependencies: ['auth', 'logging']
}
});
await adapter.initialize();
// NeverHub will auto-detect and register
// Events will be published automatically
`
`typescript
const health = await adapter.getHealth();
console.log('Status:', health.data?.status);
console.log('Metrics:', health.data?.metrics);
console.log('Checks:', health.data?.checks);
`
Main adapter class for OpenAI ChatKit integration.
#### Constructor
`typescript`
constructor(config?: Partial
Creates a new ChatKit adapter instance with optional configuration.
#### Methods
##### initialize(): Promise
Initializes the adapter with optional NeverHub detection.
##### sendMessage(params: SendMessageParams): Promise
Sends a chat message and receives a completion response.
Parameters:
- content (string): Message contentthreadId?
- (string): Optional thread ID for contextattachments?
- (File[]): Optional file attachmentsmetadata?
- (Record
##### streamMessage(params: StreamMessageParams): Promise
Streams a chat message with real-time responses.
Parameters:
- content (string): Message contentthreadId?
- (string): Optional thread IDonChunk?
- (function): Callback for each chunkonComplete?
- (function): Callback on completiononError?
- (function): Callback on error
##### uploadFile(params: UploadFileParams): Promise
Uploads a file attachment.
Parameters:
- file (File): File to uploadpurpose
- ('assistants' | 'fine-tune' | 'vision'): Upload purposemetadata?
- (Record
##### createThread(params?: CreateThreadParams): Promise
Creates a new conversation thread.
Parameters:
- metadata? (RecordinitialMessage?
- (string): Optional initial message
##### getThread(threadId: string): ChatKitResult
Retrieves a thread by ID.
##### listThreads(params?: ListThreadsParams): ChatKitResult
Lists all threads with optional filtering.
Parameters:
- limit? (number): Maximum threads to returnoffset?
- (number): Offset for paginationuserId?
- (string): Filter by user IDtags?
- (string[]): Filter by tags
##### getHealth(): Promise
Gets current health status and metrics.
##### getConfig(): ChatKitAdapterConfig
Gets current configuration.
##### cleanup(): Promise
Cleans up resources and unregisters from NeverHub.
`bashOpenAI Configuration
OPENAI_API_KEY=your-api-key
OPENAI_MODEL=gpt-4
OPENAI_MAX_TOKENS=4000
OPENAI_TEMPERATURE=0.7
$3
`typescript
interface ChatKitAdapterConfig {
enabled: boolean;
openai: OpenAIConfig;
features: FeatureConfig;
security: SecurityConfig;
neverhub?: NeverHubConfig;
neveradmin?: NeverAdminConfig;
ai?: AIConfig;
}
`See types documentation for complete configuration schema.
Error Handling
All methods return a
ChatKitResult type:`typescript
interface ChatKitResult {
success: boolean;
data?: T;
error?: string;
errorDetails?: ChatKitErrorDetails;
}
`Example error handling:
`typescript
const result = await adapter.sendMessage({ content: 'Hello' });if (!result.success) {
console.error('Error:', result.error);
console.error('Details:', result.errorDetails);
if (result.errorDetails?.retryable) {
// Retry logic
}
}
``- Logger: Not applicable - Uses console logging
- Docs-Suite: Ready - Markdown documentation with TypeScript API docs
- NeverHub: Integrated - Optional service discovery and event publishing
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license.
The client may use and modify this code only within the scope of the project it was delivered for.
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
- @bernierllc/neverhub-adapter - NeverHub integration
- @bernierllc/retry-policy - Retry logic
- @bernierllc/rate-limiter - Rate limiting
- @bernierllc/logger - Logging utilities