import os import uvicorn import requests import json import time from fastapi import FastAPI, File, HTTPException, Depends, Body, UploadFile from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.staticfiles import StaticFiles from models.api import ( DeleteRequest, DeleteResponse, QueryRequest, QueryResponse, UpsertRequest, UpsertResponse, AskdataRequest, AskdataResponse, ) from datastore.factory import get_datastore from services.file import get_document_from_file from services.extract_metadata import extract_table_name app = FastAPI() app.mount("/.well-known", StaticFiles(directory=".well-known"), name="static") # Create a sub-application, in order to access just the query endpoint in an OpenAPI schema, found at http://0.0.0.0:8000/sub/openapi.json when the app is running locally sub_app = FastAPI( title="Schema Retrieval Plugin API", description="A retrieval API for querying and filtering documents based on natural language queries and metadata", version="1.0.0", servers=[{"url": "https://moss.pingcap.net"}], ) app.mount("/sub", sub_app) bearer_scheme = HTTPBearer() BEARER_TOKEN = os.environ.get("BEARER_TOKEN") assert BEARER_TOKEN is not None # data serving configuration on TiDB Cloud TiDB_CLOUD_CLUSTER_ID = os.environ.get("TiDB_CLOUD_CLUSTER_ID", "1379661944641094067") TiDB_CLOUD_API_HOST = os.environ.get("TiDB_CLOUD_API_HOST", "https://data.tidbcloud.com/api/v1beta/app/chat2query-AGkqgpuU/endpoint/chat2data") TiDB_CLOUD_PUBLIC_KEY = os.environ.get("TiDB_CLOUD_PUBLIC_KEY", "") TiDB_CLOUD_PRIVATE_KEY = os.environ.get("TiDB_CLOUD_PRIVATE_KEY", "") def validate_token(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)): if credentials.scheme != "Bearer" or credentials.credentials != BEARER_TOKEN: raise HTTPException(status_code=401, detail="Invalid or missing token") return credentials @app.post( "/upsert-file", response_model=UpsertResponse, ) async def upsert_file( file: UploadFile = File(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): document = await get_document_from_file(file) try: ids = await datastore.upsert([document]) return UpsertResponse(ids=ids) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail=f"str({e})") @app.post( "/upsert", response_model=UpsertResponse, ) async def upsert( request: UpsertRequest = Body(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): try: ids = await datastore.upsert(request.documents) return UpsertResponse(ids=ids) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") @app.post( "/query", response_model=QueryResponse, ) async def query_main( request: QueryRequest = Body(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): try: results = await datastore.query( request.queries, ) return QueryResponse(results=results) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") @sub_app.post( "/query", response_model=QueryResponse, # NOTE: We are describing the shape of the API endpoint input due to a current limitation in parsing arrays of objects from OpenAPI schemas. This will not be necessary in the future. description="Accepts search query objects array each with query and optional filter. Break down complex questions into sub-questions. Refine results by criteria, e.g. time / source, don't do this often. Split queries if ResponseTooLargeError occurs.", ) async def query( request: QueryRequest = Body(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): try: results = await datastore.query( request.queries, ) return QueryResponse(results=results) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") @app.post( "/ask", response_model=AskdataResponse, ) async def ask_main( request: AskdataRequest = Body(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): if len(TiDB_CLOUD_PUBLIC_KEY) == 0 or len(TiDB_CLOUD_PRIVATE_KEY) == 0: print("TiDB_CLOUD_PUBLIC_KEY or TiDB_CLOUD_PRIVATE_KEY is not set") raise HTTPException(status_code=500, detail="Internal Service Error") print(f"ask: {request}") start_time = time.time() # firstly, search from vector store try: results = await datastore.query( [request], ) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") vector_search_time = time.time() print(f"ask: {request.query} - vector search cost time {vector_search_time-start_time} seconds") # find matched schema and table which has the highest score in tidb cloud macthedSchema = "" machedTables = [] for queryResult in results: for doc in queryResult.results: if doc.metadata.source_id is None: continue tableName = extract_table_name(doc.metadata.source_id) if tableName is None: print(f"table {doc.metadata.source_id} is not supported") continue if tableName["project"] == "tidbcloud" and doc.score >= 0.70: if macthedSchema == "": macthedSchema = tableName["db"] if macthedSchema == tableName["db"]: machedTables.append(tableName["table"]) print(f"ask: {request.query} - macthedSchema: {macthedSchema}, machedTables: {machedTables}") # if no matched schema and table in tidb cloud, proxy to tidb cloud directlly if macthedSchema == "": macthedSchema = "data_lens" try: data = { "cluster_id": TiDB_CLOUD_CLUSTER_ID, "database": macthedSchema, "tables": machedTables, "instruction": request.query } headers = { 'content-type': 'application/json' } auth = requests.auth.HTTPDigestAuth(TiDB_CLOUD_PUBLIC_KEY, TiDB_CLOUD_PRIVATE_KEY) response = requests.post(TiDB_CLOUD_API_HOST, headers=headers, data=json.dumps(data), auth=auth) end_time = time.time() print(f"ask: {request.query} - chat2query time: {end_time - vector_search_time} , ask cost time: {end_time-start_time}") return AskdataResponse(result=json.loads(response.text)) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") @app.delete( "/delete", response_model=DeleteResponse, ) async def delete( request: DeleteRequest = Body(...), token: HTTPAuthorizationCredentials = Depends(validate_token), ): if not (request.ids or request.filter or request.delete_all): raise HTTPException( status_code=400, detail="One of ids, filter, or delete_all is required", ) try: success = await datastore.delete( ids=request.ids, filter=request.filter, delete_all=request.delete_all, ) return DeleteResponse(success=success) except Exception as e: print("Error:", e) raise HTTPException(status_code=500, detail="Internal Service Error") @app.on_event("startup") async def startup(): global datastore datastore = await get_datastore() def start(): uvicorn.run("server.main:app", host="0.0.0.0", port=8000, reload=True)