Proyecto ChatBot Con Gemini

This commit is contained in:
2025-11-18 14:34:26 -03:00
commit 83a48e16da
60 changed files with 13078 additions and 0 deletions

24
chatbot-widget/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
chatbot-widget/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
chatbot-widget/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>chatbot-widget</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

4672
chatbot-widget/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
{
"name": "chatbot-widget",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-markdown": "^10.1.0",
"rehype-sanitize": "^6.0.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@vitejs/plugin-react": "^5.1.0",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.3",
"vite": "^7.2.2"
}
}

View File

View File

@@ -0,0 +1,17 @@
import Chatbot from './components/Chatbot';
import './App.css';
function App() {
return (
<div className="App">
{/* El contenido de la página web iría aquí */}
<h1>Página de ejemplo de El Día</h1>
<p>Este es un contenido de demostración para el sitio.</p>
{/* Aquí integramos nuestro widget de chatbot */}
<Chatbot />
</div>
);
}
export default App;

View File

@@ -0,0 +1,140 @@
/* Estilos para la burbuja flotante del chat */
.chat-bubble {
position: fixed;
bottom: 25px;
right: 25px;
background-color: #007bff;
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
cursor: pointer;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
transition: transform 0.2s ease-in-out;
}
.chat-bubble:hover {
transform: scale(1.1);
}
/* Estilos para la ventana del chat */
.chat-window {
position: fixed;
bottom: 100px;
right: 25px;
width: 350px;
height: 500px;
background-color: white;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
display: flex;
flex-direction: column;
overflow: hidden;
transition: opacity 0.3s, transform 0.3s;
}
/* Estilos para el encabezado del chat */
.chat-header {
background-color: #007bff;
color: white;
padding: 15px;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
}
.chat-header .close-button {
background: none;
border: none;
color: white;
font-size: 24px;
font-weight: bold;
cursor: pointer;
padding: 0;
line-height: 1;
}
.chat-header .close-button:hover {
opacity: 0.8;
}
/* Contenedor de mensajes */
.messages-container {
flex-grow: 1;
padding: 15px;
overflow-y: auto;
display: flex;
flex-direction: column;
background-color: #f4f4f4;
}
/* Estilos individuales de los mensajes */
.message {
padding: 10px 15px;
border-radius: 20px;
margin-bottom: 10px;
max-width: 80%;
line-height: 1.4;
}
.message.user {
background-color: #007bff;
color: white;
align-self: flex-end;
}
.message.bot {
background-color: #e9e9eb;
color: #333;
align-self: flex-start;
}
/* Formulario de entrada de texto */
.input-form {
display: flex;
padding: 10px;
border-top: 1px solid #ccc;
}
.input-form input {
flex-grow: 1;
border: 1px solid #ddd;
padding: 10px;
border-radius: 20px;
margin-right: 10px;
outline: none;
}
.input-form button {
background-color: #007bff;
color: white;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 18px;
cursor: pointer;
}
.input-container {
position: relative;
flex-grow: 1;
display: flex;
flex-direction: column;
}
.input-container input {
padding-right: 8px; /* Espacio para que no se solape con el botón */
width: calc(100% - 28px); /* Ajuste del ancho del input */
}
.char-counter {
font-size: 0.75rem;
color: #888;
text-align: right;
margin-top: 4px;
margin-right: 15px;
}

View File

@@ -0,0 +1,203 @@
// src/components/Chatbot.tsx
import React, { useState, useEffect, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeSanitize from 'rehype-sanitize';
import './Chatbot.css';
interface Message {
text: string;
sender: 'user' | 'bot';
}
const MAX_CHARS = 200;
// Constante para la clave del localStorage
const CHAT_HISTORY_KEY = 'chatbot-history';
const Chatbot: React.FC = () => {
const [isOpen, setIsOpen] = useState(false);
const [messages, setMessages] = useState<Message[]>(() => {
try {
// 1. Intentamos obtener el historial guardado.
const savedHistory = localStorage.getItem(CHAT_HISTORY_KEY);
if (savedHistory) {
// 2. Si existe, lo parseamos y lo devolvemos para usarlo como estado inicial.
return JSON.parse(savedHistory);
}
} catch (error) {
console.error("No se pudo cargar el historial del chat desde localStorage:", error);
}
// 3. Si no hay nada guardado o hay un error, devolvemos el estado por defecto.
return [{ text: '¡Hola! Soy tu asistente virtual. ¿En qué puedo ayudarte hoy?', sender: 'bot' }];
});
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const messagesEndRef = useRef<null | HTMLDivElement>(null);
// Añadimos un useEffect para guardar los mensajes.
useEffect(() => {
try {
// Cada vez que el array de 'messages' cambie, lo guardamos en localStorage.
localStorage.setItem(CHAT_HISTORY_KEY, JSON.stringify(messages));
} catch (error) {
console.error("No se pudo guardar el historial del chat en localStorage:", error);
}
}, [messages]);
useEffect(() => {
// Solo intentamos hacer scroll si la ventana del chat está abierta.
if (isOpen) {
// Usamos un pequeño retardo para asegurar que el navegador haya renderizado
// completamente la ventana antes de intentar hacer el scroll.
// Esto previene problemas si hay animaciones CSS.
setTimeout(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, 50);
}
}, [messages, isOpen]);
const toggleChat = () => setIsOpen(!isOpen);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
};
const handleSendMessage = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (inputValue.trim() === '' || isLoading) return;
const userMessage: Message = { text: inputValue, sender: 'user' };
setMessages(prev => [...prev, userMessage]);
const messageToSend = inputValue;
setInputValue('');
setIsLoading(true);
const botMessagePlaceholder: Message = { text: '', sender: 'bot' };
setMessages(prev => [...prev, botMessagePlaceholder]);
try {
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/chat/stream-message`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: messageToSend }),
});
if (!response.ok || !response.body) {
throw new Error('Error en la respuesta del servidor.');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let accumulatedResponse = ''; // Variable para acumular el texto crudo
const readStream = async () => {
while (true) {
const { done, value } = await reader.read();
if (done) {
// El stream ha terminado, no hacemos nada más aquí.
break;
}
// Acumulamos la respuesta cruda que viene del backend
accumulatedResponse += decoder.decode(value);
try {
// Intentamos limpiar la respuesta acumulada
// 1. Parseamos como si fuera un array JSON
const parsedArray = JSON.parse(accumulatedResponse
// Añadimos un corchete de cierre por si el stream se corta a la mitad
.replace(/,$/, '') + ']');
// 2. Unimos los fragmentos del array en un solo texto
const cleanText = Array.isArray(parsedArray) ? parsedArray.join('') : accumulatedResponse;
// 3. Actualizamos el estado con el texto limpio
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
const updatedLastMessage = { ...lastMessage, text: cleanText };
return [...prev.slice(0, -1), updatedLastMessage];
});
} catch (e) {
// Si hay un error de parseo (porque el JSON aún no está completo),
// mostramos el texto sin los caracteres iniciales/finales.
const partiallyCleanedText = accumulatedResponse
.replace(/^\[?"|"?,"?|"?\]$/g, '')
.replace(/","/g, '');
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
const updatedLastMessage = { ...lastMessage, text: partiallyCleanedText };
return [...prev.slice(0, -1), updatedLastMessage];
});
}
}
};
await readStream();
} catch (error) {
console.error("Error al conectar con la API de streaming:", error);
const errorText = error instanceof Error ? error.message : 'Lo siento, no pude conectarme.';
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
const updatedLastMessage = { ...lastMessage, text: errorText };
return [...prev.slice(0, -1), updatedLastMessage];
});
} finally {
setIsLoading(false);
}
};
return (
<>
<div className="chat-bubble" onClick={toggleChat}>
<span>{isOpen ? 'X' : '💬'}</span>
</div>
{isOpen && (
<div className="chat-window">
<div className="chat-header">
<span>Asistente Virtual - El Día</span>
<button className="close-button" onClick={toggleChat}>&times;</button>
</div>
<div className="messages-container">
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.sender}`}>
<ReactMarkdown rehypePlugins={[rehypeSanitize]}>
{msg.text.replace(/\\n/g, "\n")}
</ReactMarkdown>
</div>
))}
<div ref={messagesEndRef} />
</div>
<form className="input-form" onSubmit={handleSendMessage}>
<div className="input-container">
<input
type="text"
placeholder={isLoading ? "Esperando respuesta..." : "Escribe tu consulta..."}
value={inputValue}
onChange={handleInputChange}
disabled={isLoading}
maxLength={MAX_CHARS}
/>
<div className="char-counter">
{inputValue.length} / {MAX_CHARS}
</div>
</div>
<button type="submit" disabled={isLoading}>
{isLoading ? '...' : '→'}
</button>
</form>
</div>
)}
</>
);
};
export default Chatbot;

View File

View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})