-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1235 lines (1042 loc) · 31.2 KB
/
Copy pathapp.py
File metadata and controls
1235 lines (1042 loc) · 31.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
from contextlib import asynccontextmanager
from fastapi import (
FastAPI,
File,
Form,
HTTPException,
Query,
Request,
UploadFile,
)
from fastapi.responses import (
HTMLResponse,
)
from fastapi.staticfiles import (
StaticFiles,
)
from fastapi.templating import (
Jinja2Templates,
)
import asyncio
import ast
import httpx
import json
import os
from pathlib import Path
from config_loader import (
config,
ROOT as CONFIG_ROOT,
)
from app_settings import (
settings,
)
from utils.urls import (
join_url,
)
from utils.launcher_trace import (
launcher_trace_enabled,
trace_inbound_http,
trace_outgoing_request,
trace_outgoing_response,
)
from utils.chat_log import (
migrate_legacy_chat_logs,
)
from utils.session_restore import (
build_archived_session_restore_payload,
build_archived_session_preview,
list_archived_sessions,
get_archived_session_summary,
delete_archived_session,
)
from websocket import (
websocket_router,
)
from clients.registry import build_clients
from runtime.client import RuntimeClient
from runtime.model_switch import (
RuntimeModelSwitchError,
initialize_runtime_model,
)
from runtime.LT_memory import (
start_lt_memory_server_scheduler,
stop_lt_memory_server_scheduler,
)
from runtime.registry import runtime_state
from runtime.state import (
BRAIN_RUNTIME_ID,
SERVICE_RUNTIME_ID,
)
from runtime.behavior_contract import (
get_behavior_contract,
)
from utils.rule_citations import (
get_rule_citation_registry,
)
from utils.file_manager_asset_utils import (
read_asset_text_preview,
)
from utils.attached_files_store import (
FILES_DIR,
delete_file_record,
ensure_files_dir,
get_file_record,
public_file_snapshot,
restore_file_record,
set_file_pinned,
store_uploaded_file,
)
STATUS_CHECK_TIMEOUT = getattr(
config,
"STATUS_CHECK_TIMEOUT",
0.5,
)
# ---------------------------------------------------------
# APP LIFESPAN
# ---------------------------------------------------------
@asynccontextmanager
async def lifespan(application: FastAPI):
ensure_files_dir()
migrate_legacy_chat_logs()
# -----------------------------------------------------
# SHARED HTTP CLIENT
# -----------------------------------------------------
application.state.http_client = httpx.AsyncClient(
timeout=None,
limits=httpx.Limits(
max_connections=100,
max_keepalive_connections=20,
),
http2=False,
event_hooks={
"request": [trace_outgoing_request],
"response": [trace_outgoing_response],
},
)
# -----------------------------------------------------
# RUNTIME CLIENTS
# -----------------------------------------------------
application.state.clients = build_clients(
application.state.http_client
)
start_lt_memory_server_scheduler(
application.state
)
yield
# -----------------------------------------------------
# SHUTDOWN
# -----------------------------------------------------
await stop_lt_memory_server_scheduler(
application.state
)
from websocket.transport import stop_runtime_transports
await stop_runtime_transports(application.state)
await application.state.http_client.aclose()
app = FastAPI(
lifespan=lifespan,
)
app.middleware("http")(trace_inbound_http)
templates = Jinja2Templates(
directory="ui/templates",
)
app.mount(
"/static",
StaticFiles(directory="ui/static"),
name="static",
)
ensure_files_dir()
app.mount(
"/assets/files",
StaticFiles(directory=str(FILES_DIR)),
name="attached_files",
)
app.include_router(
websocket_router
)
@app.get("/api/sessions/{session_id}/restore")
async def api_restore_archived_session(session_id: str):
payload = build_archived_session_restore_payload(
session_id
)
if payload is None:
raise HTTPException(
status_code=404,
detail="Archived session not found",
)
return payload
@app.get("/api/sessions")
async def api_list_archived_sessions():
return {"sessions": list_archived_sessions()}
@app.get("/api/sessions/{session_id}/summary")
async def api_archived_session_summary(session_id: str):
summary = get_archived_session_summary(session_id)
if summary is None:
raise HTTPException(status_code=404, detail="Session not saved yet")
return summary
@app.get("/api/sessions/{session_id}/preview")
async def api_preview_archived_session(session_id: str):
payload = build_archived_session_preview(session_id)
if payload is None:
raise HTTPException(status_code=404, detail="Session preview not found")
return payload
@app.delete("/api/sessions/{session_id}")
async def api_delete_archived_session(session_id: str):
try:
deleted = await asyncio.to_thread(delete_archived_session, session_id)
except OSError as error:
raise HTTPException(status_code=500, detail="Could not delete session logs") from error
if not deleted:
raise HTTPException(status_code=404, detail="Saved session not found")
return {"deleted": True, "session_id": session_id}
@app.get("/api/files")
async def api_list_files():
return public_file_snapshot()
@app.post("/api/files/link-folder")
async def api_link_folder(request: Request):
from urllib.parse import urlsplit
from utils.project_reader import link_project_folder
origin = request.headers.get("origin")
if origin and urlsplit(origin).netloc != request.headers.get("host"):
raise HTTPException(status_code=403, detail="Origin not allowed")
if request.headers.get("content-type", "").split(";", 1)[0] != "application/json":
raise HTTPException(status_code=415, detail="Expected JSON")
try:
payload = await request.json()
if not isinstance(payload, dict) or not isinstance(payload.get("path"), str):
raise ValueError("Provide a folder path")
record, created, pin_error = link_project_folder(payload["path"])
except (OSError, ValueError, RuntimeError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
return {"file": record, "created": created, "pin_error": pin_error, **public_file_snapshot()}
@app.post("/api/files/upload")
async def api_upload_file(
file: UploadFile = File(...),
width: str = Form(""),
height: str = Form(""),
):
content = await file.read()
def parse_dimension(value):
try:
number = int(str(value or "").strip())
except (TypeError, ValueError):
return None
return number if number > 0 else None
record, created, pin_error = store_uploaded_file(
name=file.filename or "attachment",
content=content,
mime_type=file.content_type or "",
width=parse_dimension(width),
height=parse_dimension(height),
pin=True,
)
return {
"file": record,
"created": created,
"pin_error": pin_error,
**public_file_snapshot(),
}
@app.post("/api/files/{file_id}/pin")
async def api_pin_file(
file_id: str,
pinned: bool = Query(True),
):
record, error = set_file_pinned(file_id, pinned)
if record is None:
raise HTTPException(status_code=404, detail="File not found")
if error == "max_attached_files":
raise HTTPException(status_code=409, detail="Maximum 5 attached files")
return {
"file": record,
**public_file_snapshot(),
}
@app.delete("/api/files/{file_id}")
async def api_delete_file(file_id: str):
if not delete_file_record(file_id):
raise HTTPException(status_code=404, detail="File not found")
return public_file_snapshot()
@app.post("/api/files/{file_id}/restore")
async def api_restore_file(
file_id: str,
file: UploadFile = File(...),
record: str = Form("{}"),
):
try:
metadata = json.loads(record or "{}")
except json.JSONDecodeError as error:
raise HTTPException(status_code=400, detail="Invalid file restore metadata") from error
if not isinstance(metadata, dict):
raise HTTPException(status_code=400, detail="Invalid file restore metadata")
restored, error = restore_file_record(
file_id,
record=metadata,
content=await file.read(),
)
if restored is None:
status = 409 if error == "id_exists" else 400
raise HTTPException(status_code=status, detail=error or "File restore failed")
return {
"file": restored,
**public_file_snapshot(),
}
@app.get("/api/files/{file_id}/preview")
async def api_preview_file(file_id: str):
record = get_file_record(file_id)
if record is None:
raise HTTPException(status_code=404, detail="File not found")
payload = {"file": record}
if record.get("kind") == "text":
path = FILES_DIR / record["stored_name"]
try:
payload["text_content"] = path.read_text(encoding="utf-8", errors="replace")
except OSError:
payload["text_content"] = ""
return payload
# ---------------------------------------------------------
# INDEX PAGE
# ---------------------------------------------------------
def _runtime_status_context_window(status: dict | None) -> int:
try:
value = int((status or {}).get("context_window") or 0)
except (TypeError, ValueError):
return 0
return value if value > 0 else 0
def build_runtime_config(
*,
brain_status: dict | None = None,
service_status: dict | None = None,
):
brain_context_window = _runtime_status_context_window(
brain_status
)
service_context_window = _runtime_status_context_window(
service_status
)
if not settings.SERVICE_CONFIGURED:
service_context_window = brain_context_window
return {
"service": {
"label": "service",
"api_base": config.SERVICE_API_BASE,
"model": config.SERVICE_MODEL_UID,
"used_tokens": 0,
"context_tokens": 0,
"total_tokens": 0,
"max_tokens": service_context_window,
},
"brain": {
"label": "brain",
"api_base": config.BRAIN_API_BASE,
"model": config.BRAIN_MODEL_UID,
"used_tokens": 0,
"context_tokens": 0,
"total_tokens": 0,
"max_tokens": brain_context_window,
},
}
RUNTIME_CONFIG_WRITE_FIELDS = {
"service": {
"model": "SERVICE_MODEL_UID",
},
"brain": {
"model": "BRAIN_MODEL_UID",
},
}
RUNTIME_CONFIG_API_BASE_FIELDS = {
"service": "SERVICE_API_BASE",
"brain": "BRAIN_API_BASE",
}
def normalize_runtime_endpoint_base(base_url: object) -> str:
return str(base_url or "").strip().rstrip("/")
def _format_config_literal(value):
if isinstance(value, str):
return repr(value)
if isinstance(value, bool):
return "True" if value else "False"
return str(value)
def write_runtime_config_values(updates: dict[str, object]) -> None:
config_path = CONFIG_ROOT / "config.py"
if not config_path.exists():
raise FileNotFoundError(
f"config.py not found at {config_path}"
)
# Windows PowerShell launchers write UTF-8 with BOM; strip it before AST parsing.
text = config_path.read_text(
encoding="utf-8-sig"
)
tree = ast.parse(
text
)
lines = text.splitlines()
replaced: set[str] = set()
for node in ast.walk(tree):
if not isinstance(node, ast.Assign):
continue
for target in node.targets:
if (
not isinstance(target, ast.Name)
or target.id not in updates
):
continue
if (
getattr(node, "end_lineno", node.lineno)
!= node.lineno
):
raise ValueError(
f"Cannot rewrite multiline config value {target.id}"
)
line_index = node.lineno - 1
current_line = lines[line_index]
indent = current_line[
:len(current_line) - len(current_line.lstrip())
]
lines[line_index] = (
f"{indent}{target.id} = "
f"{_format_config_literal(updates[target.id])}"
)
replaced.add(target.id)
missing = [
name
for name in updates
if name not in replaced
]
if missing and lines and lines[-1].strip():
lines.append("")
for name in missing:
lines.append(
f"{name} = {_format_config_literal(updates[name])}"
)
config_path.write_text(
"\n".join(lines).rstrip() + "\n",
encoding="utf-8",
)
def apply_runtime_config_values(
updates: dict[str, object],
application: FastAPI | None = None,
) -> None:
for name, value in updates.items():
setattr(
config,
name,
value,
)
if hasattr(settings, name):
object.__setattr__(
settings,
name,
value,
)
if not settings.SERVICE_CONFIGURED:
fallback_pairs = {
"SERVICE_API_BASE": "BRAIN_API_BASE",
"SERVICE_MODEL_UID": "BRAIN_MODEL_UID",
}
for service_name, brain_name in fallback_pairs.items():
value = getattr(
config,
brain_name,
)
setattr(
config,
service_name,
value,
)
object.__setattr__(
settings,
service_name,
value,
)
runtime_state.update_runtime_state(
BRAIN_RUNTIME_ID,
model=settings.BRAIN_MODEL_UID,
max_tokens=0,
)
runtime_state.update_runtime_state(
SERVICE_RUNTIME_ID,
model=settings.SERVICE_MODEL_UID,
max_tokens=0,
)
if (
application is None
or not hasattr(application.state, "http_client")
):
return
next_clients = build_clients(
application.state.http_client
)
current_clients = getattr(
application.state,
"clients",
None,
)
if isinstance(current_clients, dict):
current_clients.clear()
current_clients.update(
next_clients
)
else:
application.state.clients = next_clients
def compact_runtime_model_options(models: list[dict]) -> list[dict]:
options = []
seen = set()
for model in models:
model_type = str(
model.get("type")
or model.get("model_type")
or ""
).strip().casefold()
if model_type in {
"embedding",
"embeddings",
}:
continue
model_id = (
model.get("id")
or model.get("key")
or model.get("model")
or model.get("name")
)
model_id = str(model_id or "").strip()
if not model_id or model_id in seen:
continue
display_name = (
model.get("display_name")
or model.get("name")
or model.get("label")
or model_id
)
options.append({
"id": model_id,
"name": str(display_name or model_id).strip(),
})
seen.add(model_id)
return options
@app.get(
"/",
response_class=HTMLResponse,
)
async def index(
request: Request,
):
status_snapshot = await build_status_snapshot(
request.app.state.http_client
)
return templates.TemplateResponse(
request,
"index.html",
{
"runtime_config": (
status_snapshot[
"runtime_config"
]
),
"runtime_status": {
"brain": status_snapshot["brain"],
"service": status_snapshot["service"],
"service_configured": (
status_snapshot[
"service_configured"
]
),
},
"format_response": (
status_snapshot["format_response"]
),
},
)
# ---------------------------------------------------------
# API STATUS
# ---------------------------------------------------------
async def fetch_runtime_model_status(
client: httpx.AsyncClient,
*,
base_url: str,
model_uid: str,
):
runtime = RuntimeClient(
api_base=base_url,
model_uid=model_uid,
timeout=STATUS_CHECK_TIMEOUT,
client=client,
)
online = False
attempted_url = ""
detected_url = ""
detected_source = ""
available_models = []
best_status = None
for endpoint in runtime.model_limits_detection_endpoints():
request_url = join_url(base_url, endpoint)
if not attempted_url:
attempted_url = request_url
try:
response = await client.get(
request_url,
timeout=STATUS_CHECK_TIMEOUT,
)
except (
httpx.HTTPError,
asyncio.TimeoutError,
):
continue
if response.status_code != 200:
continue
online = True
detected_url = request_url
detected_source = (
"openai"
if endpoint == settings.MODELS_ENDPOINT
else "native"
)
try:
models = runtime.extract_model_list(
response.json()
)
except ValueError:
continue
available_models = compact_runtime_model_options(
models
)
model = runtime.select_model_metadata(models)
if model is None:
continue
loaded_model = runtime.select_loaded_model_metadata(
model
)
loaded_instances = model.get("loaded_instances")
loaded = (
loaded_model is not None
if isinstance(loaded_instances, list)
else None
)
context_window = runtime.extract_context_window_from_model(
loaded_model
)
candidate_status = {
"online": True,
"source": detected_source,
"url": detected_url,
"available_models": available_models,
"loaded": loaded,
"model": model,
"loaded_model": loaded_model or {},
"context_window": context_window or 0,
}
if best_status is None:
best_status = candidate_status
# A catalog entry without a live context window is not enough for the
# panel. Keep probing the remaining provider endpoints until one of
# them reports the actual loaded n_ctx/context_length.
if context_window:
return candidate_status
if best_status is not None:
return best_status
return {
"online": online,
"source": detected_source,
"url": detected_url or attempted_url,
"available_models": available_models,
"loaded": None,
"model": {},
"loaded_model": {},
"context_window": 0,
}
async def build_status_snapshot(
client: httpx.AsyncClient,
):
brain_request = fetch_runtime_model_status(
client,
base_url=config.BRAIN_API_BASE,
model_uid=config.BRAIN_MODEL_UID,
)
if settings.SERVICE_CONFIGURED:
brain_status, service_status = await asyncio.gather(
brain_request,
fetch_runtime_model_status(
client,
base_url=config.SERVICE_API_BASE,
model_uid=config.SERVICE_MODEL_UID,
),
)
else:
brain_status = await brain_request
service_status = {
"online": False,
"source": "",
"url": "",
"available_models": [],
"loaded": None,
"model": {},
"loaded_model": {},
"context_window": 0,
}
brain_online = bool(brain_status.get("online"))
service_online = bool(service_status.get("online"))
brain_context_window = _runtime_status_context_window(
brain_status
)
service_context_window = (
_runtime_status_context_window(service_status)
if settings.SERVICE_CONFIGURED
else brain_context_window
)
runtime_state.update_runtime_state(
BRAIN_RUNTIME_ID,
model=settings.BRAIN_MODEL_UID,
max_tokens=brain_context_window,
status="online" if brain_online else "offline",
)
runtime_state.update_runtime_state(
SERVICE_RUNTIME_ID,
model=settings.SERVICE_MODEL_UID,
max_tokens=service_context_window,
status=(
"online"
if settings.SERVICE_CONFIGURED and service_online
else "offline"
),
)
runtime_config = build_runtime_config(
brain_status=brain_status,
service_status=service_status,
)
runtime_config["service"]["lm_studio"] = service_status
runtime_config["brain"]["lm_studio"] = brain_status
return {
"brain": brain_online,
"service": service_online,
"service_configured": settings.SERVICE_CONFIGURED,
"service_route": (
"dedicated"
if settings.SERVICE_CONFIGURED
else "brain_fallback"
),
"format_response": True,
"runtime_config": runtime_config,
}
@app.get("/api/status")
async def api_status():
return await build_status_snapshot(
app.state.http_client
)
@app.post("/api/runtime-model/switch")
async def api_switch_runtime_model(request: Request):
try:
payload = await request.json()
except json.JSONDecodeError as error:
raise HTTPException(
status_code=400,
detail="Invalid JSON",
) from error
if not isinstance(payload, dict):
raise HTTPException(
status_code=400,
detail="Invalid payload",
)
role = str(
payload.get("role") or ""
).strip().lower()
role_fields = RUNTIME_CONFIG_WRITE_FIELDS.get(
role
)
if role_fields is None:
raise HTTPException(
status_code=400,
detail="Invalid runtime role",
)
if (
role == "service"
and not settings.SERVICE_CONFIGURED
):
raise HTTPException(
status_code=409,
detail=(
"Dedicated Service runtime is not configured"
),
)
model = str(
payload.get("model") or ""
).strip()
if not model:
raise HTTPException(
status_code=400,
detail="Model is required",
)
current_base = normalize_runtime_endpoint_base(
getattr(
settings,
RUNTIME_CONFIG_API_BASE_FIELDS[role],
)
)
requested_base = normalize_runtime_endpoint_base(
payload.get("base_url") or current_base
)
if not current_base:
raise HTTPException(
status_code=400,
detail="Runtime endpoint is not configured",
)
if requested_base != current_base:
raise HTTPException(
status_code=400,
detail="Runtime endpoint cannot be switched here",
)
try:
switch_result = await initialize_runtime_model(
app.state.http_client,
role=role,
model_uid=model,
base_url=current_base,
cached_load_config=payload.get("load_config"),
)
except RuntimeModelSwitchError as error:
raise HTTPException(
status_code=502,
detail=str(error),
) from error
updates: dict[str, object] = {
role_fields["model"]: model,
}
try:
write_runtime_config_values(updates)
apply_runtime_config_values(
updates,
app,
)
except Exception as error:
# LM Studio has already completed the load at this point. Keep a local
# sync failure distinct from a model-load failure in the modal.
raise HTTPException(
status_code=500,
detail=(
"Model loaded in LM Studio, but JIN failed to sync "
f"runtime config: {error}"
),
) from error
try:
snapshot = await build_status_snapshot(
app.state.http_client
)
except Exception as error:
# Status metadata is presentation data. A failed refresh must not turn
# an already completed model switch into a false HTTP 500.
switch_result["status_refresh_error"] = (
f"{type(error).__name__}: {error}"
)
fallback_status = {
"online": True,
"source": "native",
"url": current_base,
"available_models": [],
"loaded": True,
"model": {
"key": model,
"id": model,
},
"loaded_model": {
"id": switch_result.get("instance_id") or model,
"config": switch_result.get("load_config") or {},
},
}
fallback_status["context_window"] = (
RuntimeClient.extract_context_window_from_model(