first and real commit
This commit is contained in:
BIN
api/__pycache__/api.cpython-314.pyc
Normal file
BIN
api/__pycache__/api.cpython-314.pyc
Normal file
Binary file not shown.
BIN
api/__pycache__/router.cpython-314.pyc
Normal file
BIN
api/__pycache__/router.cpython-314.pyc
Normal file
Binary file not shown.
BIN
api/__pycache__/routes.cpython-314.pyc
Normal file
BIN
api/__pycache__/routes.cpython-314.pyc
Normal file
Binary file not shown.
17
api/api.py
Normal file
17
api/api.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from api.routes.root import router as rootRouter
|
||||||
|
from api.routes.ai import router as aiRouter
|
||||||
|
|
||||||
|
|
||||||
|
application = FastAPI()
|
||||||
|
|
||||||
|
application.add_middleware(CORSMiddleware,
|
||||||
|
allow_origins=['*'],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_headers=['*'],
|
||||||
|
allow_methods=['GET','POST'])
|
||||||
|
|
||||||
|
|
||||||
|
application.include_router(router=rootRouter, prefix='')
|
||||||
|
application.include_router(router=aiRouter, prefix='/ai')
|
||||||
BIN
api/routes/__pycache__/ai.cpython-314.pyc
Normal file
BIN
api/routes/__pycache__/ai.cpython-314.pyc
Normal file
Binary file not shown.
BIN
api/routes/__pycache__/root.cpython-314.pyc
Normal file
BIN
api/routes/__pycache__/root.cpython-314.pyc
Normal file
Binary file not shown.
89
api/routes/ai.py
Normal file
89
api/routes/ai.py
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import anthropic, json
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from os import getenv
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
load_dotenv(".env_file")
|
||||||
|
client = anthropic.Anthropic(api_key=getenv('CLAUDE_KEY'))
|
||||||
|
|
||||||
|
with open('/home/rodo/Documents/py/LittleAPI/list.json', 'r') as f:
|
||||||
|
config = json.load(f)
|
||||||
|
pdf_file_ids = config.get("files", [])
|
||||||
|
|
||||||
|
@router.post("/using_docs", tags=["AI"])
|
||||||
|
async def send_message_using_docs(message:str):
|
||||||
|
"""
|
||||||
|
Envía un mensaje usando documentos PDF almacenados.
|
||||||
|
|
||||||
|
- **message**: El mensaje de texto a procesar
|
||||||
|
- **Retorna**: Stream de texto con la respuesta de Claude
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
content = [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": message
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
for file_id in pdf_file_ids:
|
||||||
|
content.append(
|
||||||
|
{
|
||||||
|
"type": "document",
|
||||||
|
"source" : {
|
||||||
|
"type" : "file",
|
||||||
|
"file_id": file_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def event_generator():
|
||||||
|
with client.beta.messages.stream(
|
||||||
|
model="claude-haiku-4-5",
|
||||||
|
max_tokens=2048,
|
||||||
|
messages=[{
|
||||||
|
"role": "user",
|
||||||
|
"content": content
|
||||||
|
}],
|
||||||
|
betas=["files-api-2025-04-14"],
|
||||||
|
) as stream:
|
||||||
|
for text in stream.text_stream:
|
||||||
|
yield text
|
||||||
|
return StreamingResponse(event_generator(), media_type="text/plain")
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
@router.post("/", tags=["AI"])
|
||||||
|
async def send_message(message:str):
|
||||||
|
"""
|
||||||
|
Envía un mensaje normal a Claude.
|
||||||
|
|
||||||
|
- **message**: El mensaje de texto a procesar
|
||||||
|
- **Retorna**: Stream de texto con la respuesta de Claude
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
content = [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": message
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
def event_generator():
|
||||||
|
with client.beta.messages.stream(
|
||||||
|
model="claude-haiku-4-5",
|
||||||
|
max_tokens=512,
|
||||||
|
messages=[{
|
||||||
|
"role": "user",
|
||||||
|
"content": content
|
||||||
|
}],
|
||||||
|
) as stream:
|
||||||
|
for text in stream.text_stream:
|
||||||
|
yield text
|
||||||
|
|
||||||
|
return StreamingResponse(event_generator(), media_type="text/plain")
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
9
api/routes/root.py
Normal file
9
api/routes/root.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get('/', tags=["root"])
|
||||||
|
def root():
|
||||||
|
return {
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
56
frontend/README.md
Normal file
56
frontend/README.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# LittleAPI Frontend
|
||||||
|
|
||||||
|
Frontend independiente en PyQt6 para consumir la API del proyecto LittleAPI.
|
||||||
|
|
||||||
|
## Instalación
|
||||||
|
|
||||||
|
1. Navega a la carpeta frontend:
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Crea un entorno virtual (opcional pero recomendado):
|
||||||
|
```bash
|
||||||
|
python -m venv venv
|
||||||
|
source venv/bin/activate # En Windows: venv\Scripts\activate
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Instala las dependencias:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Uso
|
||||||
|
|
||||||
|
1. Asegúrate de que el backend esté corriendo en `http://localhost:9900`:
|
||||||
|
```bash
|
||||||
|
python main.py # En la carpeta raíz del proyecto
|
||||||
|
```
|
||||||
|
|
||||||
|
2. En otra terminal, ejecuta el frontend desde la carpeta `frontend`:
|
||||||
|
```bash
|
||||||
|
python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Características
|
||||||
|
|
||||||
|
- ✓ Verificación del estado de la API
|
||||||
|
- ✓ Envío de mensajes normales
|
||||||
|
- ✓ Envío de mensajes usando documentos
|
||||||
|
- ✓ Respuestas en streaming
|
||||||
|
- ✓ Interfaz simple y limpia con PyQt6
|
||||||
|
- ✓ Manejo de errores de conexión
|
||||||
|
|
||||||
|
## Estructura
|
||||||
|
|
||||||
|
- `main.py` - Aplicación principal con interfaz PyQt6
|
||||||
|
- `config.py` - Configuración (URLs, dimensiones, etc.)
|
||||||
|
- `requirements.txt` - Dependencias del proyecto
|
||||||
|
|
||||||
|
## Configuración
|
||||||
|
|
||||||
|
Edita `config.py` para cambiar:
|
||||||
|
- URL de la API
|
||||||
|
- Dimensiones de la ventana
|
||||||
|
- Timeouts
|
||||||
|
- Otros parámetros
|
||||||
BIN
frontend/__pycache__/config.cpython-314.pyc
Normal file
BIN
frontend/__pycache__/config.cpython-314.pyc
Normal file
Binary file not shown.
18
frontend/config.py
Normal file
18
frontend/config.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
from dotenv import load_dotenv
|
||||||
|
from os import getenv
|
||||||
|
|
||||||
|
load_dotenv('.env_file')
|
||||||
|
|
||||||
|
# Configuración de la aplicación frontend
|
||||||
|
API_BASE_URL = f"http://{getenv('HOST')}:{getenv('PORT')}"
|
||||||
|
API_HEALTH_ENDPOINT = f"{API_BASE_URL}/"
|
||||||
|
API_MESSAGE_ENDPOINT = f"{API_BASE_URL}/ai/"
|
||||||
|
API_MESSAGE_DOCS_ENDPOINT = f"{API_BASE_URL}/ai/using_docs"
|
||||||
|
|
||||||
|
# Configuración de la ventana
|
||||||
|
WINDOW_WIDTH = 900
|
||||||
|
WINDOW_HEIGHT = 700
|
||||||
|
WINDOW_TITLE = "LittleAPI Frontend"
|
||||||
|
|
||||||
|
# Configuración de timeout para requests
|
||||||
|
REQUEST_TIMEOUT = 30
|
||||||
349
frontend/main.py
Normal file
349
frontend/main.py
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
import sys
|
||||||
|
import requests
|
||||||
|
import markdown
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QApplication,
|
||||||
|
QMainWindow,
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QTextEdit,
|
||||||
|
QTextBrowser,
|
||||||
|
QPushButton,
|
||||||
|
QLabel,
|
||||||
|
QRadioButton,
|
||||||
|
QButtonGroup,
|
||||||
|
QMessageBox,
|
||||||
|
)
|
||||||
|
from PyQt6.QtCore import Qt, QThread, pyqtSignal
|
||||||
|
from PyQt6.QtGui import QFont
|
||||||
|
from config import (
|
||||||
|
API_BASE_URL,
|
||||||
|
API_HEALTH_ENDPOINT,
|
||||||
|
API_MESSAGE_ENDPOINT,
|
||||||
|
API_MESSAGE_DOCS_ENDPOINT,
|
||||||
|
WINDOW_WIDTH,
|
||||||
|
WINDOW_HEIGHT,
|
||||||
|
WINDOW_TITLE,
|
||||||
|
REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def markdown_to_html(text):
|
||||||
|
"""Convierte markdown a HTML con soporte para tablas, títulos, negritas y cursivas"""
|
||||||
|
html = markdown.markdown(
|
||||||
|
text,
|
||||||
|
extensions=['tables', 'sane_lists', 'extra']
|
||||||
|
)
|
||||||
|
# Agregar CSS para mejorar la presentación
|
||||||
|
styled_html = f"""
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<style>
|
||||||
|
body {{
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
color: #333;
|
||||||
|
line-height: 1.5;
|
||||||
|
margin: 0;
|
||||||
|
padding: 10px;
|
||||||
|
}}
|
||||||
|
h1, h2, h3, h4, h5, h6 {{
|
||||||
|
color: #2c3e50;
|
||||||
|
margin-top: 20px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}}
|
||||||
|
h1 {{ font-size: 1.8em; border-bottom: 2px solid #3498db; padding-bottom: 5px; }}
|
||||||
|
h2 {{ font-size: 1.5em; border-bottom: 1px solid #bdc3c7; padding-bottom: 3px; }}
|
||||||
|
h3 {{ font-size: 1.3em; }}
|
||||||
|
strong, b {{ color: #2c3e50; font-weight: bold; }}
|
||||||
|
em, i {{ font-style: italic; color: #555; }}
|
||||||
|
p {{ margin: 10px 0; }}
|
||||||
|
ul, ol {{
|
||||||
|
margin: 10px 0;
|
||||||
|
padding-left: 30px;
|
||||||
|
}}
|
||||||
|
li {{ margin: 5px 0; }}
|
||||||
|
table {{
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 15px 0;
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
}}
|
||||||
|
th {{
|
||||||
|
background-color: #3498db;
|
||||||
|
color: white;
|
||||||
|
padding: 12px;
|
||||||
|
text-align: left;
|
||||||
|
font-weight: bold;
|
||||||
|
}}
|
||||||
|
td {{
|
||||||
|
border: 1px solid #bdc3c7;
|
||||||
|
padding: 10px 12px;
|
||||||
|
}}
|
||||||
|
tr:nth-child(even) {{
|
||||||
|
background-color: #ecf0f1;
|
||||||
|
}}
|
||||||
|
tr:hover {{
|
||||||
|
background-color: #d5dbdb;
|
||||||
|
}}
|
||||||
|
code {{
|
||||||
|
background-color: #f4f4f4;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
color: #e74c3c;
|
||||||
|
}}
|
||||||
|
pre {{
|
||||||
|
background-color: #2c3e50;
|
||||||
|
color: #ecf0f1;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 5px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 10px 0;
|
||||||
|
}}
|
||||||
|
pre code {{
|
||||||
|
background-color: transparent;
|
||||||
|
color: #ecf0f1;
|
||||||
|
padding: 0;
|
||||||
|
}}
|
||||||
|
blockquote {{
|
||||||
|
border-left: 4px solid #3498db;
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 10px 15px;
|
||||||
|
background-color: #ecf0f1;
|
||||||
|
}}
|
||||||
|
a {{
|
||||||
|
color: #3498db;
|
||||||
|
text-decoration: none;
|
||||||
|
}}
|
||||||
|
a:hover {{
|
||||||
|
text-decoration: underline;
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{html}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
return styled_html
|
||||||
|
|
||||||
|
|
||||||
|
class APIWorker(QThread):
|
||||||
|
"""Thread worker para hacer requests a la API sin bloquear la UI"""
|
||||||
|
response_received = pyqtSignal(str)
|
||||||
|
error_occurred = pyqtSignal(str)
|
||||||
|
finished = pyqtSignal()
|
||||||
|
|
||||||
|
def __init__(self, endpoint, message, use_streaming=True):
|
||||||
|
super().__init__()
|
||||||
|
self.endpoint = endpoint
|
||||||
|
self.message = message
|
||||||
|
self.use_streaming = use_streaming
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
try:
|
||||||
|
if self.use_streaming:
|
||||||
|
self._handle_streaming_response()
|
||||||
|
else:
|
||||||
|
self._handle_normal_response()
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
self.error_occurred.emit(
|
||||||
|
"Error de conexión: No se puede conectar a la API.\n"
|
||||||
|
f"Asegúrate de que el servidor esté corriendo en {API_BASE_URL}"
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
self.error_occurred.emit("Error de timeout: La API tardó demasiado en responder.")
|
||||||
|
except Exception as e:
|
||||||
|
self.error_occurred.emit(f"Error: {str(e)}")
|
||||||
|
finally:
|
||||||
|
self.finished.emit()
|
||||||
|
|
||||||
|
def _handle_streaming_response(self):
|
||||||
|
"""Maneja respuestas en streaming"""
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
self.endpoint,
|
||||||
|
params={"message": self.message},
|
||||||
|
stream=True,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
for chunk in response.iter_content(decode_unicode=True, chunk_size=10):
|
||||||
|
if chunk:
|
||||||
|
self.response_received.emit(chunk)
|
||||||
|
except Exception as e:
|
||||||
|
raise e
|
||||||
|
|
||||||
|
def _handle_normal_response(self):
|
||||||
|
"""Maneja respuestas normales"""
|
||||||
|
response = requests.post(
|
||||||
|
self.endpoint,
|
||||||
|
params={"message": self.message},
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
self.response_received.emit(response.text)
|
||||||
|
|
||||||
|
|
||||||
|
class MainWindow(QMainWindow):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.setWindowTitle(WINDOW_TITLE)
|
||||||
|
self.setGeometry(100, 100, WINDOW_WIDTH, WINDOW_HEIGHT)
|
||||||
|
self.worker = None
|
||||||
|
self.api_status = False
|
||||||
|
self.response_buffer = "" # Buffer para acumular la respuesta
|
||||||
|
|
||||||
|
self.initUI()
|
||||||
|
self.check_api_status()
|
||||||
|
|
||||||
|
def initUI(self):
|
||||||
|
"""Inicializa la interfaz de usuario"""
|
||||||
|
central_widget = QWidget()
|
||||||
|
self.setCentralWidget(central_widget)
|
||||||
|
|
||||||
|
main_layout = QVBoxLayout()
|
||||||
|
|
||||||
|
# Sección de estado
|
||||||
|
status_layout = QHBoxLayout()
|
||||||
|
self.status_label = QLabel("● Estado: Verificando...")
|
||||||
|
self.status_label.setFont(QFont("Arial", 10))
|
||||||
|
status_layout.addWidget(self.status_label)
|
||||||
|
status_layout.addStretch()
|
||||||
|
refresh_btn = QPushButton("Actualizar estado")
|
||||||
|
refresh_btn.clicked.connect(self.check_api_status)
|
||||||
|
status_layout.addWidget(refresh_btn)
|
||||||
|
main_layout.addLayout(status_layout)
|
||||||
|
|
||||||
|
# Selector de modo
|
||||||
|
mode_layout = QHBoxLayout()
|
||||||
|
mode_label = QLabel("Modo:")
|
||||||
|
mode_layout.addWidget(mode_label)
|
||||||
|
|
||||||
|
self.mode_group = QButtonGroup()
|
||||||
|
self.radio_normal = QRadioButton("Mensaje normal")
|
||||||
|
self.radio_docs = QRadioButton("Con documentos")
|
||||||
|
self.radio_normal.setChecked(True)
|
||||||
|
self.mode_group.addButton(self.radio_normal)
|
||||||
|
self.mode_group.addButton(self.radio_docs)
|
||||||
|
mode_layout.addWidget(self.radio_normal)
|
||||||
|
mode_layout.addWidget(self.radio_docs)
|
||||||
|
mode_layout.addStretch()
|
||||||
|
main_layout.addLayout(mode_layout)
|
||||||
|
|
||||||
|
# Área de entrada
|
||||||
|
input_label = QLabel("Mensaje:")
|
||||||
|
main_layout.addWidget(input_label)
|
||||||
|
self.input_text = QTextEdit()
|
||||||
|
self.input_text.setPlaceholderText("Escribe tu mensaje aquí...")
|
||||||
|
self.input_text.setMaximumHeight(120)
|
||||||
|
main_layout.addWidget(self.input_text)
|
||||||
|
|
||||||
|
# Botones de acción
|
||||||
|
button_layout = QHBoxLayout()
|
||||||
|
self.send_btn = QPushButton("Enviar")
|
||||||
|
self.send_btn.clicked.connect(self.send_message)
|
||||||
|
self.clear_btn = QPushButton("Limpiar")
|
||||||
|
self.clear_btn.clicked.connect(self.clear_all)
|
||||||
|
button_layout.addWidget(self.send_btn)
|
||||||
|
button_layout.addWidget(self.clear_btn)
|
||||||
|
button_layout.addStretch()
|
||||||
|
main_layout.addLayout(button_layout)
|
||||||
|
|
||||||
|
# Área de respuesta
|
||||||
|
response_label = QLabel("Respuesta:")
|
||||||
|
main_layout.addWidget(response_label)
|
||||||
|
self.response_text = QTextBrowser()
|
||||||
|
self.response_text.setMarkdown("La respuesta de la API aparecerá aquí...")
|
||||||
|
main_layout.addWidget(self.response_text)
|
||||||
|
|
||||||
|
central_widget.setLayout(main_layout)
|
||||||
|
|
||||||
|
def check_api_status(self):
|
||||||
|
"""Verifica el estado del API"""
|
||||||
|
try:
|
||||||
|
response = requests.get(API_HEALTH_ENDPOINT, timeout=REQUEST_TIMEOUT)
|
||||||
|
if response.status_code == 200:
|
||||||
|
self.api_status = True
|
||||||
|
self.status_label.setText("● Estado: API conectada ✓")
|
||||||
|
self.status_label.setStyleSheet("color: green;")
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.api_status = False
|
||||||
|
self.status_label.setText("● Estado: API desconectada ✗")
|
||||||
|
self.status_label.setStyleSheet("color: red;")
|
||||||
|
|
||||||
|
def send_message(self):
|
||||||
|
"""Envía el mensaje a la API"""
|
||||||
|
if not self.api_status:
|
||||||
|
QMessageBox.warning(self, "Error", "La API no está conectada.")
|
||||||
|
return
|
||||||
|
|
||||||
|
message = self.input_text.toPlainText().strip()
|
||||||
|
if not message:
|
||||||
|
QMessageBox.warning(self, "Advertencia", "Por favor escribe un mensaje.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Determinar endpoint
|
||||||
|
use_docs = self.radio_docs.isChecked()
|
||||||
|
endpoint = API_MESSAGE_DOCS_ENDPOINT if use_docs else API_MESSAGE_ENDPOINT
|
||||||
|
|
||||||
|
# Limpiar respuesta anterior
|
||||||
|
self.response_buffer = ""
|
||||||
|
self.response_text.clear()
|
||||||
|
|
||||||
|
# Deshabilitar botón de envío
|
||||||
|
self.send_btn.setEnabled(False)
|
||||||
|
self.send_btn.setText("Procesando...")
|
||||||
|
|
||||||
|
# Crear y ejecutar worker
|
||||||
|
self.worker = APIWorker(endpoint, message, use_streaming=True)
|
||||||
|
self.worker.response_received.connect(self.append_response)
|
||||||
|
self.worker.error_occurred.connect(self.handle_error)
|
||||||
|
self.worker.finished.connect(self.on_request_finished)
|
||||||
|
self.worker.start()
|
||||||
|
|
||||||
|
def append_response(self, chunk):
|
||||||
|
"""Acumula chunks de respuesta y los renderiza como markdown"""
|
||||||
|
self.response_buffer += chunk
|
||||||
|
# Renderizar el markdown con HTML
|
||||||
|
html = markdown_to_html(self.response_buffer)
|
||||||
|
self.response_text.setHtml(html)
|
||||||
|
# Auto-scroll al final
|
||||||
|
scrollbar = self.response_text.verticalScrollBar()
|
||||||
|
scrollbar.setValue(scrollbar.maximum())
|
||||||
|
|
||||||
|
def handle_error(self, error_message):
|
||||||
|
"""Maneja errores"""
|
||||||
|
error_md = f"**Error:** {error_message}"
|
||||||
|
html = markdown_to_html(error_md)
|
||||||
|
self.response_text.setHtml(html)
|
||||||
|
QMessageBox.critical(self, "Error", error_message)
|
||||||
|
|
||||||
|
def on_request_finished(self):
|
||||||
|
"""Se ejecuta cuando la request termina"""
|
||||||
|
self.send_btn.setEnabled(True)
|
||||||
|
self.send_btn.setText("Enviar")
|
||||||
|
self.check_api_status()
|
||||||
|
|
||||||
|
def clear_all(self):
|
||||||
|
"""Limpia el mensaje y la respuesta"""
|
||||||
|
self.input_text.clear()
|
||||||
|
self.response_buffer = ""
|
||||||
|
self.response_text.clear()
|
||||||
|
self.input_text.setFocus()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
app = QApplication(sys.argv)
|
||||||
|
window = MainWindow()
|
||||||
|
window.show()
|
||||||
|
sys.exit(app.exec())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
5
frontend/requirements.txt
Normal file
5
frontend/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
PyQt6==6.7.1
|
||||||
|
PyQt6-Qt6==6.7.1
|
||||||
|
PyQt6-sip==13.6.1
|
||||||
|
requests==2.32.3
|
||||||
|
markdown==3.5.2
|
||||||
423
html_client.html
Normal file
423
html_client.html
Normal file
@@ -0,0 +1,423 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Claude API Chat</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
background: white;
|
||||||
|
border-radius: 16px;
|
||||||
|
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 800px;
|
||||||
|
height: 90vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
padding: 20px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-selector {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
justify-content: center;
|
||||||
|
margin-top: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-btn {
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||||
|
color: white;
|
||||||
|
padding: 8px 20px;
|
||||||
|
border-radius: 20px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-btn:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-btn.active {
|
||||||
|
background: white;
|
||||||
|
color: #667eea;
|
||||||
|
border-color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.api-url-container {
|
||||||
|
padding: 15px 20px;
|
||||||
|
background: #f8f9fa;
|
||||||
|
border-bottom: 1px solid #e9ecef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.api-url-container label {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #6c757d;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.api-url-container input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #ced4da;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: #f8f9fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex;
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes slideIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(10px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
max-width: 70%;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: 18px;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user .message-content {
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content {
|
||||||
|
background: white;
|
||||||
|
color: #333;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.error .message-content {
|
||||||
|
background: #fee;
|
||||||
|
color: #c33;
|
||||||
|
border: 1px solid #fcc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-container {
|
||||||
|
padding: 20px;
|
||||||
|
background: white;
|
||||||
|
border-top: 1px solid #e9ecef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#messageInput {
|
||||||
|
flex: 1;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border: 2px solid #e9ecef;
|
||||||
|
border-radius: 24px;
|
||||||
|
font-size: 14px;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#messageInput:focus {
|
||||||
|
border-color: #667eea;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sendBtn {
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 12px 28px;
|
||||||
|
border-radius: 24px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: transform 0.2s, box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sendBtn:hover:not(:disabled) {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#sendBtn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator {
|
||||||
|
display: none;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: white;
|
||||||
|
border-radius: 18px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
width: fit-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span {
|
||||||
|
display: inline-block;
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #667eea;
|
||||||
|
margin: 0 2px;
|
||||||
|
animation: bounce 1.4s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span:nth-child(2) {
|
||||||
|
animation-delay: 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span:nth-child(3) {
|
||||||
|
animation-delay: 0.4s;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes bounce {
|
||||||
|
0%, 60%, 100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
30% {
|
||||||
|
transform: translateY(-10px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container::-webkit-scrollbar-track {
|
||||||
|
background: #f1f1f1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container::-webkit-scrollbar-thumb {
|
||||||
|
background: #888;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #555;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="header">
|
||||||
|
<h1>🤖 Claude API Chat</h1>
|
||||||
|
<p style="font-size: 14px; opacity: 0.9;">Interfaz de chat con tu API de FastAPI</p>
|
||||||
|
<div class="mode-selector">
|
||||||
|
<button class="mode-btn active" data-mode="normal">Chat Normal</button>
|
||||||
|
<button class="mode-btn" data-mode="docs">Con Documentos</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="api-url-container">
|
||||||
|
<label for="apiUrl">URL Base de la API:</label>
|
||||||
|
<input type="text" id="apiUrl" value="http://localhost:8000" placeholder="http://localhost:8000">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chat-container" id="chatContainer">
|
||||||
|
<div class="message assistant">
|
||||||
|
<div class="message-content">
|
||||||
|
¡Hola! 👋 Estoy listo para ayudarte. Puedes cambiar entre modo normal y modo con documentos usando los botones superiores.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="input-container">
|
||||||
|
<div class="typing-indicator" id="typingIndicator">
|
||||||
|
<span></span>
|
||||||
|
<span></span>
|
||||||
|
<span></span>
|
||||||
|
</div>
|
||||||
|
<div class="input-wrapper">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="messageInput"
|
||||||
|
placeholder="Escribe tu mensaje aquí..."
|
||||||
|
autocomplete="off"
|
||||||
|
>
|
||||||
|
<button id="sendBtn">Enviar</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Estado de la aplicación
|
||||||
|
let currentMode = 'normal';
|
||||||
|
const chatContainer = document.getElementById('chatContainer');
|
||||||
|
const messageInput = document.getElementById('messageInput');
|
||||||
|
const sendBtn = document.getElementById('sendBtn');
|
||||||
|
const apiUrlInput = document.getElementById('apiUrl');
|
||||||
|
const typingIndicator = document.getElementById('typingIndicator');
|
||||||
|
const modeBtns = document.querySelectorAll('.mode-btn');
|
||||||
|
|
||||||
|
// Cambiar modo
|
||||||
|
modeBtns.forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
modeBtns.forEach(b => b.classList.remove('active'));
|
||||||
|
btn.classList.add('active');
|
||||||
|
currentMode = btn.dataset.mode;
|
||||||
|
|
||||||
|
addMessage('assistant', `Modo cambiado a: ${currentMode === 'normal' ? 'Chat Normal' : 'Chat con Documentos'}`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Agregar mensaje al chat
|
||||||
|
function addMessage(type, content) {
|
||||||
|
const messageDiv = document.createElement('div');
|
||||||
|
messageDiv.className = `message ${type}`;
|
||||||
|
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
contentDiv.textContent = content;
|
||||||
|
|
||||||
|
messageDiv.appendChild(contentDiv);
|
||||||
|
chatContainer.appendChild(messageDiv);
|
||||||
|
|
||||||
|
// Scroll automático
|
||||||
|
chatContainer.scrollTop = chatContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enviar mensaje
|
||||||
|
async function sendMessage() {
|
||||||
|
const message = messageInput.value.trim();
|
||||||
|
if (!message) return;
|
||||||
|
|
||||||
|
const apiUrl = apiUrlInput.value.trim();
|
||||||
|
if (!apiUrl) {
|
||||||
|
addMessage('error', 'Por favor, ingresa la URL de la API');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agregar mensaje del usuario
|
||||||
|
addMessage('user', message);
|
||||||
|
messageInput.value = '';
|
||||||
|
|
||||||
|
// Deshabilitar input y mostrar indicador
|
||||||
|
sendBtn.disabled = true;
|
||||||
|
messageInput.disabled = true;
|
||||||
|
typingIndicator.classList.add('active');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Construir la URL del endpoint
|
||||||
|
const endpoint = currentMode === 'normal' ? '/ai/' : '/ai/using_docs';
|
||||||
|
const url = `${apiUrl}${endpoint}?message=${encodeURIComponent(message)}`;
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Accept': 'application/json',
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Error HTTP: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leer el stream de respuesta
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let fullResponse = '';
|
||||||
|
|
||||||
|
// Crear mensaje de respuesta
|
||||||
|
const messageDiv = document.createElement('div');
|
||||||
|
messageDiv.className = 'message assistant';
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
messageDiv.appendChild(contentDiv);
|
||||||
|
chatContainer.appendChild(messageDiv);
|
||||||
|
|
||||||
|
// Ocultar indicador de escritura
|
||||||
|
typingIndicator.classList.remove('active');
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value, { stream: true });
|
||||||
|
fullResponse += chunk;
|
||||||
|
contentDiv.textContent = fullResponse;
|
||||||
|
|
||||||
|
// Scroll automático
|
||||||
|
chatContainer.scrollTop = chatContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error);
|
||||||
|
typingIndicator.classList.remove('active');
|
||||||
|
addMessage('error', `Error al enviar mensaje: ${error.message}`);
|
||||||
|
} finally {
|
||||||
|
// Rehabilitar input
|
||||||
|
sendBtn.disabled = false;
|
||||||
|
messageInput.disabled = false;
|
||||||
|
messageInput.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event listeners
|
||||||
|
sendBtn.addEventListener('click', sendMessage);
|
||||||
|
|
||||||
|
messageInput.addEventListener('keypress', (e) => {
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
sendMessage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Focus inicial
|
||||||
|
messageInput.focus();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user