@bernierllc/chatkit-adapter
v1.2.0
Published
OpenAI ChatKit integration adapter with NeverHub and NeverAdmin support
Readme
@bernierllc/chatkit-adapter
OpenAI ChatKit integration adapter with NeverHub service discovery and NeverAdmin UI integration.
Installation
npm install @bernierllc/chatkit-adapterQuick Start
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);
}Features
- 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
Usage Examples
Basic Message Sending
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);
}Streaming Responses
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);
}
});Thread Management
// 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);File Attachments
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);
}NeverHub Integration
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 automaticallyHealth Monitoring
const health = await adapter.getHealth();
console.log('Status:', health.data?.status);
console.log('Metrics:', health.data?.metrics);
console.log('Checks:', health.data?.checks);API Reference
ChatKitAdapter
Main adapter class for OpenAI ChatKit integration.
Constructor
constructor(config?: Partial<ChatKitAdapterConfig>)Creates a new ChatKit adapter instance with optional configuration.
Methods
initialize(): Promise<ChatKitResult<boolean>>
Initializes the adapter with optional NeverHub detection.
sendMessage(params: SendMessageParams): Promise<ChatKitResult<ChatCompletionResponse>>
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<string, unknown>): Optional metadata
streamMessage(params: StreamMessageParams): Promise<ChatKitResult<void>>
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<ChatKitResult<ChatAttachment>>
Uploads a file attachment.
Parameters:
file(File): File to uploadpurpose('assistants' | 'fine-tune' | 'vision'): Upload purposemetadata?(Record<string, unknown>): Optional metadata
createThread(params?: CreateThreadParams): Promise<ChatKitResult<ChatThread>>
Creates a new conversation thread.
Parameters:
metadata?(Record<string, unknown>): Thread metadatainitialMessage?(string): Optional initial message
getThread(threadId: string): ChatKitResult<ChatThread>
Retrieves a thread by ID.
listThreads(params?: ListThreadsParams): ChatKitResult<ChatThread[]>
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<ChatKitResult<NeverHubHealthStatus>>
Gets current health status and metrics.
getConfig(): ChatKitAdapterConfig
Gets current configuration.
cleanup(): Promise<void>
Cleans up resources and unregisters from NeverHub.
Configuration
Environment Variables
# OpenAI Configuration
OPENAI_API_KEY=your-api-key
OPENAI_MODEL=gpt-4
OPENAI_MAX_TOKENS=4000
OPENAI_TEMPERATURE=0.7
# ChatKit Features
CHATKIT_STREAMING=true
CHATKIT_ATTACHMENTS=true
CHATKIT_THREADS=true
# Security
CHATKIT_RATE_LIMIT_PER_USER=100
CHATKIT_MAX_MESSAGE_LENGTH=4000
CHATKIT_TOKEN_EXPIRATION=900000
# NeverHub Integration
NEVERHUB_ENABLED=true
NEVERHUB_SERVICE_NAME=chatkit-adapterConfiguration Object
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<T> type:
interface ChatKitResult<T> {
success: boolean;
data?: T;
error?: string;
errorDetails?: ChatKitErrorDetails;
}Example error handling:
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
}
}Integration Status
- Logger: Not applicable - Uses console logging
- Docs-Suite: Ready - Markdown documentation with TypeScript API docs
- NeverHub: Integrated - Optional service discovery and event publishing
License
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.
See Also
- @bernierllc/neverhub-adapter - NeverHub integration
- @bernierllc/retry-policy - Retry logic
- @bernierllc/rate-limiter - Rate limiting
- @bernierllc/logger - Logging utilities
