2020-04-15 14:04:30 +02:00
|
|
|
import logging
|
2020-07-07 12:28:41 +02:00
|
|
|
import time
|
2021-12-06 18:55:39 +01:00
|
|
|
import json
|
2021-10-04 21:18:23 +02:00
|
|
|
from pathlib import Path
|
2022-01-26 18:20:44 +01:00
|
|
|
from numpy import ndarray
|
2020-04-15 14:04:30 +02:00
|
|
|
|
|
|
|
from fastapi import APIRouter
|
2020-10-15 18:41:36 +02:00
|
|
|
|
2021-11-19 11:34:32 +01:00
|
|
|
import haystack
|
2021-10-25 15:50:23 +02:00
|
|
|
from haystack.pipelines.base import Pipeline
|
2021-10-04 21:18:23 +02:00
|
|
|
from rest_api.config import PIPELINE_YAML_PATH, QUERY_PIPELINE_NAME
|
2021-10-04 11:21:00 +02:00
|
|
|
from rest_api.config import LOG_LEVEL, CONCURRENT_REQUEST_PER_WORKER
|
|
|
|
from rest_api.schema import QueryRequest, QueryResponse
|
2020-06-22 12:07:12 +02:00
|
|
|
from rest_api.controller.utils import RequestLimiter
|
2020-04-15 14:04:30 +02:00
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
|
2021-04-07 17:53:32 +02:00
|
|
|
logging.getLogger("haystack").setLevel(LOG_LEVEL)
|
|
|
|
logger = logging.getLogger("haystack")
|
2020-11-04 09:54:02 +01:00
|
|
|
|
2021-10-13 14:23:23 +02:00
|
|
|
from pydantic import BaseConfig
|
|
|
|
|
|
|
|
BaseConfig.arbitrary_types_allowed = True
|
2021-04-07 17:53:32 +02:00
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
router = APIRouter()
|
2021-10-04 21:18:23 +02:00
|
|
|
|
|
|
|
|
|
|
|
PIPELINE = Pipeline.load_from_yaml(Path(PIPELINE_YAML_PATH), pipeline_name=QUERY_PIPELINE_NAME)
|
|
|
|
# TODO make this generic for other pipelines with different naming
|
|
|
|
RETRIEVER = PIPELINE.get_node(name="Retriever")
|
|
|
|
DOCUMENT_STORE = RETRIEVER.document_store if RETRIEVER else None
|
|
|
|
logging.info(f"Loaded pipeline nodes: {PIPELINE.graph.nodes.keys()}")
|
|
|
|
|
2021-06-29 07:44:25 +02:00
|
|
|
concurrency_limiter = RequestLimiter(CONCURRENT_REQUEST_PER_WORKER)
|
2021-11-30 18:11:54 +01:00
|
|
|
logging.info("Concurrent requests per worker: {CONCURRENT_REQUEST_PER_WORKER}")
|
2021-04-07 17:53:32 +02:00
|
|
|
|
|
|
|
|
2021-09-27 16:40:25 +02:00
|
|
|
@router.get("/initialized")
|
2021-11-11 09:40:58 +01:00
|
|
|
def check_status():
|
2021-09-27 16:40:25 +02:00
|
|
|
"""
|
|
|
|
This endpoint can be used during startup to understand if the
|
|
|
|
server is ready to take any requests, or is still loading.
|
|
|
|
|
|
|
|
The recommended approach is to call this endpoint with a short timeout,
|
|
|
|
like 500ms, and in case of no reply, consider the server busy.
|
|
|
|
"""
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2021-11-19 11:34:32 +01:00
|
|
|
@router.get("/hs_version")
|
|
|
|
def haystack_version():
|
|
|
|
return {"hs_version": haystack.__version__}
|
|
|
|
|
|
|
|
|
2021-11-11 09:40:58 +01:00
|
|
|
@router.post("/query", response_model=QueryResponse, response_model_exclude_none=True)
|
2021-10-04 11:21:00 +02:00
|
|
|
def query(request: QueryRequest):
|
2021-04-07 17:53:32 +02:00
|
|
|
with concurrency_limiter.run():
|
|
|
|
result = _process_request(PIPELINE, request)
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
def _process_request(pipeline, request) -> QueryResponse:
|
2021-04-07 17:53:32 +02:00
|
|
|
start_time = time.time()
|
2021-10-19 15:22:44 +02:00
|
|
|
|
2021-09-10 11:41:16 +02:00
|
|
|
params = request.params or {}
|
2021-11-18 18:13:03 +01:00
|
|
|
|
|
|
|
# format global, top-level filters (e.g. "params": {"filters": {"name": ["some"]}})
|
|
|
|
if "filters" in params.keys():
|
|
|
|
params["filters"] = _format_filters(params["filters"])
|
|
|
|
|
|
|
|
# format targeted node filters (e.g. "params": {"Retriever": {"filters": {"value"}}})
|
|
|
|
for key, value in params.items():
|
|
|
|
if "filters" in params[key].keys():
|
|
|
|
params[key]["filters"] = _format_filters(params[key]["filters"])
|
|
|
|
|
|
|
|
result = pipeline.run(query=request.query, params=params,debug=request.debug)
|
2022-01-26 18:20:44 +01:00
|
|
|
|
|
|
|
# if any of the documents contains an embedding as an ndarray the latter needs to be converted to list of float
|
|
|
|
for document in result['documents'] or []:
|
|
|
|
if isinstance(document.embedding, ndarray):
|
|
|
|
document.embedding = document.embedding.tolist()
|
|
|
|
|
2020-10-16 13:25:31 +02:00
|
|
|
end_time = time.time()
|
2021-12-06 18:55:39 +01:00
|
|
|
logger.info(json.dumps({"request": request, "response": result, "time": f"{(end_time - start_time):.2f}"}, default=str))
|
2021-04-07 17:53:32 +02:00
|
|
|
|
|
|
|
return result
|
2021-11-18 18:13:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
def _format_filters(filters):
|
|
|
|
"""
|
|
|
|
Adjust filters to compliant format:
|
|
|
|
Put filter values into a list and remove filters with null value.
|
|
|
|
"""
|
|
|
|
new_filters = {}
|
2021-11-22 09:36:14 +01:00
|
|
|
if filters is None:
|
|
|
|
logger.warning(f"Request with deprecated filter format ('\"filters\": null'). "
|
|
|
|
f"Remove empty filters from params to be compliant with future versions")
|
|
|
|
else:
|
|
|
|
for key, values in filters.items():
|
|
|
|
if values is None:
|
|
|
|
logger.warning(f"Request with deprecated filter format ('{key}: null'). "
|
|
|
|
f"Remove null values from filters to be compliant with future versions")
|
|
|
|
continue
|
|
|
|
elif not isinstance(values, list):
|
|
|
|
logger.warning(f"Request with deprecated filter format ('{key}': {values}). "
|
|
|
|
f"Change to '{key}':[{values}]' to be compliant with future versions")
|
|
|
|
values = [values]
|
|
|
|
|
|
|
|
new_filters[key] = values
|
2021-11-18 18:13:03 +01:00
|
|
|
return new_filters
|