> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thaliq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Feedback e Insights

> Como enviar feedback de mensajes y consumir insights extraidos por el agente

## Feedback

El SDK permite enviar feedback (thumbs up/down) sobre mensajes individuales del agente. Esto ayuda a mejorar la calidad de las respuestas y aparece en las metricas del tenant.

### Obtener el messageId

El `messageId` necesario para feedback se obtiene del evento `response.completed` o de la metadata de la respuesta:

```typescript theme={null}
// Via streaming
const stream = thaliq.agent.stream('Analiza mis gastos');
let messageId: string | undefined;

for await (const event of stream) {
  if (event.type === 'content.delta') {
    process.stdout.write(event.delta);
  }
  if (event.type === 'response.completed') {
    messageId = event.metadata?.messageId;
  }
}

// Via chat
const response = await thaliq.agent.chat('Analiza mis gastos');
messageId = response.metadata.messageId;
```

### Enviar feedback

```typescript theme={null}
await thaliq.agent.feedback({
  conversationId: 'conv-123',
  messageId: 'msg-456',
  feedback: 'positive',  // 'positive' | 'negative'
});
```

### Parametros

| Parametro        | Tipo                       | Requerido | Descripcion                |
| ---------------- | -------------------------- | :-------: | -------------------------- |
| `conversationId` | `string`                   |     Si    | ID de la conversacion      |
| `messageId`      | `string`                   |     Si    | ID del mensaje a calificar |
| `feedback`       | `'positive' \| 'negative'` |     Si    | Calificacion               |

### Ejemplo completo

```typescript theme={null}
const stream = thaliq.agent.stream('¿Cuales son mis gastos mas altos?');
let messageId: string | undefined;
let conversationId: string | undefined;

for await (const event of stream) {
  if (event.type === 'meta') {
    conversationId = event.conversationId;
  }
  if (event.type === 'content.delta') {
    appendToUI(event.delta);
  }
  if (event.type === 'response.completed') {
    messageId = event.metadata?.messageId;
  }
}

// Mostrar botones de feedback en la UI
showFeedbackButtons({
  onThumbsUp: async () => {
    await thaliq.agent.feedback({
      conversationId: conversationId!,
      messageId: messageId!,
      feedback: 'positive',
    });
  },
  onThumbsDown: async () => {
    await thaliq.agent.feedback({
      conversationId: conversationId!,
      messageId: messageId!,
      feedback: 'negative',
    });
  },
});
```

<Info>
  El endpoint de feedback es `POST /api/agent/feedback`. El feedback se persiste en DynamoDB y es visible en la plataforma.
</Info>

***

## Insights

Los agentes pueden extraer **insights** automaticamente del contexto de la conversacion. Estos son observaciones, alertas, oportunidades o logros que el agente detecta al analizar datos.

### Tipos de insight

| Tipo          | Descripcion                  | Ejemplo                                         |
| ------------- | ---------------------------- | ----------------------------------------------- |
| `warning`     | Alerta que requiere atencion | "Gasto inusual detectado en restaurantes"       |
| `opportunity` | Oportunidad identificada     | "Puedes ahorrar S/200 reduciendo suscripciones" |
| `info`        | Informacion relevante        | "Tu gasto promedio mensual es S/3,200"          |
| `achievement` | Logro o hito positivo        | "Ahorraste 15% mas que el mes pasado"           |

### Severidad

| Severidad  | Significado                 |
| ---------- | --------------------------- |
| `low`      | Informativo                 |
| `medium`   | Requiere atencion eventual  |
| `high`     | Importante                  |
| `critical` | Requiere atencion inmediata |

### Consumir insights

Los insights vienen incluidos en la respuesta:

```typescript theme={null}
// Via chat
const response = await thaliq.agent.chat('Dame un resumen de mis finanzas');

for (const insight of response.insights) {
  console.log(`[${insight.severity}] ${insight.type}: ${insight.title}`);
  console.log(insight.description);
  if (insight.amount) console.log(`Monto: ${insight.amount}`);
}
```

```typescript theme={null}
// Via streaming (en response.completed)
const stream = thaliq.agent.stream('Dame un resumen');

for await (const event of stream) {
  if (event.type === 'response.completed') {
    renderInsights(event.insights);
  }
}

// O via finalResponse()
const response = await stream.finalResponse();
renderInsights(response.insights);
```

### Interfaz Insight

```typescript theme={null}
interface Insight {
  type: 'warning' | 'opportunity' | 'info' | 'achievement';
  severity: 'low' | 'medium' | 'high' | 'critical';
  title: string;
  description: string;
  category?: string;    // Ej: "gastos", "ahorros", "inversiones"
  amount?: string;      // Ej: "S/ 1,200" (para insights financieros)
}
```

### Ejemplo: renderizar insights en una app

```typescript theme={null}
function renderInsights(insights: Insight[]) {
  const iconMap = {
    warning: '⚠️',
    opportunity: '💡',
    info: 'ℹ️',
    achievement: '🏆',
  };

  for (const insight of insights) {
    const icon = iconMap[insight.type];
    console.log(`${icon} ${insight.title}`);
    console.log(`   ${insight.description}`);
    if (insight.category) console.log(`   Categoria: ${insight.category}`);
    if (insight.amount) console.log(`   Monto: ${insight.amount}`);
    console.log('');
  }
}
```

<Tip>
  Los insights dependen de las tools del agente y del contexto de la conversacion. No todas las respuestas incluyen insights — solo aquellas donde el agente detecta informacion relevante.
</Tip>
