# @veritas/developer-support

AI-powered developer support chatbot for the Veritas B2B API.

## Overview

This package provides an intelligent chatbot that helps developers integrate
with the Veritas B2B API. It uses OpenRouter-backed OpenAI-compatible large
language models combined with a curated knowledge base to provide accurate,
contextual answers to developer questions.

## Features

- **AI-Powered Responses**: Uses OpenRouter/OpenAI-compatible chat models for
  natural language understanding
- **Knowledge Base**: Built-in documentation for all API endpoints
- **Code Examples**: Provides code snippets in JavaScript/TypeScript and Python
- **Conversation Memory**: Maintains context across multiple messages
- **Topic Detection**: Automatically categorizes questions by topic
- **Escalation Support**: Seamlessly hand off to human support when needed
- **Embeddable Widget**: Drop-in chat widget for documentation sites
- **Analytics**: Track usage, satisfaction, and common questions

## Installation

```bash
pnpm add @veritas/developer-support
```

## Quick Start

### Basic Usage

```typescript
import { createChatbot } from '@veritas/developer-support';

const chatbot = createChatbot({
  apiKey: process.env.OPENROUTER_API_KEY!,
  model: 'deepseek/deepseek-v4-flash',
});

// Start a conversation
const conversation = await chatbot.startConversation();

// Send a message
const response = await chatbot.chat(
  conversation.id,
  'How do I authenticate with the API?'
);

console.log(response.message.content);
// Response includes code examples, documentation links, etc.

// Provide feedback
await chatbot.addFeedback(
  conversation.id,
  response.message.id,
  true, // helpful
  'Clear explanation!'
);
```

### With Explicit OpenRouter

```typescript
const chatbot = createChatbot({
  provider: 'openrouter',
  apiKey: process.env.OPENROUTER_API_KEY!,
  model: 'deepseek/deepseek-v4-flash',
});
```

### Streaming Responses

```typescript
for await (const chunk of chatbot.streamChat(
  conversationId,
  'How do I search?'
)) {
  if (chunk.type === 'text') {
    process.stdout.write(chunk.content);
  }
}
```

## Widget Integration

Embed the chat widget in your documentation site:

```typescript
import { createChatbot, createWidget } from '@veritas/developer-support';

const chatbot = createChatbot({
  apiKey: process.env.OPENROUTER_API_KEY!,
});

const widget = createWidget(chatbot, {
  position: 'bottom-right',
  primaryColor: '#2563eb',
  title: 'API Support',
  greeting: 'Hi! How can I help you with the API?',
});

// Mount to DOM
widget.mount();

// Or mount to a specific container
widget.mount('chat-container');
```

### Widget Configuration

```typescript
interface WidgetConfig {
  position: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  primaryColor?: string;
  title?: string;
  placeholder?: string;
  greeting?: string;
  showAvatar?: boolean;
  startExpanded?: boolean;
  zIndex?: number;
  customClass?: string;
}
```

### Widget Events

```typescript
const widget = createWidget(chatbot, config, {
  onOpen: () => console.log('Widget opened'),
  onClose: () => console.log('Widget closed'),
  onMessageSent: (message) => console.log('User sent:', message),
  onMessageReceived: (response) => console.log('Bot replied'),
  onError: (error) => console.error('Error:', error),
  onFeedback: (messageId, helpful) => console.log('Feedback:', helpful),
  onEscalation: (conversationId) => console.log('Escalated!'),
});
```

## Knowledge Base

The chatbot includes a comprehensive knowledge base covering:

- Authentication and API keys
- Rate limiting
- Feed API
- Search API
- Claims/Fact-Check API
- Entities API
- Media API
- Alerts API
- Webhooks
- JavaScript SDK
- Python SDK
- Common errors and troubleshooting
- Best practices

### Adding Custom Articles

```typescript
const knowledgeBase = chatbot.getKnowledgeBase();

knowledgeBase.addArticle({
  id: 'custom-integration',
  title: 'Custom Integration Guide',
  content: 'Your custom documentation...',
  topics: ['general'],
  keywords: ['custom', 'integration', 'guide'],
  priority: 5,
});
```

## Escalation

When the chatbot can't fully answer a question, it can escalate to human
support:

```typescript
// User explicitly requests escalation
const result = await chatbot.escalate(conversationId, 'Need human help');

// Configure escalation webhook
const chatbot = createChatbot({
  apiKey: process.env.OPENROUTER_API_KEY!,
  escalationWebhookUrl: 'https://your-app.com/support/escalation',
});
```

## Analytics

Track chatbot performance and usage:

```typescript
import { createAnalytics } from '@veritas/developer-support';

const analytics = createAnalytics();

// Get statistics
const stats = await analytics.getStats();
console.log('Resolution rate:', stats.resolutionRate);
console.log('Top topics:', stats.topicBreakdown);
console.log('Common questions:', stats.topQuestions);

// Generate report
import { generateReport } from '@veritas/developer-support';
console.log(generateReport(stats));
```

## Topic Detection

The chatbot automatically detects question topics:

```typescript
import { TopicDetector } from '@veritas/developer-support';

const topic = TopicDetector.detect('How do I authenticate?');
console.log(topic); // 'authentication'

const displayName = TopicDetector.getDisplayName(topic);
console.log(displayName); // 'Authentication'
```

### Supported Topics

- `authentication` - API keys, tokens, auth
- `rate-limiting` - Quotas, limits, throttling
- `feed-api` - News feed, articles
- `search-api` - Search, queries, filters
- `claims-api` - Fact-checking, verification
- `entities-api` - People, organizations
- `media-api` - Images, videos
- `alerts-api` - Notifications, subscriptions
- `webhooks` - Webhook setup, signatures
- `sdk-javascript` - JS/TS SDK
- `sdk-python` - Python SDK
- `billing` - Pricing, payments
- `account` - Account management
- `general` - General questions

## Configuration

```typescript
interface ChatbotConfig {
  // Optional
  provider?: 'openrouter' | 'openai' | 'opencode-cli'; // Default: openrouter
  apiKey?: string; // Defaults to OPENROUTER_API_KEY for OpenRouter
  model?: string; // Default: deepseek/deepseek-v4-flash
  maxTokens?: number; // Default: 2048
  temperature?: number; // Default: 0.7
  customSystemPrompt?: string; // Additional instructions
  enableMemory?: boolean; // Default: true
  maxHistoryLength?: number; // Default: 20
  escalationWebhookUrl?: string; // For human escalation
  supportedTopics?: SupportTopic[]; // Limit topics
}
```

## API Reference

### DeveloperSupportChatbot

- `startConversation(options?)` - Start a new conversation
- `chat(conversationId, message)` - Send a message and get a response
- `streamChat(conversationId, message)` - Stream a response
- `getConversation(conversationId)` - Get conversation details
- `addFeedback(conversationId, messageId, helpful, comment?)` - Add feedback
- `escalate(conversationId, reason)` - Escalate to human support
- `resolveConversation(conversationId)` - Mark as resolved
- `getKnowledgeBase()` - Access the knowledge base

### SupportWidget

- `mount(containerId?)` - Mount to DOM
- `unmount()` - Remove from DOM
- `open()` - Open the widget
- `close()` - Close the widget
- `toggle()` - Toggle open/closed
- `sendMessage(content)` - Send a message
- `provideFeedback(messageId, helpful)` - Submit feedback
- `escalate()` - Request human support
- `clearConversation()` - Start fresh
- `subscribe(listener)` - Subscribe to state changes
- `getState()` - Get current state
- `getConfig()` - Get configuration
- `updateConfig(config)` - Update configuration

## License

UNLICENSED - Private package
