11import os
22# import ssl
3- from fastapi import FastAPI , Body
3+ from fastapi import FastAPI
4+ from fastapi .middleware .cors import CORSMiddleware
45from pydantic import BaseModel
5- from vertexai .generative_models import GenerativeModel , SafetySetting , Part
6+ from vertexai .generative_models import SafetySetting
67from pydantic import BaseModel , Field
78from fastapi import HTTPException
89import re
1516from yipao .vectorstores import QdrantDB
1617from yipao .LLM import GoogleGenAi
1718
18- KEY_PATH = './credentials/gen-lang-client-0867205962-4a2d259770b4.json'
19- PROJECT_ID = "gen-lang-client-0867205962"
20- REGION = "us-central1"
21- MODEL = "gemini-1.5-flash-002"
22- CONFIG = {
23- "max_output_tokens" : 8192 ,
24- "temperature" : 1 ,
25- "top_p" : 0.95 ,
26- }
27- SAFETY_SETTINGS = [
28- SafetySetting (
29- category = SafetySetting .HarmCategory .HARM_CATEGORY_HATE_SPEECH ,
30- threshold = SafetySetting .HarmBlockThreshold .OFF
31- ),
32- SafetySetting (
33- category = SafetySetting .HarmCategory .HARM_CATEGORY_DANGEROUS_CONTENT ,
34- threshold = SafetySetting .HarmBlockThreshold .OFF
35- ),
36- SafetySetting (
37- category = SafetySetting .HarmCategory .HARM_CATEGORY_SEXUALLY_EXPLICIT ,
38- threshold = SafetySetting .HarmBlockThreshold .OFF
39- ),
40- SafetySetting (
41- category = SafetySetting .HarmCategory .HARM_CATEGORY_HARASSMENT ,
42- threshold = SafetySetting .HarmBlockThreshold .OFF
43- ),
44- ]
45- added_excel = True
46-
4719app = FastAPI (
4820 title = "Simple Inference API" ,
4921 version = "1.0.0" ,
5224
5325app .add_middleware (
5426 CORSMiddleware ,
55- allow_origins = origins ,
27+ allow_origins = [ "*" ] ,
5628 allow_credentials = True ,
5729 allow_methods = ["*" ],
5830 allow_headers = ["*" ],
7042# APP
7143# --------------
7244
73- @app .get ("/ping" , summary = "Ping de validacion" )
74- def root ():
75- return {"Hello" : "World" }
76-
77-
7845class QueryModel (BaseModel ):
79- Item : str = Field (..., examples = ["root:123456@127.0.0.1:3306/messagehistoryrag" ], description = "Url database" )
80- q : str = Field (..., description = 'Pregunta del usuario' )
81-
82- class InitializeModel (BaseModel ):
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- }
94-
46+ query : str = Field (..., description = 'Pregunta del usuario' )
9547
9648def connect_sql ():
9749 connection = {
@@ -103,90 +55,40 @@ def connect_sql():
10355 }
10456
10557 try :
106- mysql = MySql (** db )
58+ mysql = MySql (** connection )
10759 except Exception as e :
10860 raise HTTPException (status_code = 500 , detail = f"Failed to connect to MySQL: { str (e )} " )
10961
11062 return mysql
11163
64+ qdrant = QdrantDB ('http://localhost:6333' , os .getenv ('QDRANT_API_KEY' ), collection_name = os .getenv ('DATABASE' ))
65+ chat = GoogleGenAi (model = "gemini-1.5-pro" , api_key = os .getenv ('APIKEYGEMINI' ))
11266
113- def parse_sql_url (url ):
114- pattern = re .compile (r'(?P<user>.*?):(?P<password>.*?)(?=@)@(?P<host>.*?):(?P<port>\d+?)/(?P<database>.*)' )
115- match = pattern .match (url )
116- if match :
117- connection = match .groupdict ()
118- connection ['port' ] = int (connection ['port' ])
119- else :
120- print ("URL format is incorrect" )
121- return connection
122-
123-
124- qdrant = QdrantDB (':memory:' )
125- chat = VertexAiLLM (MODEL , KEY_PATH , PROJECT_ID , CONFIG , SAFETY_SETTINGS )
67+ qdrant .initialize_collection ()
68+ mysql = connect_sql ()
69+ agent = yp .Agent (llm = chat , database = mysql , vectorstore = qdrant , name_collection = os .getenv ('DATABASE' ))
12670
12771#--------------
12872# ROUTES
12973#--------------
13074
13175
132- @app .get ("/init_item" , summary = "Initializes by the item" )
133- def initialize_qdrant ():
134- global added_excel
135-
136-
137- qdrant .initialize (os .getenv ('DATABASE' ))
138-
139- mysql = connect_sql ()
140-
141- agent = yp .Agent (llm = chat ,
142- database = mysql ,
143- vectorstore = qdrant ,
144- name_collection = os .getenv ('DATABASE' ))
145- agent .document_database ()
146-
147- if not added_excel :
148-
149- file_path = './static/Question, intention and response.xlsx'
150-
151- df = pd .read_excel (file_path )
152-
153- selected_columns = df [['question (english)' , 'intent (english)' , 'intermediate response (SQL QUERY)' ]]
154-
155- formatted_output = [
156- f"\n pregunta: { row ['question (english)' ]} \n intencion: { row ['intent (english)' ]} \n ejemplo de query: { row ['intermediate response (SQL QUERY)' ]} \n "
157- for _ , row in selected_columns .iterrows ()
158- ]
159-
160- qdrant .add_ddls (formatted_output , connection ["database" ])
161- added_excel = True
162-
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" )
76+ @app .get ("/health" , summary = "Healthcheck" )
77+ def health ():
78+ return {"message" : "Healthy" }
16779
16880@app .post ("/inference" , summary = "Ejecuta una consulta en lenguaje natural, devuelve el resultado de la consulta junto con la consulta creada" )
16981def query_inference (data : QueryModel ):
17082
171- connection = parse_sql_url (data .Item )
172-
173- mysql = connect_sql (connection )
174-
175- agent = yp .Agent (llm = chat ,
176- database = mysql ,
177- vectorstore = qdrant ,
178- name_collection = connection ["database" ])
179-
18083 try :
181- res , _ , _ , sql_query = agent .invoke (data .q , debug = True , iterations = 6 )
84+ res , sql_query = agent .invoke (data .query , debug = True , iterations = 6 )
18285
18386 try :
18487 res = res .to_dict (orient = "records" )
18588 except Exception as e :
18689 print (f"Error converting result to dict: { e } " )
18790 res = str (res )
188-
189- return {"q" : data .q , "res" : res , "sql_query_generated" : sql_query }
91+ return {"q" : data .query , "res" : res , "sql_query_generated" : sql_query }
19092 except Exception as e :
19193 print ('Error en el query' ,e )
19294 raise HTTPException (status_code = 401 , detail = f"Query execution failed" )
0 commit comments