-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1790 lines (1580 loc) · 75.2 KB
/
server.py
File metadata and controls
1790 lines (1580 loc) · 75.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json, os, re, math, sys
import inspect
from copy import deepcopy
import logging
from pynvml import (
nvmlInit,
nvmlDeviceGetCount,
nvmlDeviceGetHandleByIndex,
nvmlDeviceGetMemoryInfo
)
from fastapi import FastAPI, UploadFile, Request, WebSocket, HTTPException, status
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware import Middleware
from sqlalchemy import text
from typing import Literal, Tuple, Union, List, Dict, Awaitable, Callable, Optional, Any
from ray import serve
from ray.serve.handle import DeploymentHandle
from ray.util.placement_group import PlacementGroup
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from QueryLake.api import api
from QueryLake.database import database_admin_operations
from QueryLake.database.create_db_session import initialize_database_engine
from QueryLake.runtime.db_compat import (
DeploymentProfile,
build_capabilities_payload,
build_profile_diagnostics_payload,
validate_current_db_profile,
)
from QueryLake.runtime.profile_bringup import build_profile_bringup_payload
from QueryLake.runtime.projection_refresh import (
ProjectionRefreshRequest,
build_projection_diagnostics_payload,
explain_projection_refresh_plan,
execute_projection_refresh_plan,
build_projection_refresh_plan,
)
from QueryLake.typing.config import Config, AuthType, Model
from QueryLake.typing.toolchains import ToolChain, ToolChainV2
try:
from QueryLake.operation_classes.ray_web_scraper import WebScraperDeployment
except Exception as exc:
logging.getLogger(__name__).warning(
"WebScraperDeployment import failed (%s). Web scraping will be unavailable.",
exc,
)
@serve.deployment(name="web_scraper:stub")
class WebScraperDeployment:
async def run(self, *args, **kwargs):
return None
from sse_starlette.sse import EventSourceResponse
from QueryLake.misc_functions.function_run_clean import get_function_call_preview, get_function_specs
from QueryLake.typing.function_calling import FunctionCallDefinition
from QueryLake.api.single_user_auth import (
global_public_key,
global_private_key,
process_input_as_auth_type,
OAUTH_SECRET_KEY,
)
from QueryLake.api.auth_utils import resolve_bearer_auth_header
from QueryLake.runtime.request_context import RequestContext, set_request_context, set_request_id
from QueryLake.runtime.auth_provider import register_provider
from QueryLake.runtime.auth_provider_local import LocalAuthProvider
from QueryLake.runtime.auth_provider_oauth import OAuthAuthProvider
from QueryLake.runtime.umbrella_scaling import get_umbrella_deployment_options
from QueryLake.misc_functions.external_providers import external_llm_count_tokens
from QueryLake.misc_functions.server_class_functions import find_function_calls
from QueryLake.routing.ws_toolchain import toolchain_websocket_handler
from QueryLake.routing.openai_completions import (
openai_chat_completion,
openai_create_embedding,
)
from QueryLake.routing.api_call_router import api_general_call
from QueryLake.routing.llm_call import llm_call
from QueryLake.routing.upload_documents import handle_document
from QueryLake.routing.misc_models import (
embedding_call,
embedding_sparse_call,
rerank_call,
web_scrape_call
)
from QueryLake.runtime.service import ToolchainRuntimeService
from QueryLake.observability import metrics
from QueryLake.database import sql_db_tables as T
from jose import jwt
from QueryLake.files.service import FilesRuntimeService
def _ensure_logging_configured() -> None:
"""Ensure all QueryLake processes have a sane logging configuration.
Ray Serve replicas often start in fresh interpreter processes without the
root logger being configured. When that happens, module-level loggers default
to WARNING and emit nothing, making debugging nearly impossible. We install
a basic StreamHandler the first time we import the server module so that
INFO-level logs propagate into Ray's log aggregation by default.
"""
root_logger = logging.getLogger()
has_stream_handler = any(
isinstance(handler, logging.StreamHandler) for handler in root_logger.handlers
)
if not has_stream_handler:
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")
)
root_logger.addHandler(stream_handler)
level_name = os.environ.get("QUERYLAKE_LOG_LEVEL", "INFO").upper()
try:
root_logger.setLevel(level_name)
except (ValueError, TypeError):
root_logger.setLevel(logging.INFO)
for handler in root_logger.handlers:
try:
handler.setLevel(root_logger.level)
except Exception: # pragma: no cover - defensive
continue
logging.captureWarnings(True)
_ensure_logging_configured()
logger = logging.getLogger(__name__)
def build_readyz_payload(
*,
model_ids: List[str],
profile: Optional[DeploymentProfile] = None,
metadata_store_path: Optional[str] = None,
) -> Dict[str, Any]:
capabilities_payload = build_capabilities_payload(profile)
profile_diagnostics_payload = build_profile_diagnostics_payload(
profile,
metadata_store_path=metadata_store_path,
)
profile_bringup_payload = build_profile_bringup_payload(
profile=profile,
metadata_store_path=metadata_store_path,
)
return {
"ok": True,
"db": "ok",
"models": list(model_ids),
"db_profile": capabilities_payload.get("profile"),
"db_profile_diagnostics": profile_diagnostics_payload.get("startup_validation"),
"db_profile_bringup": {
"summary": dict(profile_bringup_payload.get("summary") or {}),
"projection_ids_needing_build": list(
profile_bringup_payload.get("projection_ids_needing_build") or []
),
"route_runtime_blocked_ids": list(
profile_bringup_payload.get("route_runtime_blocked_ids") or []
),
"backend_unreachable_planes": list(
profile_bringup_payload.get("backend_unreachable_planes") or []
),
},
}
def _recommend_gpu_memory_fraction(
required_vram: int,
max_model_len: Optional[int],
per_node_capacity: Optional[int],
configured_fraction: Optional[float],
) -> float:
"""Heuristically choose a GPU memory utilization fraction for vLLM models."""
try:
configured = float(configured_fraction) if configured_fraction is not None else 0.0
except (TypeError, ValueError):
configured = 0.0
if per_node_capacity and per_node_capacity > 0:
base_fraction = required_vram / per_node_capacity
context_bonus = 0.0
if max_model_len:
context_bonus = max(0.0, (max_model_len - 8192) / 16384.0) * 0.15
heuristic = min(0.9, base_fraction + context_bonus)
if configured <= 0.0:
candidate = heuristic
elif configured + 1e-3 < heuristic:
candidate = heuristic
else:
candidate = min(configured, 0.9)
candidate = max(candidate, base_fraction)
else:
candidate = max(configured, 0.4)
return max(0.3, min(candidate, 0.9))
def _select_gpu_fraction(
existing_fraction: Optional[float],
recommended_fraction: float,
) -> float:
"""Reserve a slightly larger Ray GPU fraction to avoid oversubscription."""
try:
existing = float(existing_fraction) if existing_fraction is not None else 0.0
except (TypeError, ValueError):
existing = 0.0
target = max(existing, recommended_fraction + 0.05)
if target >= 0.99:
return 1.0
return max(round(target, 3), 0.01)
def _estimate_reserved_vram(
per_node_capacity: Optional[int],
required_vram: int,
util_fraction: float,
gpu_fraction: float,
) -> int:
"""Derive the VRAM resource reservation to hand to Ray."""
if not per_node_capacity or per_node_capacity <= 0:
return required_vram
projected_fraction = max(util_fraction, gpu_fraction)
return max(
required_vram,
int(math.ceil(per_node_capacity * projected_fraction)),
)
# This import was added in error and is being removed.
# from QueryLake.log_utils import set_up_logger
origins = [
"http://localhost:3001",
"localhost:3001",
"0.0.0.0:3001"
]
middleware = [
Middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)
]
fastapi_app = FastAPI(
# lifespan=lifespan
middleware=middleware
)
@fastapi_app.get("/favicon.ico", include_in_schema=False)
async def favicon() -> Response:
# Avoid noisy 404s when users open backend URLs (e.g. /healthz) in a browser.
# We intentionally return 204 rather than serving an asset so the backend can
# remain stateless and avoid bundling frontend files.
return Response(status_code=204)
@fastapi_app.middleware("http")
async def attach_request_context(request: Request, call_next):
import time
request_id = request.headers.get("x-request-id") or request.headers.get("X-Request-Id")
request_id = set_request_id(request_id)
set_request_context(
RequestContext(
request_id=request_id,
route=request.url.path,
)
)
start = time.time()
response: Response = await call_next(request)
latency = time.time() - start
metrics.record_request(request.url.path, response.status_code, latency)
response.headers["x-request-id"] = request_id
return response
API_FUNCTIONS = [str(pair[0]) for pair in inspect.getmembers(api, inspect.isfunction)]
API_FUNCTIONS_ALLOWED = list(set(API_FUNCTIONS) - set(api.excluded_member_function_descriptions))
API_FUNCTIONS_ALLOWED = [func for func in API_FUNCTIONS_ALLOWED if (not re.match(r"__.*?__", func))]
API_FUNCTIONS = [func for func in API_FUNCTIONS_ALLOWED]
API_FUNCTION_HELP_DICTIONARY, API_FUNCTION_HELP_GUIDE = {}, ""
for func in API_FUNCTIONS:
if not hasattr(api, func):
continue
API_FUNCTION_HELP_DICTIONARY[func] = {
"result": get_function_call_preview(getattr(api, func), api.system_arguments),
}
API_FUNCTION_HELP_GUIDE += "%s\n\n\n\n" % get_function_call_preview(getattr(api, func), api.system_arguments)
def clean_function_arguments_for_api(system_args : dict,
user_args : dict,
function_name : str = None,
function_args = None,
bypass_disabled : bool = False,
function_object : Callable = None) -> dict:
synth_args = deepcopy(user_args)
if not function_object is None:
function_args = list(inspect.signature(function_object).parameters.items())
function_args = [arg[0] for arg in function_args]
elif not function_name is None and (function_name in API_FUNCTIONS or bypass_disabled) and function_args is None:
function_args = list(inspect.signature(getattr(api, function_name)).parameters.items())
function_args = [arg[0] for arg in function_args]
keys_get = list(synth_args.keys())
logger.debug("Cleaning args with %s and %s", function_args, keys_get)
for key in keys_get:
if key in system_args or (not function_args is None and not key in function_args):
del synth_args[key]
for key in system_args.keys():
if function_args is None or key in function_args:
synth_args[key] = system_args[key]
return synth_args
@serve.deployment(max_ongoing_requests=100)
@serve.ingress(fastapi_app)
class UmbrellaClass:
def __init__(
self,
configuration: Config,
toolchains_v1: Dict[str, ToolChain],
toolchains_v2: Dict[str, ToolChainV2],
web_scraper_handle: DeploymentHandle,
llm_handles: Dict[str, DeploymentHandle] = {},
embedding_handles: Dict[str, DeploymentHandle] = None,
rerank_handles: Dict[str, DeploymentHandle] = None,
surya_handles: Dict[str, DeploymentHandle] = None,
chandra_handles: Dict[str, DeploymentHandle] = None,
):
logger.info("Initializing UmbrellaClass deployment")
self.config : Config = configuration
self.toolchain_configs : Dict[str, ToolChain] = toolchains_v1
self.toolchain_configs_v2 : Dict[str, ToolChainV2] = toolchains_v2
self.llm_handles_no_stream = llm_handles
self.llm_handles : Dict[str, DeploymentHandle] = { k : handle.options(
# This is what enables streaming/generators. See: https://docs.ray.io/en/latest/serve/api/doc/ray.serve.handle.DeploymentResponseGenerator.html
stream=True,
) for k, handle in llm_handles.items()} if self.config.enabled_model_classes.llm else {}
self.llm_configs : Dict[str, Model] = { config.id : config for config in self.config.models }
self.embedding_handles = embedding_handles
self.rerank_handles = rerank_handles
self.web_scraper_handle = web_scraper_handle
self.surya_handles = surya_handles if surya_handles else {}
self.chandra_handles = chandra_handles if chandra_handles else {}
logger.info("Connecting to database and synchronizing metadata")
try:
self.database, self.engine = initialize_database_engine()
logger.info("Database connection established")
database_admin_operations.add_models_to_database(self.database, self.config.models)
database_admin_operations.add_toolchains_to_database(self.database, self.toolchain_configs)
logger.info("Database model/toolchain sync complete")
except Exception as exc:
logger.exception("Failed to initialize database session: %s", exc)
raise
# Register the default auth provider (local DB-backed).
register_provider("local", LocalAuthProvider(self.database))
if os.getenv("QL_AUTH_OAUTH_ENABLED") == "1":
register_provider("oauth", OAuthAuthProvider())
self.toolchain_runtime = ToolchainRuntimeService(
umbrella=self,
toolchains_v1=self.toolchain_configs,
toolchains_v2=self.toolchain_configs_v2,
)
self.files_runtime = FilesRuntimeService(self.database, umbrella=self)
self.default_function_arguments = {
# All model deployments
"server_llm_handles_no_stream": self.llm_handles_no_stream,
"server_llm_handles": self.llm_handles,
"server_embedding_handles": self.embedding_handles,
"server_rerank_handles": self.rerank_handles,
"server_web_scraper_handle": self.web_scraper_handle,
"server_surya_handles": self.surya_handles,
"server_chandra_handles": self.chandra_handles,
"database": self.database,
"toolchains_available": self.toolchain_configs,
"public_key": global_public_key,
"server_private_key": global_private_key,
"toolchain_function_caller": self.api_function_getter,
"global_config": self.config,
"toolchain_runtime_service": self.toolchain_runtime,
"umbrella": self,
"job_signal_bus": self.toolchain_runtime.signal_bus,
}
self.special_function_table = {
"llm": self.llm_call,
"llm_count_tokens": self.llm_count_tokens,
"embedding": self.embedding_call,
"embedding_sparse": self.embedding_sparse_call,
"rerank": self.rerank_call,
"web_scrape": self.web_scrape_call,
"find_function_calls": find_function_calls,
"function_help": self.get_all_function_descriptions
}
self.all_functions = API_FUNCTIONS_ALLOWED+list(self.special_function_table.keys())
self.all_function_descriptions = [
{
"endpoint": f"/api/{func_name}",
"api_function_id": func_name,
**get_function_specs(
self.api_function_getter(func_name),
excluded_arguments=list(self.default_function_arguments.keys()),
querylake_auth_sub=True
)
}
for func_name in self.all_functions
]
logger.info("UmbrellaClass initialization complete")
logger.debug("Enabled model classes: %s", self.config.enabled_model_classes)
async def _resolve_auth(self, request: Request, auth_payload: Optional[dict]) -> AuthType:
if auth_payload is not None:
return process_input_as_auth_type(auth_payload)
auth_header = request.headers.get("authorization")
if auth_header and auth_header.lower().startswith("bearer "):
return resolve_bearer_auth_header(auth_header)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required")
async def embedding_call(self,
auth : AuthType,
inputs : List[str],
model: str = None):
return await embedding_call(self, auth, inputs, model)
async def embedding_sparse_call(
self,
auth: AuthType,
inputs: List[str],
model: str = None,
):
return await embedding_sparse_call(self, auth, inputs, model)
async def rerank_call(
self,
auth : AuthType,
inputs : Union[List[Tuple[str, str]], Tuple[str, str]],
normalize : Union[bool, List[bool]] = True,
model: str = None
):
return await rerank_call(self, auth, inputs, normalize, model)
async def web_scrape_call(
self,
auth : AuthType,
inputs : Union[str, List[str]],
timeout : Union[float, List[float]] = 10,
markdown : Union[bool, List[bool]] = True,
load_strategy : Union[Literal["full", "eager", "none"], list] = "full",
summary: Union[bool, List[bool]] = False
):
return await web_scrape_call(self, auth, inputs, timeout, markdown, load_strategy, summary)
async def llm_count_tokens(self, model_id : str, input_string : str):
model_specified = model_id.split("/")
if len(model_specified) == 1:
assert model_id in self.llm_handles, f"Model choice [{model_id}] not available for LLMs (tried to count tokens)"
return await self.llm_handles_no_stream[model_id].count_tokens.remote(input_string)
else:
return external_llm_count_tokens(input_string, model_id)
@fastapi_app.post("/v1/chat/completions")
async def openai_chat_completions_endpoint(
self,
raw_request : Request
):
return await openai_chat_completion(self, raw_request)
@fastapi_app.post("/v2/kernel/chat/completions")
async def openai_chat_completions_endpoint_v2(self, raw_request: Request):
return await self.openai_chat_completions_endpoint(raw_request)
@fastapi_app.post("/v1/embeddings")
async def openai_embedding_endpoint(
self,
raw_request: Request
):
return await openai_create_embedding(self, raw_request)
@fastapi_app.post("/v2/kernel/embeddings")
async def openai_embedding_endpoint_v2(self, raw_request: Request):
return await self.openai_embedding_endpoint(raw_request)
@fastapi_app.get("/v1/models")
async def list_models_endpoint(self):
local_models = [model.model_dump() for model in self.config.models]
external_models = []
for provider_name, models in (self.config.external_model_providers or {}).items():
for entry in models:
external_models.append(
{
"id": f"{provider_name}/{entry.id}",
"name": entry.name,
"context": entry.context,
"modelcard": entry.modelcard,
"provider": provider_name,
}
)
return {"data": local_models + external_models}
@fastapi_app.get("/v1/models/{model_id}")
async def get_model_endpoint(self, model_id: str):
for model in self.config.models:
if model.id == model_id:
return model.model_dump()
if "/" in model_id:
provider_name, provider_model = model_id.split("/", 1)
for entry in (self.config.external_model_providers or {}).get(provider_name, []):
if entry.id == provider_model:
return {
"id": model_id,
"name": entry.name,
"context": entry.context,
"modelcard": entry.modelcard,
"provider": provider_name,
}
raise HTTPException(status_code=404, detail="Model not found")
async def llm_call(self,
auth : AuthType,
question : str = None,
model_parameters : dict = {},
model : str = None,
lora_id : str = None,
sources : List[dict] = [],
chat_history : List[dict] = None,
stream_callables: Dict[str, Awaitable[Callable[[str], None]]] = None,
functions_available: List[Union[FunctionCallDefinition, dict]] = None,
only_format_prompt: bool = False):
return await llm_call(
self, auth, question,
model_parameters,
model, lora_id, sources, chat_history,
stream_callables,
functions_available,
only_format_prompt
)
def get_all_function_descriptions(self):
"""
Return a list of all available API functions with their specifications.
"""
return self.all_function_descriptions
def api_function_getter(self, function_name):
if function_name in self.special_function_table:
return self.special_function_table[function_name]
assert function_name in API_FUNCTIONS_ALLOWED, f"Invalid API Function '{function_name}' Called"
return getattr(api, function_name)
@fastapi_app.post("/update_documents")
@fastapi_app.post("/upload_document")
async def upload_document(self, req : Request, file : UploadFile):
return await handle_document(self, clean_function_arguments_for_api, req, file)
@fastapi_app.post("/v2/kernel/update_documents")
@fastapi_app.post("/v2/kernel/upload_document")
async def upload_document_v2(self, req: Request, file: UploadFile):
return await self.upload_document(req, file)
@fastapi_app.get("/api/ping")
async def ping_function(self, req: Request):
logger.debug("Ping received from %s", req.client.host if req.client else "unknown")
return {"success": True, "note": "Pong"}
@fastapi_app.get("/v2/kernel/ping")
async def ping_function_v2(self, req: Request):
return await self.ping_function(req)
@fastapi_app.get("/v1/capabilities")
async def capabilities(self):
return build_capabilities_payload()
@fastapi_app.get("/v2/kernel/capabilities")
async def capabilities_v2(self):
return build_capabilities_payload()
@fastapi_app.get("/v1/profile-diagnostics")
async def profile_diagnostics(self):
return build_profile_diagnostics_payload()
@fastapi_app.get("/v2/kernel/profile-diagnostics")
async def profile_diagnostics_v2(self):
return build_profile_diagnostics_payload()
@fastapi_app.get("/v1/projection-diagnostics")
async def projection_diagnostics(self):
return build_projection_diagnostics_payload()
@fastapi_app.get("/v2/kernel/projection-diagnostics")
async def projection_diagnostics_v2(self):
return build_projection_diagnostics_payload()
@fastapi_app.get("/v1/profile-bringup")
async def profile_bringup(self):
return build_profile_bringup_payload()
@fastapi_app.get("/v2/kernel/profile-bringup")
async def profile_bringup_v2(self):
return build_profile_bringup_payload()
@fastapi_app.post("/v1/projection-plan/explain")
async def projection_plan_explain(self, request: Request):
body = await request.json()
refresh_request = ProjectionRefreshRequest.model_validate(body or {})
return explain_projection_refresh_plan(refresh_request).model_dump()
@fastapi_app.post("/v2/kernel/projection-plan/explain")
async def projection_plan_explain_v2(self, request: Request):
return await self.projection_plan_explain(request)
@fastapi_app.post("/v1/projection-refresh/run")
async def projection_refresh_run(self, request: Request):
body = await request.json()
refresh_request = ProjectionRefreshRequest.model_validate(body or {})
plan = build_projection_refresh_plan(refresh_request)
return execute_projection_refresh_plan(plan, database=self.database).model_dump()
@fastapi_app.post("/v2/kernel/projection-refresh/run")
async def projection_refresh_run_v2(self, request: Request):
return await self.projection_refresh_run(request)
# -----------------
# Files v1 endpoints
# -----------------
@fastapi_app.post("/files")
async def upload_file_endpoint(self, request: Request, file: UploadFile, logical_name: Optional[str] = None, collection_id: Optional[str] = None):
auth = await self._resolve_auth(request, None)
checksum = request.headers.get("x-checksum-sha256")
idem = request.headers.get("idempotency-key")
result = await self.files_runtime.upload_file(
auth,
file,
logical_name=logical_name,
collection_id=collection_id,
checksum_sha256=checksum,
idempotency_key=idem,
)
return {"success": True, **result}
@fastapi_app.get("/files/{file_id}")
async def get_file_endpoint(self, file_id: str, request: Request):
auth = await self._resolve_auth(request, None)
result = await self.files_runtime.list_file(file_id, auth=auth)
return {"success": True, **result}
@fastapi_app.get("/files/{file_id}/versions")
async def get_file_versions_endpoint(self, file_id: str, request: Request):
auth = await self._resolve_auth(request, None)
result = await self.files_runtime.list_versions(file_id, auth=auth)
return {"success": True, "versions": result}
@fastapi_app.get("/files/{file_id}/events")
async def get_file_events_endpoint(self, file_id: str, request: Request, since: Optional[int] = None):
auth = await self._resolve_auth(request, None)
result = await self.files_runtime.list_events(file_id, since, auth=auth)
return {"success": True, "events": result}
@fastapi_app.get("/files/{file_id}/jobs")
async def get_file_jobs_endpoint(self, file_id: str, request: Request):
auth = await self._resolve_auth(request, None)
result = await self.files_runtime.list_jobs(file_id, auth=auth)
return {"success": True, "jobs": result}
@fastapi_app.get("/files/{file_id}/stream")
async def files_stream_endpoint(self, file_id: str, request: Request):
auth = await self._resolve_auth(request, None)
_ = auth
subscriber = await self.files_runtime.subscribe(file_id)
last_event_id_str = request.headers.get("last-event-id") or request.query_params.get("last_event_id")
since_rev = None
if last_event_id_str is not None:
try:
since_rev = int(last_event_id_str)
except ValueError:
since_rev = None
if since_rev is not None:
history = await self.files_runtime.list_events(file_id, since_rev, auth=auth)
for event in history:
await subscriber.push({"event": event.get("kind"), "data": json.dumps(event), "id": event.get("rev")})
async def event_generator():
try:
async for message in subscriber.stream():
yield message
finally:
await self.files_runtime.unsubscribe(file_id, subscriber)
return EventSourceResponse(event_generator())
@fastapi_app.post("/v2/kernel/files")
async def upload_file_endpoint_v2(self, request: Request, file: UploadFile, logical_name: Optional[str] = None, collection_id: Optional[str] = None):
return await self.upload_file_endpoint(request, file, logical_name, collection_id)
@fastapi_app.get("/v2/kernel/files/{file_id}")
async def get_file_endpoint_v2(self, file_id: str, request: Request):
return await self.get_file_endpoint(file_id, request)
@fastapi_app.get("/v2/kernel/files/{file_id}/versions")
async def get_file_versions_endpoint_v2(self, file_id: str, request: Request):
return await self.get_file_versions_endpoint(file_id, request)
@fastapi_app.get("/v2/kernel/files/{file_id}/events")
async def get_file_events_endpoint_v2(self, file_id: str, request: Request, since: Optional[int] = None):
return await self.get_file_events_endpoint(file_id, request, since)
@fastapi_app.get("/v2/kernel/files/{file_id}/jobs")
async def get_file_jobs_endpoint_v2(self, file_id: str, request: Request):
return await self.get_file_jobs_endpoint(file_id, request)
@fastapi_app.get("/v2/kernel/files/{file_id}/stream")
async def files_stream_endpoint_v2(self, file_id: str, request: Request):
return await self.files_stream_endpoint(file_id, request)
@fastapi_app.post("/files/{file_id}/versions/{version_id}/process")
async def process_file_version_endpoint(
self,
file_id: str,
version_id: str,
request: Request,
ocr_profile: Optional[str] = None,
):
auth = await self._resolve_auth(request, None)
result = await self.files_runtime.process_version(
file_id,
version_id,
auth=auth,
ocr_profile=ocr_profile,
)
return {"success": True, **result}
@fastapi_app.get("/files/cas/{sha256}")
async def get_file_bytes_cas(self, sha256: str, request: Request):
auth = await self._resolve_auth(request, None)
# Resolve permission by locating any file_version referencing CAS
from sqlmodel import select
matches = self.database.exec(select(T.file_version).where(T.file_version.bytes_cas == sha256)).all()
for fv in matches:
try:
await self.files_runtime.list_file(fv.file_id, auth=auth)
data = self.files_runtime.store.get_bytes(sha256)
if data is None:
raise HTTPException(status_code=404, detail="Object not found")
return Response(content=data, media_type="application/octet-stream")
except HTTPException:
continue
raise HTTPException(status_code=404, detail="Object not found")
@fastapi_app.post("/files/presign")
async def presign_file_download(self, request: Request):
body = await request.json()
auth = await self._resolve_auth(request, body.get("auth"))
file_id = body.get("file_id")
version_id = body.get("version_id")
bytes_cas = body.get("bytes_cas")
expires_in = int(body.get("expires_in", 300))
_username = (await self.toolchain_runtime.get_session_state if False else None) # placeholder to quiet linters
# Permission gate via file listing
if file_id:
await self.files_runtime.list_file(file_id, auth=auth)
cas = bytes_cas
if not cas:
if not (file_id and version_id):
raise HTTPException(status_code=400, detail="Provide either bytes_cas or (file_id, version_id)")
fv = self.database.get(T.file_version, version_id)
if fv is None or fv.file_id != file_id:
raise HTTPException(status_code=404, detail="version not found")
cas = fv.bytes_cas
# Build token
from datetime import datetime, timedelta, timezone
username = self.files_runtime._username_from_auth(auth)
payload = {"cas": cas, "sub": username or "files", "exp": datetime.now(timezone.utc) + timedelta(seconds=expires_in)}
token = jwt.encode(payload, OAUTH_SECRET_KEY, algorithm="HS256")
return {"success": True, "token": token, "expires_in": expires_in}
@fastapi_app.get("/files/download/{token}")
async def download_presigned(self, token: str):
try:
payload = jwt.decode(token, OAUTH_SECRET_KEY, algorithms=["HS256"])
cas = payload.get("cas")
if not cas:
raise HTTPException(status_code=400, detail="Invalid token")
data = self.files_runtime.store.get_bytes(cas)
if data is None:
raise HTTPException(status_code=404, detail="Object not found")
return Response(content=data, media_type="application/octet-stream")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid or expired token: {e}")
@fastapi_app.get("/metrics")
async def metrics_endpoint(self):
body, content_type = metrics.expose_metrics()
return Response(content=body, media_type=content_type)
@fastapi_app.get("/healthz")
async def healthz(self):
return {"ok": True}
@fastapi_app.get("/readyz")
async def readyz(self):
try:
self.database.exec(text("SELECT 1"))
except Exception as e:
raise HTTPException(status_code=503, detail=f"db not ready: {e}")
return build_readyz_payload(model_ids=list(self.llm_configs.keys()))
# Callable by POST and GET
@fastapi_app.post("/api/{rest_of_path:path}")
@fastapi_app.get("/api/{rest_of_path:path}")
async def api_general_call(self, req: Request, rest_of_path: str, file: UploadFile = None):
return await api_general_call(
self,
clean_function_arguments_for_api,
API_FUNCTION_HELP_DICTIONARY,
API_FUNCTION_HELP_GUIDE,
req, rest_of_path, file
)
@fastapi_app.websocket("/toolchain")
async def toolchain_websocket_handler(self, ws: WebSocket):
return await toolchain_websocket_handler(
self,
ws,
clean_function_arguments_for_api,
api.fetch_toolchain_session,
api.create_toolchain_session,
api.toolchain_file_upload_event_call,
api.save_toolchain_session,
api.toolchain_event_call
)
@fastapi_app.post("/sessions")
async def create_session_endpoint(self, request: Request):
body = await request.json()
auth = await self._resolve_auth(request, body.get("auth"))
toolchain_id = body.get("toolchain_id")
if not toolchain_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="toolchain_id required")
title = body.get("title")
initial_inputs = body.get("initial_inputs")
result = await self.toolchain_runtime.create_session(auth, toolchain_id, title, initial_inputs)
return {"success": True, **result}
@fastapi_app.get("/sessions/{session_id}")
async def get_session_endpoint(self, session_id: str, request: Request):
auth = await self._resolve_auth(request, None)
state = await self.toolchain_runtime.get_session_state(session_id, auth)
return {"success": True, **state}
@fastapi_app.delete("/sessions/{session_id}")
async def delete_session_endpoint(self, session_id: str, request: Request):
auth = await self._resolve_auth(request, None)
await self.toolchain_runtime.delete_session(session_id, auth)
return {"success": True}
@fastapi_app.post("/sessions/{session_id}/event")
async def post_session_event(self, session_id: str, request: Request):
body = await request.json()
auth = await self._resolve_auth(request, body.get("auth"))
node_id = body.get("node_id")
if not node_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="node_id required")
inputs = body.get("inputs", {})
expected_rev = body.get("rev")
correlation_id = body.get("correlation_id")
result = await self.toolchain_runtime.post_event(
session_id,
node_id,
inputs,
expected_rev,
auth=auth,
correlation_id=correlation_id,
)
return {"success": True, **result}
@fastapi_app.get("/sessions/{session_id}/events")
async def list_session_events(self, session_id: str, request: Request, since: Optional[int] = None):
auth = await self._resolve_auth(request, None)
events = await self.toolchain_runtime.list_events(session_id, since, auth)
return {"success": True, "events": [event.model_dump() for event in events]}
@fastapi_app.get("/sessions/{session_id}/jobs")
async def list_session_jobs(self, session_id: str, request: Request):
auth = await self._resolve_auth(request, None)
jobs = await self.toolchain_runtime.list_jobs(session_id, auth)
return {"success": True, "jobs": jobs}
@fastapi_app.post("/sessions/{session_id}/jobs/{job_id}/cancel")
async def cancel_session_job(self, session_id: str, job_id: str, request: Request):
auth = await self._resolve_auth(request, None)
result = await self.toolchain_runtime.cancel_job(session_id, job_id, auth)
return {"success": True, **result}
@fastapi_app.get("/sessions/{session_id}/stream")
async def stream_session(self, session_id: str, request: Request):
auth = await self._resolve_auth(request, None)
subscriber = await self.toolchain_runtime.subscribe(session_id, auth)
last_event_id_str = request.headers.get("last-event-id") or request.query_params.get("last_event_id")
since_rev = None
if last_event_id_str is not None:
try:
since_rev = int(last_event_id_str)
except ValueError:
since_rev = None
if since_rev is not None:
history = await self.toolchain_runtime.list_events(session_id, since_rev, auth)
for event in history:
await subscriber.push(event.model_dump())
async def event_generator():
try:
async for message in subscriber.stream():
payload = {key: value for key, value in message.items() if value is not None}
yield payload
finally:
await self.toolchain_runtime.unsubscribe(session_id, subscriber)
return EventSourceResponse(event_generator())
@fastapi_app.post("/v2/kernel/sessions")
async def create_session_endpoint_v2(self, request: Request):
return await self.create_session_endpoint(request)
@fastapi_app.get("/v2/kernel/sessions/{session_id}")
async def get_session_endpoint_v2(self, session_id: str, request: Request):
return await self.get_session_endpoint(session_id, request)
@fastapi_app.delete("/v2/kernel/sessions/{session_id}")
async def delete_session_endpoint_v2(self, session_id: str, request: Request):
return await self.delete_session_endpoint(session_id, request)
@fastapi_app.post("/v2/kernel/sessions/{session_id}/event")
async def post_session_event_v2(self, session_id: str, request: Request):
return await self.post_session_event(session_id, request)
@fastapi_app.get("/v2/kernel/sessions/{session_id}/events")
async def list_session_events_v2(self, session_id: str, request: Request, since: Optional[int] = None):
return await self.list_session_events(session_id, request, since)
@fastapi_app.get("/v2/kernel/sessions/{session_id}/jobs")
async def list_session_jobs_v2(self, session_id: str, request: Request):
return await self.list_session_jobs(session_id, request)
@fastapi_app.post("/v2/kernel/sessions/{session_id}/jobs/{job_id}/cancel")
async def cancel_session_job_v2(self, session_id: str, job_id: str, request: Request):
return await self.cancel_session_job(session_id, job_id, request)
@fastapi_app.get("/v2/kernel/sessions/{session_id}/stream")
async def stream_session_v2(self, session_id: str, request: Request):
return await self.stream_session(session_id, request)
@fastapi_app.post("/v2/kernel/api/{rest_of_path:path}")
@fastapi_app.get("/v2/kernel/api/{rest_of_path:path}")
async def api_general_call_v2(self, req: Request, rest_of_path: str, file: UploadFile = None):
return await self.api_general_call(req, rest_of_path, file)
# This function is the new entrypoint for the application, called by start_querylake.py
def _get_placement_bundle() -> Dict[str, Union[int, float]]:
"""Get the placement group bundle configuration (GPU, VRAM_MB, CPU) for this deployment."""
try:
import ray
import pynvml
pynvml.nvmlInit()
device_count = pynvml.nvmlDeviceGetCount()
bundle = {"GPU": 1}
# Add VRAM if we can detect it
if device_count > 0:
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
memory_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
vram_mb = memory_info.total // (1024 * 1024)
bundle["VRAM_MB"] = vram_mb
# Add CPU - calculate CPU allocation per GPU node based on actual per-node CPU availability
gpu_nodes = [node for node in ray.nodes() if node.get("Resources", {}).get("GPU", 0) > 0 and node.get("alive", False)]