This document describes how to integrate the AstroBot frontend with the Flask backend that uses OpenRouter to access language models like GPT-3.5-turbo and identify any AI model available through OpenRouter.
Este documento describe cómo integrar el frontend de AstroBot con el backend Flask que utiliza OpenRouter para acceder a modelos de lenguaje como GPT-3.5-turbo e identificar cualquier modelo de IA disponible a través de OpenRouter.
The backend is built with Flask and has the following structure:
El backend está construido con Flask y tiene la siguiente estructura:
backend/
├── app/
│ ├── __init__.py # Flask application initialization | Inicialización de la aplicación Flask
│ ├── ai.py # Functions to interact with OpenRouter | Funciones para interactuar con OpenRouter
│ ├── config.py # Application configuration | Configuración de la aplicación
│ └── routes.py # Routes and endpoints definition | Definición de rutas y endpoints
├── .env # Environment variables (don't include in version control) | Variables de entorno (no incluir en control de versiones)
└── run.py # Script to run the application | Script para ejecutar la aplicación
To run the backend, you need:
Para ejecutar el backend, necesitas:
- Python 3.8 or higher | Python 3.8 o superior
- Dependencies listed in
requirements.txt| Las dependencias listadas enrequirements.txt:- Flask
- flask-cors
- openai==0.28.0
- python-dotenv
The backend requires the following environment variables:
El backend requiere las siguientes variables de entorno:
OPENROUTER_API_KEY=your_openrouter_api_key
OPENROUTER_API_BASE=https://openrouter.ai/api/v1These variables should be defined in a .env file in the root of the backend project.
Estas variables deben definirse en un archivo .env en la raíz del proyecto backend.
To allow mobile devices to connect to the backend, it's necessary to configure Flask to listen on all network interfaces:
Para permitir que dispositivos móviles se conecten al backend, es necesario configurar Flask para que escuche en todas las interfaces de red:
-
Modify the
run.pyfile to contain:Modifica el archivo
run.pypara que contenga:
# run.py
from app import create_app
from dotenv import load_dotenv
# Load environment variables defined in the .env file
# Carga las variables de entorno definidas en el archivo .env
load_dotenv()
app = create_app()
if __name__ == '__main__':
# Setting host='0.0.0.0' allows the server to be accessible
# from any device on the network, not just from localhost
# Configurar host='0.0.0.0' permite que el servidor sea accesible
# desde cualquier dispositivo en la red, no solo desde localhost
app.run(host='0.0.0.0', port=5000, debug=True)-
In the frontend, update the backend URL to use your computer's IP address on the local network:
En el frontend, actualiza la URL del backend para usar la dirección IP de tu computadora en la red local:
// In AstroBotService.js | En AstroBotService.js
const API_BASE_URL = 'http://192.168.100.129:5000'; // Replace with your local IP | Reemplaza con tu IP localYou can find your local IP address with the ipconfig command on Windows or ifconfig on Mac/Linux.
Puedes encontrar tu dirección IP local con el comando ipconfig en Windows o ifconfig en Mac/Linux.
-
Clone the backend repository from GitHub:
Clonar el repositorio del backend desde GitHub:
git clone https://github.com/user/astrobot-backend.git
cd astrobot-backend-
Install dependencies:
Instalar las dependencias:
pip install -r requirements.txtThis endpoint processes messages sent by the user and returns responses generated by the AI model. It also identifies which OpenRouter AI model was used for the response.
Este endpoint procesa los mensajes enviados por el usuario y devuelve respuestas generadas por el modelo de IA. También identifica qué modelo de IA de OpenRouter se utilizó para la respuesta.
Request | Solicitud:
{
"message": "What is molar mass? | ¿Qué es la masa molar?"
}Response | Respuesta:
{
"response": "Molar mass is the mass of one mole of a substance, expressed in grams/mol. To calculate the molar mass of a compound, add up the atomic masses of all atoms in the molecular formula. | La masa molar es la masa de un mol de una sustancia, expresada en gramos/mol. Para calcular la masa molar de un compuesto, suma las masas atómicas de todos los átomos en la fórmula molecular.",
"model": "gpt-3.5-turbo-0125"
}In the AstroBotService.js file, make sure the base URL points to your Flask server:
En el archivo AstroBotService.js, asegúrate de que la URL base apunte a tu servidor Flask:
const API_BASE_URL = 'http://127.0.0.1:5000'; // Change this to your server URL in production | Cambia esto a la URL de tu servidor en producción-
Connection Verification | Verificación de Conexión:
-
The frontend verifies the connection with the backend by sending a "ping" message to the
/chatendpoint. -
If the connection is successful, the full chat functionality is enabled.
-
If the connection fails, simulation mode is activated.
-
El frontend verifica la conexión con el backend enviando un mensaje "ping" al endpoint
/chat. -
Si la conexión es exitosa, se habilita la funcionalidad completa del chat.
-
Si la conexión falla, se activa el modo de simulación.
-
-
Sending Messages | Envío de Mensajes:
-
The user writes a message in the chat interface.
-
The frontend sends the message to the backend through the
/chatendpoint. -
The backend processes the message using OpenRouter and returns the response with model identification.
-
The frontend displays the response in the chat interface.
-
El usuario escribe un mensaje en la interfaz de chat.
-
El frontend envía el mensaje al backend a través del endpoint
/chat. -
El backend procesa el mensaje utilizando OpenRouter y devuelve la respuesta con identificación del modelo.
-
El frontend muestra la respuesta en la interfaz de chat.
-
-
Error Handling | Manejo de Errores:
-
If the backend does not respond within the time limit, an error message is displayed.
-
If the backend returns an error, an appropriate message is displayed.
-
In both cases, simulation mode is activated to allow a continuous user experience.
-
Si el backend no responde dentro del tiempo límite, se muestra un mensaje de error.
-
Si el backend devuelve un error, se muestra un mensaje apropiado.
-
En ambos casos, se activa el modo de simulación para permitir una experiencia de usuario continua.
-
When the backend is not available, the frontend automatically activates a simulation mode that:
Cuando el backend no está disponible, el frontend activa automáticamente un modo de simulación que:
- Generates predefined responses based on simple patterns | Genera respuestas predefinidas basadas en patrones simples
- Displays a clear indicator that simulation mode is active | Muestra un indicador claro de que se está en modo simulación
- Allows the user to continue interacting with the interface | Permite al usuario seguir interactuando con la interfaz
To test the connection with the backend, run:
Para probar la conexión con el backend, ejecuta:
node test_backend.jsThis script verifies: Este script verifica:
- The connection with the backend | La conexión con el backend
- Sending and receiving messages | El envío y recepción de mensajes
- AI model identification | La identificación del modelo de IA
To run the backend in development:
Para ejecutar el backend en desarrollo:
python run.pyFor production, consider using Gunicorn or uWSGI with a web server like Nginx.
Para producción, considera usar Gunicorn o uWSGI con un servidor web como Nginx.
The frontend integrates with the rest of the AstroLab Calculator application. Make sure to update the backend URL in production.
El frontend se integra con el resto de la aplicación AstroLab Calculator. Asegúrate de actualizar la URL del backend en producción.
-
"Network request failed" Error | Error "Network request failed"
- Verify that the Flask server is running | Verifica que el servidor Flask esté en ejecución
- Check that the URL and port are correct | Comprueba que la URL y el puerto sean correctos
- Make sure CORS is enabled in the backend | Asegúrate de que CORS esté habilitado en el backend
-
"Request timed out" Error | Error "La solicitud excedió el tiempo de espera"
- May indicate that the server is overloaded | Puede indicar que el servidor está sobrecargado
- Check internet connection | Verifica la conexión a internet
- Increase timeout in
fetchWithTimeout| Aumenta el tiempo de espera enfetchWithTimeout
-
Empty or incorrect responses | Respuestas vacías o incorrectas
- Verify OpenRouter API keys | Verifica las claves API de OpenRouter
- Check request and response formats | Comprueba el formato de las solicitudes y respuestas
- Review Flask server logs for specific errors | Revisa los logs del servidor Flask para errores específicos
AstroBot can now identify which AI model from OpenRouter is being used to generate responses. The backend has been enhanced to include this information in each response:
AstroBot ahora puede identificar qué modelo de IA de OpenRouter se está utilizando para generar respuestas. El backend ha sido mejorado para incluir esta información en cada respuesta:
# In ai.py | En ai.py
def get_ai_response(message):
try:
response = openai.ChatCompletion.create(
model="openai/gpt-3.5-turbo", # Can be changed to any model | Puede cambiarse a cualquier modelo
api_base=os.environ.get("OPENROUTER_API_BASE"),
api_key=os.environ.get("OPENROUTER_API_KEY"),
messages=[{"role": "user", "content": message}]
)
return {
"response": response.choices[0].message.content,
"model": response.model # Include model identification | Incluir identificación del modelo
}
except Exception as e:
print(f"Error getting AI response: {e}")
return {"error": str(e)}The frontend can display this information to the user:
El frontend puede mostrar esta información al usuario:
// In chat component | En el componente de chat
function displayResponse(data) {
const chatBox = document.getElementById('chat-box');
const responseDiv = document.createElement('div');
responseDiv.className = 'response';
responseDiv.innerHTML = `
<p>${data.response}</p>
<small class="model-info">Generated by: ${data.model || 'Unknown model'}</small>
`;
chatBox.appendChild(responseDiv);
}