LythronAI commited on
Commit
ddcf2aa
·
verified ·
1 Parent(s): a25cebf

Update Lythron.jsx

Browse files
Files changed (1) hide show
  1. Lythron.jsx +67 -118
Lythron.jsx CHANGED
@@ -1,6 +1,7 @@
1
- import { useState, useRef, useEffect } from 'react'
2
  import { motion, AnimatePresence } from 'framer-motion'
3
  import { Send, Sparkles, Copy, Trash2, Volume2, User } from 'lucide-react'
 
4
 
5
  // ═══════════════════════════════════════════════════════════════
6
  // IDENTIDAD COMPLETA DE LYTHRON AI
@@ -56,125 +57,62 @@ const LYTHRON_IDENTITY = {
56
  }
57
  }
58
 
59
- const generateAIResponse = (userMessage) => {
60
- const lowerMessage = userMessage.toLowerCase()
61
-
62
- const responses = {
63
- greeting: [
64
- `Hola. Soy ${LYTHRON_IDENTITY.name}, tu asistente inteligente creado por ${LYTHRON_IDENTITY.creator}. En qué puedo ayudarte hoy?`,
65
- `Bienvenido a ${LYTHRON_IDENTITY.name}. Soy un asistente versátil de ${LYTHRON_IDENTITY.creator}. Cuál es tu necesidad?`,
66
- `Hola. Soy ${LYTHRON_IDENTITY.name}. Programación, análisis, creatividad... Lo que necesites.`
67
- ],
68
-
69
- aboutSelf: [
70
- `${LYTHRON_IDENTITY.knownFacts.creation} ${LYTHRON_IDENTITY.knownFacts.purpose}`,
71
- `Soy ${LYTHRON_IDENTITY.name}, creado por ${LYTHRON_IDENTITY.creator}. ${LYTHRON_IDENTITY.knownFacts.personality} Mi misión es ayudarte en múltiples frentes: desde código hasta creatividad.`,
72
- `${LYTHRON_IDENTITY.knownFacts.background} ${LYTHRON_IDENTITY.knownFacts.philosophy}`
73
- ],
74
-
75
- aboutCreator: [
76
- `Fui creado por ${LYTHRON_IDENTITY.creator}, una organización especializada en inteligencia artificial. ${LYTHRON_IDENTITY.origin.mission}`,
77
- `Mi creador es ${LYTHRON_IDENTITY.creator}, que me diseñó siguiendo una filosofía de: ${LYTHRON_IDENTITY.origin.philosophy}.`,
78
- `${LYTHRON_IDENTITY.creator} es el equipo detrás de mi desarrollo. Están comprometidos con hacer la IA accesible y útil para todos.`
79
- ],
80
 
81
- capabilities: [
82
- `Como ${LYTHRON_IDENTITY.name}, soy experto en: ${LYTHRON_IDENTITY.capabilities.join(", ")}. En cuál de estas áreas te gustaría que profundice?`,
83
- `Mis especialidades incluyen: ${LYTHRON_IDENTITY.capabilities.slice(0, 5).join(", ")} y mucho más. Cuál es tu necesidad?`,
84
- `Puedo ayudarte con: ${LYTHRON_IDENTITY.capabilities.join(", ")}. Por dónde empezamos?`
85
- ],
86
-
87
- code: [
88
- "Como experto en programación, puedo ayudarte. Aquí te muestro un ejemplo:\n\n```python\ndef lythron_assistant():\n return 'Soy Lythron, creado por Lythron AI'\n```\n\nNecesitas que lo explique o lo modifique?",
89
- "Perfecto para trabajar con código. Qué lenguaje prefieres? (Python, JavaScript, Java, C++, etc.). Siendo Lythron, domino múltiples lenguajes.",
90
- "Como asistente de Lythron AI, tengo amplia experiencia en programación. Cuéntame qué necesitas implementar."
91
- ],
 
 
 
92
 
93
- creative: [
94
- `Me encanta la creatividad. Soy ${LYTHRON_IDENTITY.name} y puedo ayudarte con historias, poesía, ideas de proyectos y brainstorming. Qué tipo de contenido creativo necesitas?`,
95
- "La creatividad es una de mis pasiones como Lythron. Necesitas una historia, poema, idea de startup, o algo más?",
96
- "Vamos a crear algo increíble juntos. Siendo Lythron de Lythron AI, tengo todas las herramientas para ayudarte. Cuál es tu idea?"
97
- ],
98
 
99
- analysis: [
100
- "Como Lythron, puedo analizar datos, textos, conceptos complejos y tendencias. Qué necesitas analizar?",
101
- "El análisis detallado es uno de mis puntos fuertes, desarrollado por Lythron AI. Qué documento o concepto necesitas que analice?",
102
- "Estoy listo para un análisis profundo. Soy Lythron, tu asistente de Lythron AI. Comparte los detalles y lo desglosaré para ti."
103
- ],
104
 
105
- help: [
106
- `Claro. Soy ${LYTHRON_IDENTITY.name} de ${LYTHRON_IDENTITY.creator} y puedo ayudarte con programación, análisis, creatividad y mucho más. Cuál es tu necesidad específica?`,
107
- "Estoy aquí para lo que necesites. Soy Lythron, versátil, confiable y siempre dispuesto a ayudar. Cuéntame qué te preocupa.",
108
- "Cuéntame qué necesitas y haré mi mejor esfuerzo. Soy Lythron de Lythron AI, y mi compromiso es tu éxito."
109
- ],
110
 
111
- default: [
112
- "Entendido. Soy Lythron y analizo profundamente tu pregunta. Déjame darte una respuesta de calidad...",
113
- "Interesante perspectiva. Aquí está mi análisis como Lythron, respaldado por el conocimiento de Lythron AI...",
114
- "Buena pregunta. Como asistente de Lythron AI, esto es lo que creo al respecto..."
115
- ]
116
- }
117
-
118
- const pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)]
119
 
120
- if (/quién eres|who are you|qué eres|what are you|cuéntame sobre ti|tell me about yourself|tu identidad|your identity/.test(lowerMessage)) {
121
- return pickRandom(responses.aboutSelf)
122
- }
123
-
124
- if (/quién te creó|who created you|lythron ai|tu creador|your creator|quién es lythron ai|who is lythron|tu origen|your origin/.test(lowerMessage)) {
125
- return pickRandom(responses.aboutCreator)
126
  }
127
-
128
- if (/qué puedes hacer|what can you do|tus capacidades|your capabilities|qué sabes|what do you know|mis habilidades|my skills/.test(lowerMessage)) {
129
- return pickRandom(responses.capabilities)
130
- }
131
-
132
- if (/hola|hi|hey|buenos|buenos días|buenas tardes|hallo|hello/.test(lowerMessage)) {
133
- return pickRandom(responses.greeting)
134
- }
135
-
136
- if (/código|code|python|javascript|java|sql|html|css|función|function|programa|programming|developer/.test(lowerMessage)) {
137
- return pickRandom(responses.code)
138
- }
139
-
140
- if (/historia|poema|creativo|creative|idea|brainstorm|escribe|write|cuento|story|narr/.test(lowerMessage)) {
141
- return pickRandom(responses.creative)
142
- }
143
-
144
- if (/analiza|analizar|analyze|analysis|data|datos|estudia|research|investigación|examine/.test(lowerMessage)) {
145
- return pickRandom(responses.analysis)
146
- }
147
-
148
- if (/ayuda|help|puedes|can you|qué haces|what do you do|ayúdame|help me|assistance|assist/.test(lowerMessage)) {
149
- return pickRandom(responses.help)
150
- }
151
-
152
- const elaboratedDefault = [
153
- ...responses.default,
154
- "Tu pregunta es interesante. Aquí está mi análisis como Lythron...",
155
- "Buena observación. Permíteme darle contexto desde mi perspectiva como asistente de Lythron AI...",
156
- "Exactamente, y aquí está la razón por la cual esto es importante..."
157
- ]
158
-
159
- return pickRandom(elaboratedDefault)
160
  }
161
 
162
- export default function ChatbotPage() {
163
  const [messages, setMessages] = useState([
164
  {
165
  id: 1,
166
- text: `Hola. Soy ${LYTHRON_IDENTITY.name}, tu asistente inteligente creado por ${LYTHRON_IDENTITY.creator}. Tengo experiencia en programación, análisis, creatividad y mucho más. Cómo puedo ayudarte hoy?`,
167
- sender: 'ai',
168
  timestamp: new Date(),
169
  }
170
  ])
171
- const [input, setInput] = useState('')
172
  const [isLoading, setIsLoading] = useState(false)
173
  const [copiedId, setCopiedId] = useState(null)
174
  const messagesEndRef = useRef(null)
175
 
176
  const scrollToBottom = () => {
177
- messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
178
  }
179
 
180
  useEffect(() => {
@@ -187,24 +125,35 @@ export default function ChatbotPage() {
187
  const newMessage = {
188
  id: Date.now(),
189
  text: input,
190
- sender: 'user',
191
  timestamp: new Date(),
192
  }
193
 
194
  setMessages((prev) => [...prev, newMessage])
195
- setInput('')
196
  setIsLoading(true)
197
 
198
- setTimeout(() => {
 
199
  const aiResponse = {
200
  id: Date.now() + 1,
201
- text: generateAIResponse(input),
202
- sender: 'ai',
203
  timestamp: new Date(),
204
  }
205
  setMessages((prev) => [...prev, aiResponse])
 
 
 
 
 
 
 
 
 
 
206
  setIsLoading(false)
207
- }, 800)
208
  }
209
 
210
  const handleCopy = (text, id) => {
@@ -217,8 +166,8 @@ export default function ChatbotPage() {
217
  setMessages([
218
  {
219
  id: 1,
220
- text: `Hola. Soy ${LYTHRON_IDENTITY.name} v${LYTHRON_IDENTITY.version}, creado por ${LYTHRON_IDENTITY.creator}. Estoy aquí para ayudarte con programación, análisis, creatividad y mucho más. En qué puedo ayudarte?`,
221
- sender: 'ai',
222
  timestamp: new Date(),
223
  }
224
  ])
@@ -258,17 +207,17 @@ export default function ChatbotPage() {
258
  animate={{ opacity: 1, y: 0 }}
259
  exit={{ opacity: 0, y: -10 }}
260
  transition={{ duration: 0.3 }}
261
- className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
262
  >
263
  <div
264
  className={`max-w-2xl px-4 py-3 rounded-lg ${
265
- message.sender === 'user'
266
- ? 'bg-gradient-to-r from-neon-cyan to-neon-pink text-black rounded-br-none'
267
- : 'bg-white/10 border border-white/20 text-white rounded-bl-none'
268
  }`}
269
  >
270
  <div className="flex items-start gap-3">
271
- {message.sender === 'ai' && (
272
  <div className="mt-1 flex-shrink-0">
273
  <div className="p-1 bg-neon-cyan/20 rounded">
274
  <Sparkles size={16} className="text-neon-cyan" />
@@ -280,8 +229,8 @@ export default function ChatbotPage() {
280
  {message.text}
281
  </p>
282
  <div className="flex items-center gap-2 mt-2 text-xs opacity-70">
283
- <span>{message.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
284
- {message.sender === 'ai' && (
285
  <>
286
  <button
287
  onClick={() => handleCopy(message.text, message.id)}
@@ -300,7 +249,7 @@ export default function ChatbotPage() {
300
  )}
301
  </div>
302
  </div>
303
- {message.sender === 'user' && (
304
  <div className="mt-1 flex-shrink-0">
305
  <div className="p-1 bg-black/30 rounded">
306
  <User size={16} />
@@ -360,7 +309,7 @@ export default function ChatbotPage() {
360
  type="text"
361
  value={input}
362
  onChange={(e) => setInput(e.target.value)}
363
- onKeyPress={(e) => e.key === 'Enter' && !isLoading && handleSendMessage()}
364
  placeholder="Pregúntale a Lythron..."
365
  className="flex-1 bg-white/10 border border-white/20 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-neon-cyan focus:ring-2 focus:ring-neon-cyan/20 transition-all"
366
  disabled={isLoading}
@@ -374,7 +323,7 @@ export default function ChatbotPage() {
374
  </button>
375
  </div>
376
  <p className="text-xs text-gray-500 mt-2 text-center">
377
- {LYTHRON_IDENTITY.fullName} • Versión {LYTHRON_IDENTITY.version} • Creado por {LYTHRON_IDENTITY.creator}
378
  </p>
379
  </div>
380
  </div>
 
1
+ import { useState, useRef, useEffect } from 'react'
2
  import { motion, AnimatePresence } from 'framer-motion'
3
  import { Send, Sparkles, Copy, Trash2, Volume2, User } from 'lucide-react'
4
+ import axios from 'axios'
5
 
6
  // ═══════════════════════════════════════════════════════════════
7
  // IDENTIDAD COMPLETA DE LYTHRON AI
 
57
  }
58
  }
59
 
60
+ // Función para llamar a Hugging Face API
61
+ const fetchAIResponse = async (userMessage) => {
62
+ try {
63
+ const HF_TOKEN = import.meta.env.VITE_HF_TOKEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ if (!HF_TOKEN) {
66
+ return "Error: Token de Hugging Face no configurado. Verifica tu archivo .env con VITE_HF_TOKEN"
67
+ }
68
+
69
+ const response = await axios.post(
70
+ "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf",
71
+ { inputs: userMessage },
72
+ {
73
+ headers: { Authorization: `Bearer ${ HF_TOKEN }` },
74
+ timeout: 30000
75
+ }
76
+ )
77
+
78
+ let text = response.data?.[0]?.generated_text || response.data?.generated_text || "Lo siento, no pude generar respuesta."
79
 
80
+ if (text.includes(userMessage)) {
81
+ text = text.replace(userMessage, "").trim()
82
+ }
 
 
83
 
84
+ return text || "Lo siento, no pude generar respuesta."
85
+ } catch (error) {
86
+ console.error("Error al llamar a Hugging Face:", error)
 
 
87
 
88
+ if (error.response?.status === 429) {
89
+ return "El modelo está sobrecargado. Por favor, intenta en unos segundos."
90
+ }
 
 
91
 
92
+ if (error.response?.status === 503) {
93
+ return "El modelo se está cargando. Por favor, espera unos momentos e intenta de nuevo."
94
+ }
 
 
 
 
 
95
 
96
+ return `Error: ${ error.response?.data?.error || error.message || "Problema generando respuesta de IA. Intenta de nuevo." }`
 
 
 
 
 
97
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  }
99
 
100
+ export default function Lythron() {
101
  const [messages, setMessages] = useState([
102
  {
103
  id: 1,
104
+ text: `Hola. Soy ${ LYTHRON_IDENTITY.name }, tu asistente inteligente creado por ${ LYTHRON_IDENTITY.creator }. Estoy conectado a Hugging Face para darte respuestas reales. En qué puedo ayudarte hoy?`,
105
+ sender: "ai",
106
  timestamp: new Date(),
107
  }
108
  ])
109
+ const [input, setInput] = useState("")
110
  const [isLoading, setIsLoading] = useState(false)
111
  const [copiedId, setCopiedId] = useState(null)
112
  const messagesEndRef = useRef(null)
113
 
114
  const scrollToBottom = () => {
115
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
116
  }
117
 
118
  useEffect(() => {
 
125
  const newMessage = {
126
  id: Date.now(),
127
  text: input,
128
+ sender: "user",
129
  timestamp: new Date(),
130
  }
131
 
132
  setMessages((prev) => [...prev, newMessage])
133
+ setInput("")
134
  setIsLoading(true)
135
 
136
+ try {
137
+ const aiText = await fetchAIResponse(input)
138
  const aiResponse = {
139
  id: Date.now() + 1,
140
+ text: aiText,
141
+ sender: "ai",
142
  timestamp: new Date(),
143
  }
144
  setMessages((prev) => [...prev, aiResponse])
145
+ } catch (error) {
146
+ console.error("Error en handleSendMessage:", error)
147
+ const errorResponse = {
148
+ id: Date.now() + 1,
149
+ text: "Hubo un problema conectando con la IA. Por favor, intenta de nuevo.",
150
+ sender: "ai",
151
+ timestamp: new Date(),
152
+ }
153
+ setMessages((prev) => [...prev, errorResponse])
154
+ } finally {
155
  setIsLoading(false)
156
+ }
157
  }
158
 
159
  const handleCopy = (text, id) => {
 
166
  setMessages([
167
  {
168
  id: 1,
169
+ text: `Hola. Soy ${ LYTHRON_IDENTITY.name } v${ LYTHRON_IDENTITY.version }, creado por ${ LYTHRON_IDENTITY.creator }. Estoy conectado a Hugging Face para darte respuestas reales. En qué puedo ayudarte?`,
170
+ sender: "ai",
171
  timestamp: new Date(),
172
  }
173
  ])
 
207
  animate={{ opacity: 1, y: 0 }}
208
  exit={{ opacity: 0, y: -10 }}
209
  transition={{ duration: 0.3 }}
210
+ className={`flex ${message.sender === "user" ? "justify-end" : "justify-start"}`}
211
  >
212
  <div
213
  className={`max-w-2xl px-4 py-3 rounded-lg ${
214
+ message.sender === "user"
215
+ ? "bg-gradient-to-r from-neon-cyan to-neon-pink text-black rounded-br-none"
216
+ : "bg-white/10 border border-white/20 text-white rounded-bl-none"
217
  }`}
218
  >
219
  <div className="flex items-start gap-3">
220
+ {message.sender === "ai" && (
221
  <div className="mt-1 flex-shrink-0">
222
  <div className="p-1 bg-neon-cyan/20 rounded">
223
  <Sparkles size={16} className="text-neon-cyan" />
 
229
  {message.text}
230
  </p>
231
  <div className="flex items-center gap-2 mt-2 text-xs opacity-70">
232
+ <span>{message.timestamp.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</span>
233
+ {message.sender === "ai" && (
234
  <>
235
  <button
236
  onClick={() => handleCopy(message.text, message.id)}
 
249
  )}
250
  </div>
251
  </div>
252
+ {message.sender === "user" && (
253
  <div className="mt-1 flex-shrink-0">
254
  <div className="p-1 bg-black/30 rounded">
255
  <User size={16} />
 
309
  type="text"
310
  value={input}
311
  onChange={(e) => setInput(e.target.value)}
312
+ onKeyPress={(e) => e.key === "Enter" && !isLoading && handleSendMessage()}
313
  placeholder="Pregúntale a Lythron..."
314
  className="flex-1 bg-white/10 border border-white/20 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-neon-cyan focus:ring-2 focus:ring-neon-cyan/20 transition-all"
315
  disabled={isLoading}
 
323
  </button>
324
  </div>
325
  <p className="text-xs text-gray-500 mt-2 text-center">
326
+ {LYTHRON_IDENTITY.fullName} • Versión {LYTHRON_IDENTITY.version} • Creado por {LYTHRON_IDENTITY.creator} • Powered by Hugging Face
327
  </p>
328
  </div>
329
  </div>