← back to Designer Wallcoverings

DW-Agents/dw-agents/CHAT_IMPLEMENTATION_GUIDE.md

254 lines

# Chat Feature Implementation Guide

## Overview
The DW-Agents system now includes chat capabilities for communicating with each agent directly.

## What's Been Implemented

### 1. Master Hub Chat (✅ COMPLETED)
- **Location**: http://45.61.58.125:9893/
- **Features**:
  - Each agent card now has a "💬 Chat" button
  - Clicking the button opens a modal chat interface
  - Chat is contextual to the specific agent
  - Powered by Claude AI with agent-specific knowledge

### 2. Task Orchestrator Improvements (✅ COMPLETED)
- **Location**: http://45.61.58.125:9900/
- **Updates**:
  - Now shows up to 100 tasks (previously 20)
  - Filters tasks to show only the last 2 days
  - Auto-cleanup runs every 6 hours
  - Manual cleanup on startup
  - All current agent activities are now visible

### 3. Agents with Chat Already Implemented
The following agents already have working chat interfaces:
- ✅ Purchasing Office Agent (Port 9880)
- ✅ Marketing Agent (Port 9881)
- ✅ Accounting Agent (Port 9882)
- ✅ Trend Research Agent (Port 9883)
- ✅ Zendesk Chat Agent (Port 9884)

### 4. Agents Pending Chat Implementation
The following agents need chat added:
- ⏳ Digital Samples Agent (Port 9879)
- ⏳ Legal Team Agent (Port 9878)
- ⏳ Needs Attention Agent (Port 9886)
- ⏳ Parallel Processes Agent (Port 9887)
- ⏳ Server Uptime Agent (Port 9888)
- ⏳ Task Orchestrator Agent (Port 9900)
- ⏳ Completed Tasks Agent (Port 9889)
- ⏳ Today's Highlights Agent (Port 9885)
- ⏳ New Client Signup Agent (Port 9890)
- ⏳ In Parallel Agent (Port 9891)

## How to Add Chat to an Agent

### Step 1: Add Chat Endpoint
Add this endpoint to your agent's TypeScript file:

```typescript
app.post('/api/chat', requireAuth, async (req, res) => {
  try {
    const { message } = req.body;

    if (!message) {
      return res.status(400).json({ error: 'Message is required' });
    }

    // Initialize chat history
    if (!req.session.chatHistory) {
      req.session.chatHistory = [];
    }

    req.session.chatHistory.push({ role: 'user', content: message });

    const systemPrompt = \`You are the AI assistant for the [AGENT NAME] at Designer Wallcoverings.

Your role:
- Answer questions about [AGENT SPECIFIC FUNCTIONS]
- Help users understand [AGENT CAPABILITIES]
- Provide information from [AGENT DATA SOURCES]

Be helpful, concise, and accurate.\`;

    const anthropic = new Anthropic({
      apiKey: process.env.ANTHROPIC_API_KEY || 'your-key-here',
    });

    const response = await anthropic.messages.create({
      model: 'claude-sonnet-4-20250514',
      max_tokens: 2048,
      system: systemPrompt,
      messages: req.session.chatHistory
    });

    const assistantMessage = response.content[0].type === 'text'
      ? response.content[0].text
      : 'I apologize, but I encountered an error.';

    req.session.chatHistory.push({ role: 'assistant', content: assistantMessage });

    // Keep only last 20 messages
    if (req.session.chatHistory.length > 20) {
      req.session.chatHistory = req.session.chatHistory.slice(-20);
    }

    res.json({ response: assistantMessage });

  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({
      error: 'Failed to process message',
      response: 'I apologize, but I encountered an error. Please try again.'
    });
  }
});
```

### Step 2: Add Chat UI to Dashboard HTML
Add this to your agent's main HTML template, inside the body before the closing `</body>` tag:

```html
<!-- Chat Widget -->
<button
  onclick="toggleChat()"
  id="chatToggleBtn"
  style="position: fixed; bottom: 30px; right: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 16px 24px; border-radius: 50px; cursor: pointer; font-weight: 600; box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4); z-index: 9999; display: flex; align-items: center; gap: 10px; font-size: 1.1em; transition: transform 0.2s;"
  onmouseover="this.style.transform='scale(1.05)'"
  onmouseout="this.style.transform='scale(1)'"
>
  💬 Chat with Agent
</button>

<div id="chatWidget" style="display: none; position: fixed; bottom: 100px; right: 30px; width: 400px; height: 600px; background: white; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); z-index: 10000; flex-direction: column; overflow: hidden;">
  <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center;">
    <div>
      <div style="font-weight: 600; font-size: 1.2em;">💬 Agent Assistant</div>
      <div style="font-size: 0.9em; opacity: 0.9;">Ask me anything!</div>
    </div>
    <button onclick="toggleChat()" style="background: rgba(255,255,255,0.2); border: none; color: white; width: 36px; height: 36px; border-radius: 50%; cursor: pointer; font-size: 1.5em;">×</button>
  </div>
  <div id="chatMessages" style="flex: 1; overflow-y: auto; padding: 20px; background: #f8f9fa;">
    <div style="text-align: center; color: #888; padding: 20px;">
      👋 Hi! I'm your AI assistant. Ask me anything!
    </div>
  </div>
  <div style="padding: 20px; border-top: 1px solid #e0e0e0; background: white;">
    <div style="display: flex; gap: 10px;">
      <input
        type="text"
        id="chatInput"
        placeholder="Type your question..."
        style="flex: 1; padding: 12px; border: 2px solid #e0e0e0; border-radius: 25px; font-size: 1em;"
        onkeypress="if(event.key==='Enter') sendMessage()"
      >
      <button
        onclick="sendMessage()"
        id="chatSendBtn"
        style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 24px; border-radius: 25px; cursor: pointer; font-weight: 600;"
      >
        Send
      </button>
    </div>
  </div>
</div>

<script>
function toggleChat() {
  const widget = document.getElementById('chatWidget');
  const btn = document.getElementById('chatToggleBtn');

  if (widget.style.display === 'none') {
    widget.style.display = 'flex';
    btn.style.display = 'none';
  } else {
    widget.style.display = 'none';
    btn.style.display = 'flex';
  }
}

function addChatMessage(role, content) {
  const messagesDiv = document.getElementById('chatMessages');
  const messageDiv = document.createElement('div');
  messageDiv.style = role === 'user'
    ? 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 16px; border-radius: 12px; margin-bottom: 10px; max-width: 80%; margin-left: auto; text-align: right;'
    : 'background: white; color: #333; padding: 12px 16px; border-radius: 12px; margin-bottom: 10px; max-width: 80%; border: 1px solid #e0e0e0;';

  messageDiv.textContent = content;
  messagesDiv.appendChild(messageDiv);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

async function sendMessage() {
  const input = document.getElementById('chatInput');
  const sendBtn = document.getElementById('chatSendBtn');
  const message = input.value.trim();

  if (!message) return;

  addChatMessage('user', message);
  input.value = '';
  sendBtn.disabled = true;
  sendBtn.textContent = 'Thinking...';

  try {
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message })
    });

    const data = await response.json();
    addChatMessage('assistant', data.response || 'Sorry, I encountered an error.');
  } catch (error) {
    addChatMessage('assistant', 'Sorry, I encountered an error. Please try again.');
  } finally {
    sendBtn.disabled = false;
    sendBtn.textContent = 'Send';
  }
}
</script>
```

### Step 3: Update Session Declaration
Make sure your agent has the session type declaration:

```typescript
declare module 'express-session' {
  interface SessionData {
    authenticated: boolean;
    chatHistory: Array<{ role: 'user' | 'assistant', content: string }>;
  }
}
```

### Step 4: Restart the Agent
```bash
pm2 restart [agent-name]
```

## Testing

1. Visit the Master Hub at http://45.61.58.125:9893/
2. Click the "💬 Chat" button on any agent card
3. Ask questions about that specific agent
4. Or visit an individual agent's page and use their floating chat button

## Benefits

- **Direct Communication**: Chat with any agent about their specific domain
- **AI-Powered**: Uses Claude AI for intelligent responses
- **Context-Aware**: Each agent has specialized knowledge
- **Session Memory**: Maintains conversation history within a session
- **Responsive UI**: Clean, modern chat interface

## Next Steps

To complete the chat implementation across all agents:
1. Apply the template above to each agent listed in "Agents Pending Chat Implementation"
2. Customize the `systemPrompt` for each agent's specific capabilities
3. Test each agent's chat functionality
4. Update this document to mark agents as completed