Skip to content

Commit f25de67

Browse files
committed
Merge remote-tracking branch 'origin/main'
2 parents dc45be8 + d813d66 commit f25de67

File tree

15 files changed

+305
-190
lines changed

15 files changed

+305
-190
lines changed

examples/.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ PASSWORD = "123456"
55
DATABASE = "inpos_ayudakarla2"
66
APIKEYGEMINI =
77
HOST_QDRANT =
8-
APIKEY_QDRANT =
8+
APIKEY_QDRANT =

examples/api/app.py

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
2-
import ssl
3-
from fastapi import FastAPI
2+
# import ssl
3+
from fastapi import FastAPI, Body
44
from pydantic import BaseModel
55
from vertexai.generative_models import GenerativeModel, SafetySetting, Part
66
from pydantic import BaseModel, Field
@@ -13,7 +13,7 @@
1313
import yipao as yp
1414
from yipao.databases import MySql
1515
from yipao.vectorstores import QdrantDB
16-
from yipao.LLM import VertexAiLLM
16+
from yipao.LLM import GoogleGenAi
1717

1818
KEY_PATH='./credentials/gen-lang-client-0867205962-4a2d259770b4.json'
1919
PROJECT_ID = "gen-lang-client-0867205962"
@@ -47,10 +47,18 @@
4747
app = FastAPI(
4848
title="Simple Inference API",
4949
version="1.0.0",
50-
description="This is the OpenAPI specification of a service to query a sql database using natural language. Its purpose is to illustrate how to declare your REST API as an OpenAPI tool."
51-
)
50+
description="Esta es una demo en swagger ui de una api para realizar consultas sql a una base de datos por medio de lenguaje natural")
5251
app.openapi_version = "3.0.0"
5352

53+
app.add_middleware(
54+
CORSMiddleware,
55+
allow_origins=origins,
56+
allow_credentials=True,
57+
allow_methods=["*"],
58+
allow_headers=["*"],
59+
)
60+
61+
5462
#----------------
5563
# SSL
5664
#----------------
@@ -62,17 +70,27 @@
6270
# APP
6371
# --------------
6472

65-
@app.get("/ping")
73+
@app.get("/ping", summary="Ping de validacion")
6674
def root():
6775
return {"Hello": "World"}
6876

6977

7078
class QueryModel(BaseModel):
71-
Item: str = Field(..., description="Name Item")
72-
q: str
79+
Item: str = Field(..., examples=["root:123456@127.0.0.1:3306/messagehistoryrag"], description="Url database")
80+
q: str = Field(..., description='Pregunta del usuario')
7381

7482
class InitializeModel(BaseModel):
75-
Item: str = Field(..., description="Name Item")
83+
Item: str = Field(
84+
...,
85+
examples=["root:123456@127.0.0.1:3306/messagehistoryrag"],
86+
description="Url database")
87+
88+
class Config:
89+
schema_extra = {
90+
"example": {
91+
"Item": "root:123456@127.0.0.1:3306/messagehistoryrag"
92+
}
93+
}
7694

7795

7896
def connect_sql():
@@ -85,7 +103,7 @@ def connect_sql():
85103
}
86104

87105
try:
88-
mysql = MySql(**connection)
106+
mysql = MySql(**db)
89107
except Exception as e:
90108
raise HTTPException(status_code=500, detail=f"Failed to connect to MySQL: {str(e)}")
91109

@@ -142,10 +160,12 @@ def initialize_qdrant():
142160
qdrant.add_ddls(formatted_output, connection["database"])
143161
added_excel = True
144162

145-
return {"message": "Qdrant initialized", "payload": data.Item}
146-
163+
return {"message": "Qdrant initialized", "payload": connection["database"]}
164+
except Exception as e:
165+
print('error',e)
166+
raise HTTPException(status_code=401, detail="No fue posible conectar a la db")
147167

148-
@app.post("/inference", summary="Executes a natural language query. Needs Item and 'q' is the query to be performed.")
168+
@app.post("/inference", summary="Ejecuta una consulta en lenguaje natural, devuelve el resultado de la consulta junto con la consulta creada")
149169
def query_inference(data: QueryModel):
150170

151171
connection = parse_sql_url(data.Item)
@@ -159,7 +179,15 @@ def query_inference(data: QueryModel):
159179

160180
try:
161181
res, _, _, sql_query = agent.invoke(data.q, debug=True, iterations=6)
182+
183+
try:
184+
res = res.to_dict(orient="records")
185+
except Exception as e:
186+
print(f"Error converting result to dict: {e}")
187+
res = str(res)
188+
189+
return {"q": data.q, "res": res, "sql_query_generated": sql_query}
162190
except Exception as e:
163-
raise HTTPException(status_code=500, detail=f"Query execution failed: {str(e)}")
191+
print('Error en el query',e)
192+
raise HTTPException(status_code=401, detail=f"Query execution failed")
164193

165-
return {"q": data.q, "res": res, "sql_query_generated": sql_query}

examples/api/cert.der

-1.47 KB
Binary file not shown.

examples/api/cert.pem

Lines changed: 0 additions & 34 deletions
This file was deleted.

examples/api/key.pem

Lines changed: 0 additions & 52 deletions
This file was deleted.

examples/api/server.crt

Lines changed: 0 additions & 18 deletions
This file was deleted.

examples/api/server.csr

Lines changed: 0 additions & 15 deletions
This file was deleted.

examples/api/server.der

-758 Bytes
Binary file not shown.

examples/api/server.key

Lines changed: 0 additions & 28 deletions
This file was deleted.

examples/frontend/chat.js

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// Selecciona los elementos del DOM
2+
const messagesDiv = document.getElementById('messages');
3+
const messageInput = document.getElementById('message-input');
4+
const sendButton = document.getElementById('send-button');
5+
const usernameDialog = document.getElementById('db-dialog');
6+
const usernameInput = document.getElementById('db-input');
7+
const confirmUsernameButton = document.getElementById('db-username');
8+
const chatContainer = document.getElementById('chat-container');
9+
10+
let username = '';
11+
12+
// Función para agregar mensajes al chat
13+
function addMessageToChat(message, className) {
14+
const p = document.createElement('p');
15+
p.className = className;
16+
p.textContent = message;
17+
messagesDiv.appendChild(p);
18+
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll al final del chat
19+
}
20+
21+
// Función para mostrar el cuadro de diálogo del nombre de usuario
22+
function showUsernameDialog() {
23+
usernameDialog.style.display = 'flex';
24+
}
25+
26+
// Función para ocultar el cuadro de diálogo y mostrar el chat
27+
function hideUsernameDialog() {
28+
usernameDialog.style.display = 'none';
29+
chatContainer.style.display = 'block';
30+
}
31+
32+
// Evento de clic en el botón "Confirmar" para el nombre de usuario
33+
confirmUsernameButton.addEventListener('click', () => {
34+
const enteredUsername = usernameInput.value.trim();
35+
36+
if (enteredUsername) {
37+
const initdb = enteredUsername; // Guardamos el nombre de usuario
38+
const requestBody = {
39+
Item: initdb
40+
}
41+
fetch('http://127.0.0.1:8080/init_item', {
42+
method: 'POST',
43+
headers: {
44+
'Content-Type': 'application/json'
45+
},
46+
body: JSON.stringify(requestBody)
47+
}).then((response) => {
48+
if (!response.ok) { // Verifica si la respuesta no fue exitosa (status >= 400)
49+
return response.json().then(err => {
50+
throw new Error(`Error ${response.status}: ${err.detail || 'Error desconocido'}`);
51+
});
52+
}
53+
return response.json();
54+
}) // convertir a json
55+
.then((json) => {
56+
hideUsernameDialog()
57+
localStorage.setItem('db', initdb)
58+
addMessageToChat(`Conexion establesida a la base de datos: ${json.payload}`, 'api-response');
59+
}) //imprimir los datos en la consola
60+
.catch((err) => {
61+
console.log('Solicitud fallida', err)
62+
alert('Error en la conexios revisa que el url este bien')
63+
}); // Capturar errores
64+
65+
}
66+
});
67+
68+
// Evento de clic en el botón "Enviar"
69+
sendButton.addEventListener('click', async () => {
70+
const message = messageInput.value;
71+
72+
if (message.trim() === '') {
73+
return; // Si el mensaje está vacío, no hacemos nada
74+
}
75+
76+
// Agregar el mensaje del usuario al chat
77+
addMessageToChat(`${username}: ${message}`, 'user-message');
78+
79+
// Limpiar el input después de enviar el mensaje
80+
messageInput.value = '';
81+
82+
// Crear el cuerpo de la solicitud
83+
const requestBody = {
84+
Item: localStorage.getItem('db'),
85+
q: message
86+
};
87+
88+
try {
89+
// Enviar el mensaje al endpoint '/inference' usando fetch
90+
const response = await fetch('http://127.0.0.1:8080/inference', {
91+
method: 'POST',
92+
headers: {
93+
'Content-Type': 'application/json'
94+
},
95+
body: JSON.stringify(requestBody)
96+
});
97+
98+
// Verificar si la respuesta es exitosa
99+
if (response.ok) {
100+
const jsonResponse = await response.json();
101+
const apiResponse = jsonResponse.res; // Suponiendo que el backend devuelve una respuesta en el campo "response"
102+
const sql_query_generated = jsonResponse.sql_query_generated
103+
// Agregar la respuesta de la API al chat
104+
addMessageToChat(`Respuesta: ${JSON.stringify(apiResponse)}`, 'api-response');
105+
addMessageToChat(`Consulta SQL generada: ${sql_query_generated}`, 'api-response');
106+
107+
} else {
108+
addMessageToChat('Error al conectarse con la API', 'api-response');
109+
}
110+
} catch (error) {
111+
console.error('Error:', error);
112+
addMessageToChat('Error al enviar el mensaje', 'api-response');
113+
}
114+
});
115+
116+
// Mostrar el cuadro de diálogo del nombre de usuario al cargar la página
117+
showUsernameDialog();

0 commit comments

Comments
 (0)