# Módulo Assistant

**Epic:** OQI-007 - LLM Strategy Agent
**Progreso:** 25%
**Responsable:** AI + Backend Teams

## Descripción

El módulo assistant proporciona un copiloto LLM conversacional para trading impulsado por Claude AI. Ofrece análisis de mercado en tiempo real, generación de señales de trading, explicaciones de estrategias, y ejecución de trades basada en contexto. Incluye streaming de responses con Server-Sent Events (SSE), visualización de tool calls, y gestión persistente de conversaciones.

El asistente integra context awareness del mercado (watchlist, risk profile), memoria conversacional con checkpoints, y capacidades de análisis profundo mediante structured forms y strategy templates.

## Componentes

### Páginas

- `Assistant.tsx` - Interface principal de chat LLM: sidebar de conversation history, main chat area, context panel, signal cards, streaming indicator

### Chat Core Components (8)

- `ChatMessage.tsx` - Display de mensaje individual (user/assistant/system); soporta tools used badges y streaming indicator
- `ChatInput.tsx` - Área de input para enviar mensajes con soporte para stop streaming
- `SignalCard.tsx` - Display de trading signals (symbol, direction, entry/SL/TP, AMD phase, confidence)
- `ConversationHistory.tsx` - Sidebar widget de gestión de historial de sesiones con create/select/delete operations
- `ContextPanel.tsx` - Muestra market context (watchlist, risk profile, preferred symbols)
- `ChatHeader.tsx` - Top navigation bar con title, collapse controls, action buttons
- `MessageList.tsx` - Container para rendering de message history con optional search
- `MessageSearch.tsx` - Search functionality across conversation messages

### Message Enhancement Components (4)

- `MarkdownRenderer.tsx` - Renders markdown con handling especial para code blocks, alerts, signal cards
- `ToolCallCard.tsx` - Display de tool calls ejecutados por LLM (function name, arguments, results)
- `MessageFeedback.tsx` - User feedback mechanism para message quality (thumbs up/down, comments)
- `StreamingIndicator.tsx` - Muestra streaming status con animated dots, pulse indicators, processing steps

### Configuration Components (2)

- `AssistantSettingsPanel.tsx` - Opciones de configuración para assistant behavior y preferences
- `SignalExecutionPanel.tsx` - Interface para ejecutar trading signals con position sizing

### OQI-007 Advanced Components (4)

- `AnalysisRequestForm.tsx` - **[NEW]** Formulario estructurado para análisis complejo LLM: symbol, timeframes, indicators, strategy type, risk parameters
- `StrategyTemplateSelector.tsx` - **[NEW]** Templates predefinidos de estrategia para setup rápido de análisis
- `LLMConfigPanel.tsx` - **[NEW]** Model selection (Claude 3.5 Sonnet/Opus/Haiku) y tuning de inference parameters
- `ContextMemoryDisplay.tsx` - **[NEW]** Visualiza conversation context, summarization, token usage, checkpoints

## Hooks

### useChatAssistant

**Ubicación:** `modules/assistant/hooks/useChatAssistant.ts`

Hook centralizado para lógica de chat y state management.

**Características:**
- Session management (create, load, delete)
- Message sending con retry logic (configurable max retries)
- Streaming state tracking
- Tool call management
- Message regeneration
- Auto-scroll y error handling

**API Actions:**
```typescript
const {
  messages,
  loading,
  error,
  sendMessage,
  regenerateLastResponse,
  cancelGeneration,
  createNewSession,
  loadSession,
  editMessage
} = useChatAssistant(sessionId);
```

### useStreamingChat

**Ubicación:** `modules/assistant/hooks/useStreamingChat.ts`

Hook para handling de streaming responses en tiempo real con token animation.

**Características:**
- SSE (Server-Sent Events) support con ReadableStream fallback
- Token-by-token animation con configurable delay
- Chunk processing: content, tool_start, tool_end, thinking, error, done
- Progress tracking y duration calculation
- Cleanup y abort controller management

**Streaming Methods:**
```typescript
const {
  streamingMessage,
  isStreaming,
  progress,
  startStream,
  stopStream,
  reset,
  appendContent
} = useStreamingChat();
```

## Estructura de Carpetas

```
modules/assistant/
├── components/
│   ├── ChatMessage.tsx
│   ├── ChatInput.tsx
│   ├── SignalCard.tsx
│   ├── ConversationHistory.tsx
│   ├── ContextPanel.tsx
│   ├── ChatHeader.tsx
│   ├── MessageList.tsx
│   ├── MessageSearch.tsx
│   ├── MarkdownRenderer.tsx
│   ├── ToolCallCard.tsx
│   ├── MessageFeedback.tsx
│   ├── StreamingIndicator.tsx
│   ├── AssistantSettingsPanel.tsx
│   ├── SignalExecutionPanel.tsx
│   ├── AnalysisRequestForm.tsx         [OQI-007]
│   ├── StrategyTemplateSelector.tsx    [OQI-007]
│   ├── LLMConfigPanel.tsx              [OQI-007]
│   └── ContextMemoryDisplay.tsx        [OQI-007]
├── pages/
│   └── Assistant.tsx
├── hooks/
│   ├── useChatAssistant.ts
│   └── useStreamingChat.ts
└── README.md
```

**Servicios y estado compartidos:**
- **Services:**
  - `services/chat.service.ts` (Axios, base: `http://localhost:3000/api/v1/llm`)
  - `services/llmAgentService.ts` (fetch, base: `http://localhost:3085`)
- **Store:** `stores/chatStore.ts` (Zustand con localStorage persistence)
- **Types:** `types/chat.types.ts`
- **Utils:** `utils/messageFormatters.ts` (formatting utilities)

## APIs Consumidas

### Chat API (Base URL: `http://localhost:3000/api/v1/llm`)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/sessions` | POST | Crear nueva chat session |
| `/sessions` | GET | Listar todas las sessions del usuario |
| `/sessions/{sessionId}` | GET | Cargar session con messages |
| `/sessions/{sessionId}/chat` | POST | Enviar mensaje + obtener response (SSE streaming) |
| `/sessions/{sessionId}` | DELETE | Eliminar session |
| `/analyze/{symbol}` | GET | Análisis rápido de símbolo (public endpoint) |

### LLM Agent API (Base URL: `http://localhost:3085`)

| Feature | Type | Descripción |
|---------|------|-------------|
| **Predictions** | POST | AMD phase analysis, signals, range predictions |
| **Risk Summary** | GET | Position limits, circuit breaker status |
| **Active Signals** | GET | Currently valid trading signals |
| **Backtesting** | POST | Strategy backtesting con performance metrics |

## Uso Rápido

```tsx
import { Assistant } from '@/modules/assistant';
import { useChatStore } from '@/stores/chatStore';
import { useChatAssistant, useStreamingChat } from '@/modules/assistant/hooks';

// Uso en router
<Route path="/assistant" element={<Assistant />} />

// Uso de store
function MyComponent() {
  const {
    sessions,
    currentSessionId,
    messages,
    isOpen,
    openChat,
    closeChat,
    sendMessage
  } = useChatStore();

  const handleSend = async (content: string) => {
    await sendMessage(content);
  };

  return (
    <div>
      <button onClick={openChat}>Open Assistant</button>
      {isOpen && (
        <div>
          <p>Messages: {messages.length}</p>
          <input onSubmit={(e) => handleSend(e.target.value)} />
        </div>
      )}
    </div>
  );
}

// Uso de hooks
function ChatComponent({ sessionId }) {
  const {
    messages,
    loading,
    sendMessage,
    regenerateLastResponse
  } = useChatAssistant(sessionId);

  const {
    streamingMessage,
    isStreaming,
    stopStream
  } = useStreamingChat();

  return (
    <div>
      {messages.map(msg => <ChatMessage key={msg.id} message={msg} />)}
      {isStreaming && (
        <>
          <ChatMessage message={streamingMessage} />
          <button onClick={stopStream}>Stop</button>
        </>
      )}
    </div>
  );
}
```

## Características Principales

### Conversational Interface
- Persistent session history con localStorage
- Context awareness (market data, user preferences)
- Multi-turn conversations con memoria
- Message editing y regeneration
- Search across conversation history

### Real-time Streaming
- Server-Sent Events (SSE) para token-by-token streaming
- Animated typing indicators
- Progress tracking
- Stop generation capability
- Graceful fallback a polling

### Trading Signal Generation
- AMD phase analysis (Accumulation/Manipulation/Distribution)
- Entry/SL/TP levels con risk/reward
- Confidence scores
- Tool call visualization (functions ejecutadas)
- One-click signal execution

### Advanced Analysis Tools (OQI-007)
- **Structured Analysis Forms:** Symbol, timeframes, indicators, strategy type, risk parameters
- **Strategy Templates:** Predefinidos (Breakout, Mean Reversion, Trend Following, Scalping)
- **LLM Config Optimization:** Model selection (Sonnet/Opus/Haiku), temperature, max tokens
- **Context Memory Management:** Conversation summarization, token usage tracking, checkpoints

### Risk-Aware Recommendations
- Position sizing basado en account balance y risk %
- Drawdown tracking
- Circuit breaker awareness
- Risk summary integration

## Utility Functions

### Number & Price Formatting (utils/messageFormatters.ts)

```typescript
formatPrice(price, symbol)        // $1,234.56 o 123.45 pips
formatPercentage(value, decimals) // +12.34%
formatPnL(pnl, pnlPct)           // $100.50 (+2.5%)
formatVolume(volume)              // 0.01 lots
formatPips(pips)                  // +25.3 pips
formatCurrency(value, currency)   // $1,234.56
```

### Signal & Tool Parsing

```typescript
extractTradingSignals(text)       // Parse BUY/SELL from LLM response
extractPriceLevels(text)          // Extract entry, SL, TP
parseToolCallReferences(text)     // Find tool invocations
extractMentionedTools(text)       // List of tools used
```

### Markdown & Text Processing

```typescript
parseMarkdownTable(markdown)      // Convert to structured data
stripMarkdown(text)               // Remove formatting
extractCodeBlocks(text)           // Get code blocks
```

### Time & Validation

```typescript
formatChatTime(timestamp)         // "2 hours ago"
formatDuration(ms)                // "1h 23m 45s"
containsTradingContent(text)      // Boolean
isValidPrice(price)               // Boolean
```

## Tests

```bash
# Tests unitarios del módulo
npm run test modules/assistant

# Tests de integración con LLM
npm run test:integration assistant/llm

# Tests E2E de conversational flows
npm run test:e2e assistant
```

## Roadmap

### Pendientes - Alta Prioridad (P1-P2)
- [ ] **Voice Input** (40h) - Speech-to-text para mensajes por voz
- [ ] **Multi-model Support** (15h) - Soporte para GPT-4, Gemini además de Claude
- [ ] **Conversation Export** (10h) - Export de conversaciones a PDF/Markdown
- [ ] **Shared Conversations** (25h) - Compartir conversaciones con otros usuarios

### Mediano Plazo (P2-P3)
- [ ] **Custom Prompts** (10h) - Permite users crear custom system prompts
- [ ] **Conversation Templates** (15h) - Templates para tipos comunes de análisis
- [ ] **Web Search Integration** (30h) - Integrar búsqueda web para contexto actualizado
- [ ] **Image Analysis** (40h) - Analizar chart screenshots

### Largo Plazo (P3)
- [ ] **Multi-agent Collaboration** (60h) - Múltiples agents especializados trabajando juntos
- [ ] **Fine-tuning** (80h) - Fine-tune modelos con datos históricos propios
- [ ] **Autonomous Trading** (120h) - Agent completamente autónomo con approval workflow

## Dependencias

- `zustand` - State management
- `axios` - HTTP client
- `lucide-react` - Icons
- `react-markdown` - Markdown rendering
- SSE polyfill (si es necesario para navegadores antiguos)

## Documentación Relacionada

- **ET Specs:** No aplica (funcionalidad base de OQI-007)
- **User Stories:** US-AST-001 a US-AST-010
- **Backend API Docs:** `/docs/api/llm.md`
- **Claude AI Integration:** `/docs/integrations/claude-ai.md`
- **Prompt Engineering:** `/docs/ai/prompt-engineering.md`

---

**Última actualización:** 2026-01-25
**Autor:** Claude Opus 4.5
