# Chatbot API Reference

This document provides detailed API reference for the RAG Chatbot Library.

## Table of Contents

- [ChatbotAPI](#chatbotapi)
- [Types](#types)
- [Hooks](#hooks)
- [Components](#components)
- [Error Handling](#error-handling)

## ChatbotAPI

The main API class for interacting with the chatbot system.

### Constructor

```typescript
const api = new ChatbotAPI();
```

### Methods

#### initialize(config: ChatbotAPIConfig): Promise<ApiResponse<string>>

Initializes the chatbot with the provided configuration.

**Parameters:**

- `config`: Configuration object containing LLM, vector store, and storage settings

**Returns:** Promise resolving to success/error response

**Example:**

```typescript
const result = await api.initialize({
  llm: {
    provider: "openai",
    model: "gpt-3.5-turbo",
    apiKey: "your-api-key",
    maxTokens: 1000,
    temperature: 0.7,
  },
  vectorStore: {
    provider: "memory",
    dimensions: 1536,
  },
  storage: {
    provider: "local",
  },
});

if (result.success) {
  console.log("Chatbot initialized successfully");
} else {
  console.error("Initialization failed:", result.error);
}
```

#### sendMessage(content: string, conversationId?: string): Promise<ApiResponse<ConversationMessage>>

Sends a message and gets an AI response.

**Parameters:**

- `content`: The message content to send
- `conversationId`: Optional conversation ID (creates new conversation if not provided)

**Returns:** Promise resolving to the AI response message

**Example:**

```typescript
const response = await api.sendMessage("Hello, how can you help me?");
console.log("AI Response:", response.data?.content);
```

#### uploadDocument(file: File, metadata?: Partial<Document['metadata']>): Promise<ApiResponse<Document>>

Uploads and processes a document for the knowledge base.

**Parameters:**

- `file`: File object to upload
- `metadata`: Optional metadata for the document

**Returns:** Promise resolving to the processed document

**Example:**

```typescript
const file = new File(["Document content"], "document.txt", {
  type: "text/plain",
});
const result = await api.uploadDocument(file, {
  title: "Important Document",
  tags: ["important", "reference"],
});

if (result.success) {
  console.log("Document uploaded:", result.data?.id);
}
```

#### deleteDocument(documentId: string): Promise<ApiResponse<void>>

Deletes a document from the knowledge base.

**Parameters:**

- `documentId`: ID of the document to delete

**Returns:** Promise resolving to success/error response

#### getDocuments(limit?: number, offset?: number): Promise<ApiResponse<Document[]>>

Retrieves a list of documents.

**Parameters:**

- `limit`: Maximum number of documents to return (default: 50)
- `offset`: Number of documents to skip (default: 0)

**Returns:** Promise resolving to array of documents

#### searchSimilarDocuments(query: string, limit?: number): Promise<ApiResponse<Document[]>>

Performs semantic search on the document knowledge base.

**Parameters:**

- `query`: Search query string
- `limit`: Maximum number of results (default: 10)

**Returns:** Promise resolving to array of relevant documents

#### startConversation(title?: string): Promise<ApiResponse<Conversation>>

Creates a new conversation.

**Parameters:**

- `title`: Optional title for the conversation

**Returns:** Promise resolving to the new conversation

#### getConversations(limit?: number): Promise<ApiResponse<Conversation[]>>

Retrieves user's conversations.

**Parameters:**

- `limit`: Maximum number of conversations to return

**Returns:** Promise resolving to array of conversations

#### deleteConversation(conversationId: string): Promise<ApiResponse<void>>

Deletes a conversation and all its messages.

**Parameters:**

- `conversationId`: ID of the conversation to delete

**Returns:** Promise resolving to success/error response

#### getConversationHistory(conversationId: string): Promise<ApiResponse<ConversationMessage[]>>

Gets all messages in a conversation.

**Parameters:**

- `conversationId`: ID of the conversation

**Returns:** Promise resolving to array of messages

#### getConfiguration(): ChatbotAPIConfig | null

Gets the current configuration.

**Returns:** Current configuration object or null if not initialized

#### updateConfiguration(config: Partial<ChatbotAPIConfig>): Promise<ApiResponse<string>>

Updates the chatbot configuration.

**Parameters:**

- `config`: Partial configuration object with updates

**Returns:** Promise resolving to success/error response

## Types

### ChatbotAPIConfig

```typescript
interface ChatbotAPIConfig {
  llm?: LLMConfig;
  vectorStore?: VectorStoreConfig;
  storage?: StorageConfig;
}
```

### LLMConfig

```typescript
interface LLMConfig {
  provider: LLMProvider;
  model: string;
  apiKey: string;
  maxTokens?: number;
  temperature?: number;
  systemPrompt?: string;
}

type LLMProvider = "openai" | "anthropic" | "azure" | "huggingface";
```

### VectorStoreConfig

```typescript
interface VectorStoreConfig {
  dimensions: number;
  // Provider-specific configurations
}
```

### StorageConfig

```typescript
interface StorageConfig {
  // Provider-specific configurations
}
```

### Document

```typescript
interface Document {
  id: string;
  content: string;
  metadata: {
    title?: string;
    filename?: string;
    fileType?: string;
    fileSize?: number;
    uploadedAt?: Date;
    tags?: string[];
    description?: string;
  };
  embedding?: number[];
  createdAt: Date;
  updatedAt: Date;
}
```

### Conversation

```typescript
interface Conversation {
  id: string;
  title: string;
  messages: ConversationMessage[];
  createdAt: Date;
  updatedAt: Date;
}
```

### ConversationMessage

```typescript
interface ConversationMessage {
  id: string;
  role: "user" | "assistant" | "system";
  content: string;
  timestamp: Date;
  metadata?: {
    sources?: Document[];
    processingTime?: number;
    tokensUsed?: number;
  };
}
```

### ApiResponse

```typescript
interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  details?: any;
  status?: number;
  timestamp?: string;
}
```

### ChatbotError

```typescript
interface ChatbotError {
  code: string;
  message: string;
  details?: any;
  timestamp: Date;
  severity?: "low" | "medium" | "high" | "critical";
}
```

## Hooks

### useChatbot

Main hook providing access to chatbot functionality.

```typescript
interface UseChatbotReturn {
  // State
  isInitialized: boolean;
  isProcessing: boolean;
  conversations: Conversation[];
  currentConversation: Conversation | null;
  documents: Document[];
  lastError: ChatbotError | null;

  // Actions
  initialize: (config?: ChatbotAPIConfig) => Promise<void>;
  sendMessage: (
    content: string,
    conversationId?: string
  ) => Promise<ConversationMessage>;
  uploadDocument: (
    file: File,
    metadata?: Partial<Document["metadata"]>
  ) => Promise<Document>;
  deleteDocument: (documentId: string) => Promise<void>;
  searchSimilarDocuments: (
    query: string,
    limit?: number
  ) => Promise<Document[]>;
  startConversation: (title?: string) => Promise<Conversation>;
  selectConversation: (conversationId: string) => Promise<void>;
  deleteConversation: (conversationId: string) => Promise<void>;
  getConversationHistory: (
    conversationId: string
  ) => Promise<ConversationMessage[]>;
  clearError: () => void;
}
```

### useDocuments

Hook for document management.

```typescript
interface UseDocumentsReturn {
  documents: Document[];
  isLoading: boolean;
  uploadDocument: (
    file: File,
    metadata?: Partial<Document["metadata"]>
  ) => Promise<Document>;
  deleteDocument: (documentId: string) => Promise<void>;
  getDocument: (documentId: string) => Document | undefined;
  searchDocuments: (query: string, limit?: number) => Promise<Document[]>;
  documentCount: number;
}
```

### useErrorHandler

Hook for centralized error handling.

```typescript
interface UseErrorHandlerReturn {
  error: ChatbotError | null;
  hasError: boolean;
  clearError: () => void;
  handleError: (error: Error | ChatbotError | string) => void;
  getErrorMessage: () => string | null;
  isErrorType: (code: string) => boolean;
  errorSeverity: "low" | "medium" | "high" | "critical" | null;
}
```

### useTheme

Hook for theme management.

```typescript
interface UseThemeReturn {
  theme: Theme;
  setTheme: (theme: Partial<Theme>) => void;
  toggleMode: () => void;
  resetTheme: () => void;
}

interface Theme {
  mode: "light" | "dark";
  primaryColor: string;
  backgroundColor: string;
  textColor: string;
  borderColor: string;
}
```

### useI18n

Hook for internationalization.

```typescript
interface UseI18nReturn {
  language: SupportedLanguage;
  setLanguage: (language: SupportedLanguage) => void;
  t: (key: string, params?: Record<string, string>) => string;
  isRTL: boolean;
}

type SupportedLanguage = "en" | "ko" | "ja" | "zh";
```

## Components

### ChatbotProvider

Context provider for the chatbot system.

```typescript
interface ChatbotProviderProps {
  children: React.ReactNode;
  config?: ChatbotAPIConfig;
  onError?: (error: ChatbotError) => void;
}
```

### ChatbotWidget

Main chatbot interface component.

```typescript
interface ChatbotWidgetProps {
  theme?: Partial<Theme>;
  position?: "bottom-left" | "bottom-right" | "top-left" | "top-right";
  showSuggestedQuestions?: boolean;
  placeholder?: string;
  maxHeight?: string;
  className?: string;
}
```

### RAGChat

Full-featured chat interface.

```typescript
interface RAGChatProps {
  conversationId?: string;
  showDocumentSearch?: boolean;
  showUpload?: boolean;
  maxHeight?: string;
  className?: string;
  onDocumentUpload?: (document: Document) => void;
  onMessageSent?: (message: ConversationMessage) => void;
}
```

### FloatingChatButton

Floating action button for chat.

```typescript
interface FloatingChatButtonProps {
  position?: "bottom-left" | "bottom-right" | "top-left" | "top-right";
  size?: "sm" | "md" | "lg";
  icon?: React.ReactNode;
  onClick?: () => void;
  className?: string;
}
```

## Error Handling

### Error Codes

Common error codes returned by the API:

- `INITIALIZATION_FAILED`: Failed to initialize the chatbot
- `INVALID_CONFIG`: Invalid configuration provided
- `LLM_ERROR`: Error from the language model
- `VECTOR_STORE_ERROR`: Error from the vector store
- `STORAGE_ERROR`: Error from the storage provider
- `DOCUMENT_UPLOAD_FAILED`: Failed to upload document
- `DOCUMENT_NOT_FOUND`: Requested document not found
- `CONVERSATION_NOT_FOUND`: Requested conversation not found
- `INVALID_FILE_TYPE`: Unsupported file type
- `FILE_TOO_LARGE`: File exceeds size limit
- `RATE_LIMIT_EXCEEDED`: API rate limit exceeded
- `NETWORK_ERROR`: Network connection error
- `UNAUTHORIZED`: Invalid API credentials

### Error Handling Best Practices

1. **Always check the success field** in API responses:

```typescript
const result = await api.sendMessage("Hello");
if (!result.success) {
  console.error("Error:", result.error);
  return;
}
// Use result.data safely
```

2. **Use the error handler hook** for centralized error management:

```typescript
const { handleError, getErrorMessage } = useErrorHandler();

try {
  await api.uploadDocument(file);
} catch (error) {
  handleError(error);
}
```

3. **Implement fallback UI** for error states:

```typescript
if (hasError) {
  return (
    <div className="error-state">
      <p>{getErrorMessage()}</p>
      <button onClick={clearError}>Try Again</button>
    </div>
  );
}
```

4. **Log errors** for debugging:

```typescript
const config = {
  onError: (error: ChatbotError) => {
    console.error("Chatbot Error:", error);
    // Send to error tracking service
  },
};
```
