# @agentstable/chat-sdk

**AI-Powered Chat SDK with Intelligent Classification and Automatic Filesystem Management**

## 🚀 Quick Start

```bash
npm install @agentstable/chat-sdk
```

```typescript
import { ChatSDK } from '@agentstable/chat-sdk';

const sdk = new ChatSDK({
  baseUrl: 'https://your-server.com/api',
  userId: 'your-user-id',
  timeout: 60000
});

// Create a chat
const chat = await sdk.createChat({
  title: 'My AI Assistant',
  systemPrompt: 'You are a helpful AI assistant.'
});

// Send a message - AI automatically handles classification and actions
const message = await sdk.createMessage({
  chatId: chat.id,
  role: 'user',
  content: 'I'm starting a podcast series about AI'
});

// Get chat history
const history = await sdk.getMessages(chat.id);
```

## 🤖 Intelligent AI Features

### **Automatic Classification & Response**
The AI automatically classifies user messages and responds appropriately:

- **📝 Simple Questions**: Get direct, fast answers
- **🔍 Sharing Information**: AI probes with helpful assistance options  
- **🚀 Action Requests**: AI creates plans and organizes workflows

### **Example Interactions**

**Simple Question:**
```typescript
// User: "What's 2+2?"
// AI: "2+2 = 4"
```

**Information Sharing (Triggers Probing):**
```typescript
// User: "I'm starting a podcast series about AI"
// AI: "That's awesome! Are you looking for help with:
//      💡 Episode Planning
//      🎧 Production Setup  
//      📱 Marketing Strategy
//      Or just sharing the exciting news?"
```

**Action Request (Ready for Planning):**
```typescript
// User: "Help me set up a podcast production system"
// AI: Creates comprehensive workflow and organization
```

## 📖 Core API

### **Chat Management**

```typescript
// Create a chat
const chat = await sdk.createChat({
  title: string,
  systemPrompt?: string,
  tags?: string[]
});

// Get chat details
const chat = await sdk.getChat(chatId);

// Update chat
const updated = await sdk.updateChat(chatId, {
  title?: string,
  systemPrompt?: string,
  tags?: string[]
});

// List user's chats
const chats = await sdk.getChats();
```

### **Message Management**

```typescript
// Send a message
const message = await sdk.createMessage({
  chatId: string,
  role: 'user' | 'assistant' | 'system',
  content: string
});

// Get chat messages
const history = await sdk.getMessages(chatId, options?);

// Stream a chat response
const stream = await sdk.streamChat({
  chatId: string,
  message: string,
  includeHistory?: boolean
});
```

## 🎯 Real-World Usage

### **React Example**
```tsx
import { useState, useEffect } from 'react';
import { ChatSDK } from '@agentstable/chat-sdk';

function ChatInterface({ userId }) {
  const [sdk] = useState(() => new ChatSDK({
    baseUrl: 'https://your-server.com/api',
    userId,
    timeout: 60000
  }));
  
  const [chat, setChat] = useState(null);
  const [messages, setMessages] = useState([]);
  
  useEffect(() => {
    // Create or load chat
    const initChat = async () => {
      const newChat = await sdk.createChat({
        title: 'AI Assistant',
        systemPrompt: 'You are a helpful AI assistant.'
      });
      setChat(newChat);
      
      const history = await sdk.getMessages(newChat.id);
      setMessages(history.messages);
    };
    
    initChat();
  }, [sdk]);
  
  const sendMessage = async (content) => {
    if (!chat) return;
    
    // Add user message
    const userMessage = await sdk.createMessage({
      chatId: chat.id,
      role: 'user', 
      content
    });
    
    // Stream AI response
    const response = await fetch(`${sdk.config.baseUrl}/aiChatStream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-User-ID': userId,
      },
      body: JSON.stringify({
        chatId: chat.id,
        message: content
      })
    });
    
    const aiResponse = await response.text();
    
    // Refresh messages
    const updated = await sdk.getMessages(chat.id);
    setMessages(updated.messages);
  };
  
  return (
    <div className="chat-interface">
      {/* Your chat UI here */}
    </div>
  );
}
```

## 🛡️ Error Handling

```typescript
try {
  const message = await sdk.createMessage({
    chatId: 'invalid-id',
    role: 'user',
    content: 'Hello'
  });
} catch (error) {
  console.error('Failed to send message:', error.message);
}
```

## 🔧 Configuration

```typescript
interface SDKConfig {
  baseUrl: string;      // Your API server URL
  userId: string;       // Current user ID
  apiKey?: string;      // Optional API key
  timeout?: number;     // Request timeout (default: 30000)
}
```

## 🎨 TypeScript Support

Full TypeScript support with comprehensive type definitions for all chat and message operations.

## 📊 Automatic Features

- ✅ **Smart Classification**: AI automatically determines response type
- ✅ **Intelligent Probing**: Contextual assistance options when users share information
- ✅ **Error Handling**: Robust error management and retries
- ✅ **Real-time Streaming**: Fast, responsive AI interactions
- ✅ **Message History**: Complete conversation tracking
- ✅ **User Context**: Personalized responses based on chat history

---

**The AI handles all the complexity - you just chat naturally! 🚀** 