@agentcrafta/chat-next
v0.0.13
Published
Customizable chat agent
Downloads
1,253
Readme
Agente Conversacional Embebido
Descripción del Componente
El Agente Conversacional Embebido es un componente React que integra Microsoft Bot Framework Web Chat en una interfaz moderna y personalizable. Proporciona una experiencia de chat completa con soporte para reinicio de conversación, personalización de estilos dinámicos basados en variables CSS, y gestión automática del estado de conexión.
Este componente utiliza el Web Chat de Bot Framework para comunicarse con Power Virtual Agents (PVA) u otros bots compatibles, ofreciendo una interfaz de usuario intuitiva y responsive.
Índice
- Instalación y Configuración
- Variables de Entorno
- Uso del Componente
- Server Actions
- Hook useChat
- Configuración de StyleOptions
- Tipos y Interfaces
- Styles
- Limitaciones y Consideraciones
Instalación y Configuración
Variables de Entorno
Configure las siguientes variables en su archivo .env.local para desarrollo local:
# URL del endpoint para obtener tokens del agente conversacional
TOKEN_AGENTE_URL=https://your-bot-endpoint.com/powervirtualagents/botsbyschema/...
# o
NEXT_PUBLIC_TOKEN_AGENTE_URL=https://your-bot-endpoint.com/powervirtualagents/botsbyschema/...Para PRODUCCIÓN, asegúrese de establecer esta variable en su entorno de despliegue.
Importante: La variable debe apuntar al endpoint completo de Power Virtual Agents que incluye el esquema del bot y la API version.
Uso del Componente
Características
- Chat flotante: Aparece como un botón flotante en la esquina inferior derecha
- Interfaz responsive: Se adapta a diferentes tamaños de pantalla
- Reinicio de conversación: Botón para reiniciar la conversación completa
- Personalización de estilos: Utiliza variables CSS para temas dinámicos
- Gestión de errores: Manejo robusto de errores tanto en cliente como en servidor
Props del Componente
| Prop | Tipo | Default | Descripción |
| -------------- | -------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------- |
| botName | string | "Agent" | Nombre que se mostrará en la cabecera del chat |
| logoUrl | string | undefined | URL del logo que se mostrará junto al nombre del bot (opcional) |
| show | boolean | true | Indica si el chat debe mostrarse o no (por defecto es true) |
| styleOptions | StyleOptions | undefined | Opciones de estilo personalizadas para el chat (opcional) |
| entryPoint | string | undefined | Punto de entrada para la conversación (opcional) |
| position | "bottom-right" \| "bottom-left" \| "top-right" \| "top-left" | "bottom-right" | Posición del chat en la pantalla (por defecto es "bottom-right") |
| chatButton | (props: ChatButtonProps) => React.ReactNode | undefined | Elemento de botón personalizado para abrir el chat (opcional) |
Importación y Uso
Importante: Componente de tipo Client Component, debe ser utilizado dentro de un componente con 'use client' en Next.js.
En el archivo layout o en la página donde desea mostrar el chat, importe los estilos del componente
import "@agentcrafta/chat-next/styles.css";Básico
import { Chat } from "@agentcrafta/chat-next";
export default function HomePage() {
return (
<div>
<h1>Mi Aplicación</h1>
<Chat
entryPoint={process.env.NEXT_PUBLIC_TOKEN_AGENTE_URL || ""}
botName="Asistente Virtual"
/>
</div>
);
}Avanzado con Personalización de Estilos
"use client";
import { Chat } from "@agentcrafta/chat-next";
export default function HomePage() {
return (
<div>
<h1>Mi Aplicación</h1>
<Chat
botName="Asistente Virtual"
logoUrl="/logo.svg"
entryPoint={process.env.NEXT_PUBLIC_TOKEN_AGENTE_URL || ""}
styleOptions={{
backgroundColor: "#7e0f0f",
}}
chatButton={({ isVisible, toggle }) => (
<button onClick={toggle}>{isVisible ? "Cerrar" : "Abrir"}</button>
)}
/>
</div>
);
}Server Actions
De manera informativa, no se expone directamente la API de Server Actions, pero el componente las utiliza internamente para obtener tokens, configuración y registrar errores. A continuación se describen las funciones disponibles:
getRegionalSettings(tokenEndpoint?: string)
Propósito: Obtiene la configuración regional del bot, incluyendo las URLs de los canales disponibles.
const data = await getRegionalSettings(tokenEndpoint?: string);
console.log(data.channelUrlsById.directline); // URL de DirectLineRetorna: Configuración regional con URLs de canales disponibles.
getConversationToken(tokenEndpoint?: string)
Propósito: Obtiene el token de autenticación necesario para establecer la conexión con DirectLine.
const token = await getConversationToken(tokenEndpoint?: string);Retorna: Token de conversación válido para DirectLine.
getChatStoreConfig()
Propósito: Obtiene la configuración del store de Web Chat, incluyendo eventos iniciales y filtros.
const config = await getChatStoreConfig();
// config.eventConfig.startConversation - Evento para iniciar conversación
// config.filterConfig - Configuración de filtrosRetorna: Configuración del store con estado inicial y eventos.
logChatError(input)
Propósito: Registra errores del chat en el servidor para monitoreo y debugging.
await logChatError({
errorType: "connection_failed",
errorMessage: "No se pudo conectar al bot",
actionType: "initialize_chat",
userId: "optional-user-id",
});Parámetros:
errorType: Tipo de error (string)errorMessage: Mensaje descriptivo del erroractionType: Acción que causó el error (opcional)userId: ID del usuario (opcional)
Hook useChat
Funciones y Estado
Estado del Chat
Props del Hook
| Prop | Tipo | Default | Descripción |
| ------------------- | -------------- | ------------- | --------------------------------------------------------- |
| styleOptionsProps | StyleOptions | undefined | Opciones de estilo personalizadas para el chat (opcional) |
| entryPoint | string | Requerido | Punto de entrada para la conversación |
const {
isVisible, // boolean - Chat visible/oculto
isRestarting, // boolean - Estado de reinicio
chatKey, // number - Key para forzar re-render
webChatRef, // RefObject - Referencia al DOM del chat
styleOptionsMerged, // StyleOptions - Configuración de estilos
// ... funciones
} = useChat();Funciones Principales
handleChangeVisibility(visible: boolean)
Controla la visibilidad del chat.
handleChangeVisibility(true); // Mostrar chat
handleChangeVisibility(false); // Ocultar chatinitializeChat()
Inicializa el chat embebido obteniendo tokens y configuración.
- Obtiene configuración regional
- Solicita token de conversación
- Crea la instancia de DirectLine
- Renderiza Web Chat con estilos personalizados
restartConversation()
Reinicia completamente la conversación utilizando el patrón React key.
- Limpia referencias actuales
- Regenera el chatKey para forzar remount
- Reinicializa la conexión
cleanup()
Limpia la instancia del chat de forma segura.
Configuración de StyleOptions
Opciones de Color y Tema
interface StyleOptions {
// Colores principales
accent: string; // Color principal (#0078D4)
backgroundColor: string; // Fondo del chat (#e8e9eb)
// Configuración de burbujas del bot
bubbleBackground: string; // Fondo de mensajes del bot
bubbleBorderRadius: number; // Radio de borde de burbujas
bubbleTextColor: string; // Color del texto del bot
// Configuración de burbujas del usuario
bubbleFromUserBackground: string; // Fondo de mensajes del usuario
bubbleFromUserBorderRadius: number; // Radio de borde del usuario
bubbleFromUserTextColor: string; // Color del texto del usuario
// Configuración de avatares
botAvatarImage: string; // URL del avatar del bot
botAvatarInitials: string; // Iniciales del bot
userAvatarImage: string; // URL del avatar del usuario
userAvatarInitials: string; // Iniciales del usuario
userAvatarBackgroundColor: string; // Color de fondo del avatar
// Caja de entrada
sendBoxBackground: string; // Fondo de la caja de texto
sendBoxBorderTop: string; // Borde superior de la caja
sendBoxButtonColor: string; // Color del botón de enviar
sendBoxHeight: number; // Altura de la caja (50px)
// Animaciones
typingAnimationBackgroundImage: string; // GIF de animación de escritura
typingAnimationDuration: number; // Duración de la animación (ms)
typingAnimationHeight: number; // Altura de la animación
typingAnimationWidth: number; // Ancho de la animación
}Categorías de Configuración
Diseño y Layout
avatarSize: Tamaño de avatares (31px)bubbleMessageMaxWidth: Ancho máximo de burbujas (480px)paddingRegular: Padding estándar (10px)
Tipografía
primaryFont: Fuente principal del chatmonospaceFont: Fuente para código (Consolas)fontSizeSmall: Tamaño de fuente pequeña (70%)
Interactividad
suggestedActionBackgroundColor: Color de acciones sugeridassuggestedActionLayout: Layout de acciones ('flow', 'stacked', 'carousel')hideUploadButton: Ocultar botón de subir archivos
Animaciones y Feedback
spinnerAnimationHeight/Width: Dimensiones del spinner (16px)autoScrollSnapOnPage: Auto-scroll en nuevos mensajes
Tipos e Interfaces
StyleOptions
Interface completa para la configuración de estilos del Web Chat.
WebChatAction
Define las acciones disponibles para el store de Web Chat:
DIRECT_LINE/CONNECT_FULFILLED: Conexión establecidaDIRECT_LINE/POST_ACTIVITY: Enviar actividad/mensajeDIRECT_LINE/INCOMING_ACTIVITY: Recibir actividad/mensaje
WebChatStore
Interface para el store personalizado con middleware para manejo de eventos y filtros.
WebChatLib
Interface para la biblioteca global de Web Chat con métodos de creación y renderizado.
Styles
El componente usa su propio css interno.
/* Estilos base para AgentCrafta Chat */
.agentcrafta-chat-container {
position: fixed;
z-index: 999;
display: flex;
align-items: flex-end;
gap: 1rem;
}
/* Bottom Right: Chat a la izquierda, botón a la derecha */
.agentcrafta-chat-container.bottom-right {
bottom: 2rem;
right: 2rem;
flex-direction: row;
}
/* Bottom Left: Botón a la izquierda, chat a la derecha */
.agentcrafta-chat-container.bottom-left {
bottom: 2rem;
left: 2rem;
flex-direction: row-reverse;
}
/* Top Right: Chat a la izquierda, botón a la derecha */
.agentcrafta-chat-container.top-right {
top: 2rem;
right: 2rem;
flex-direction: row;
align-items: flex-start;
}
/* Top Left: Botón a la izquierda, chat a la derecha */
.agentcrafta-chat-container.top-left {
top: 2rem;
left: 2rem;
flex-direction: row-reverse;
align-items: flex-start;
}
.agentcrafta-chat-window {
height: 520px;
width: 450px;
overflow: hidden;
border-radius: 1rem;
background-color: white;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
transition: all 0.3s ease-in-out;
}
.agentcrafta-chat-window.bottom-right,
.agentcrafta-chat-window.bottom-left {
transform-origin: bottom;
}
.agentcrafta-chat-window.top-right,
.agentcrafta-chat-window.top-left {
transform-origin: top;
}
.agentcrafta-chat-window.visible {
transform: scale(1);
opacity: 1;
}
.agentcrafta-chat-window.hidden {
transform: scale(0.95);
opacity: 0;
pointer-events: none;
}
.agentcrafta-chat-header {
display: flex;
height: 3.5rem;
align-items: center;
justify-content: space-between;
padding: 0 1.25rem;
background-color: var(--primary-color, #0066cc);
color: white;
}
.agentcrafta-chat-header-content {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 1rem;
font-weight: 500;
}
.agentcrafta-chat-logo {
height: 1.75rem;
width: 1.75rem;
border-radius: 0.25rem;
}
.agentcrafta-chat-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.agentcrafta-chat-button {
border-radius: 0.5rem;
padding: 0.5rem;
transition: background-color 0.2s;
border: none;
background: transparent;
cursor: pointer;
color: inherit;
}
.agentcrafta-chat-button:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.agentcrafta-chat-button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
.agentcrafta-chat-content {
position: relative;
height: calc(100% - 56px);
width: 100%;
background-color: #f9fafb;
}
.agentcrafta-chat-loading {
position: absolute;
inset: 0;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(249, 250, 251, 0.8);
}
.agentcrafta-chat-loading-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
color: #4b5563;
}
.agentcrafta-chat-loading-spinner {
height: 2rem;
width: 2rem;
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.agentcrafta-chat-loading-text {
font-size: 0.875rem;
font-weight: 500;
}
/* Estilos para el botón flotante */
.agentcrafta-chat-fab {
height: 3.5rem;
width: 3.5rem;
border-radius: 9999px;
background-color: var(--primary-color, #0066cc);
color: white;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow:
0 10px 15px -3px rgba(0, 0, 0, 0.1),
0 4px 6px -2px rgba(0, 0, 0, 0.05);
transition: all 0.2s;
}
.agentcrafta-chat-fab:hover {
transform: scale(1.1);
box-shadow:
0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
.agentcrafta-chat-fab:active {
transform: scale(1.05);
}Limitaciones y Consideraciones
Compatibilidad de Bots: Solo funciona con bots que implementan Microsoft Bot Framework y DirectLine. No es compatible con bots de otros frameworks (e.g., Dialogflow puro, Rasa sin adaptador) a menos que se integre vía middleware personalizado. Bots no basados en Azure Bot Service o Power Virtual Agents pueden requerir ajustes adicionales.
Requisitos Técnicos:
- Requiere Next.js con componentes Client ('use client').
- No soporta entornos sin JavaScript (e.g., bots puramente server-side).
- Rendimiento limitado en conexiones lentas; el chat puede fallar si el token expira (vida típica: 30 minutos).
- Responsive solo en navegadores modernos; no optimizado para accesibilidad avanzada (e.g., lectores de pantalla pueden necesitar ajustes).
Seguridad y Privacidad:
- Los tokens de conversación son temporales, pero evita exponerlos en código público. El logging de errores registra datos sensibles (e.g., userId); asegúrate de cumplir con GDPR/CCPA.
- No incluye cifrado end-to-end; usa HTTPS obligatorio.
- Limitado a un chat por instancia; múltiples chats simultáneos no están soportados.
Mejores Prácticas:
- Prueba en entornos de desarrollo antes de producción.
- Monitorea errores vía Server Actions; no garantiza recuperación automática de fallos críticos.
- Para bots personalizados, valida el endpoint manualmente para compatibilidad con DirectLine.
Si encuentras limitaciones no cubiertas, consulta la documentación de Bot Framework.
Notas de Implementación
- Seguridad: El componente incluye validación de tokens y manejo de errores robusto
- Performance: Utiliza el patrón React key para reinicializaciones eficientes
- Accesibilidad: Incluye labels ARIA y soporte para navegación por teclado
- Responsive: Diseño adaptable para diferentes dispositivos
Troubleshooting
Problemas Comunes
- Chat no se inicializa: Verificar
TOKEN_AGENTE_URLen.env - Estilos no se aplican: Verificar variables CSS disponibles e importacion de estilos
- Errores de conexión: Revisar configuración de CORS y headers de seguridad
- Imágenes no cargan: Verificar rutas en carpeta
public/
