Repository navigation
Expand file tree
/
Copy pathprogram-writing-experiments.txt
More file actions
2825 lines (1389 loc) · 59.4 KB
/
Copy pathprogram-writing-experiments.txt
File metadata and controls
2825 lines (1389 loc) · 59.4 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
---
title: "Program Writing Experiments"
author: "unknown"
tags: ["library"]
type: "essay"
---
{% raw %}
Program Writing Experiments
Open sidebar
Program Writing Experiments
Model: GPT-4
What does this code do? import asyncio
import inspect
import json
import logging
import os
import sys
import time
import traceback
import urllib.parse
import uuid
import traitlets
from ace_client.ace_types.user_machine_types import *
from fastapi import (
FastAPI,
File,
Form,
HTTPException,
Request,
Response,
UploadFile,
WebSocket,
WebSocketDisconnect,
status,
)
from fastapi.responses import JSONResponse, PlainTextResponse, StreamingResponse
from jupyter_client import AsyncKernelClient, AsyncKernelManager, AsyncMultiKernelManager
from pydantic import parse_obj_as
from . import routes, run_jupyter
logger = logging.getLogger(__name__)
logging.basicConfig(
format="[%(asctime)s.%(msecs)03d] [%(levelname)s] [%(name)s] %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d,%H:%M:%S",
stream=sys.stdout,
)
os.chdir(os.path.expanduser("~"))
_MAX_UPLOAD_SIZE = 1024 * 1024 * 1024
_MAX_DOWNLOAD_TIME = 5 * 60.0
_DOWNLOAD_CHUNK_SIZE = 1024 * 1024
_MAX_JUPYTER_MESSAGE_SIZE = 10 * 1024 * 1024
_MAX_KERNELS = 20
app = FastAPI()
jupyter_config = traitlets.config.get_config()
jupyter_config.KernelRestarter.restart_limit = 0
_MULTI_KERNEL_MANAGER = AsyncMultiKernelManager(config=jupyter_config)
_response_to_callback_from_kernel_futures: Dict[str, asyncio.Future] = {}
_timeout_at = {}
_timeout = {}
_timeout_task = None
1 / 1
ChatGPT
ChatGPT
The code you've provided seems to be part of a larger system, possibly for a server application that communicates with Jupyter kernels. The functionality of this piece of code can be described as follows:
Importing necessary modules: The script imports a number of Python libraries required for its operation. These include asyncio for asynchronous programming, json for JSON data handling, logging for logging purposes, inspect and traceback for runtime behavior inspection and error analysis, and others related to HTTP handling and the Jupyter kernel.
Setup logging: The logger is set to log all messages with severity level INFO and above to the standard output (stdout).
Setting up some constants: The constants likely represent the upload size limit, download time limit, download chunk size, the maximum size of a message sent to Jupyter, and the maximum number of kernels.
Initialize FastAPI: FastAPI is a modern web framework for building APIs with Python based on standard Python type hints. It's initialized here with default settings.
Configuring Jupyter: This script seems to interface with Jupyter, a popular interactive programming environment. It uses the Traitlets library to read the Jupyter configuration, then modifies it to disable automatic restarting of the Jupyter kernels.
Create kernel manager: It creates an
AsyncMultiKernelManager
object, which will manage multiple Jupyter kernels asynchronously.
Create some dictionaries and a task: The last few lines of code define some global variables which appear to be dictionaries (
_response_to_callback_from_kernel_futures
,
_timeout_at
,
_timeout
) and a task (
_timeout_task
). The exact purpose of these isn't clear from the provided code.
Remember that without the entire code or at least a larger context, it is impossible to fully understand what the program does. However, given these details, it seems to be a server-like application which handles communication with Jupyter kernels and possibly serves requests over HTTP.
1 / 1
_kernel_queue = None
_fill_kernel_queue_task = None
_first_kernel_started = False
_SELF_IDENTIFY_HEADER_KEY = "x-ace-self-identify"
_SELF_IDENTIFY_HEADER_KEY_BYTES = b"x-ace-self-identify"
_SELF_IDENTIFY_STR = os.getenv("ACE_SELF_IDENTIFY")
_SELF_IDENTIFY_BYTES = os.getenv("ACE_SELF_IDENTIFY").encode("utf-8")
async def _kill_old_kernels():
while True:
await asyncio.sleep(2.0)
for kernel_id in list(_timeout_at.keys()):
if time.monotonic() > _timeout_at[kernel_id]:
logger.info(
f"Killing kernel {kernel_id} due to timeout, {_timeout_at[kernel_id]}, {_timeout[kernel_id]}"
)
await _delete_kernel(kernel_id)
async def _fill_kernel_queue():
global _first_kernel_started, _kernel_queue
try:
_kernel_queue = asyncio.Queue(maxsize=1)
kernel_id = None
kernel_manager = None
while True:
logger.info("Create new kernel for pool: Preparing")
if len(_timeout_at.keys()) >= _MAX_KERNELS:
logger.info(f"Too many kernels ({_MAX_KERNELS}). Deleting oldest kernel.")
sort_key = lambda kernel_id: _timeout_at[kernel_id]
kernels_to_delete = sorted(_timeout_at.keys(), key=sort_key, reverse=True)[
_MAX_KERNELS - 1 :
]
for kernel_id in kernels_to_delete:
logger.info(f"Deleting kernel {kernel_id}")
await _delete_kernel(kernel_id)
logger.info(f"Create new kernel for pool: Making new kernel")
start_time = time.monotonic()
kernel_id = await _MULTI_KERNEL_MANAGER.start_kernel()
kernel_manager = _MULTI_KERNEL_MANAGER.get_kernel(kernel_id)
client = kernel_manager.client()
client.start_channels()
await client.wait_for_ready()
client.stop_channels()
del client
end_time = time.monotonic()
logger.info(
f"Create new kernel for pool: Done making new kernel in {end_time - start_time:.3f} seconds"
)
logger.info(
f"Create new kernel for pool: New kernel id {kernel_id} in {id(_kernel_queue)}"
)
_first_kernel_started = True
await _kernel_queue.put(kernel_id)
except Exception as e:
logger.error(f"Error while filling queue: {e}", exc_info=True)
raise
async def _delete_kernel(kernel_id):
kernel_ids = _MULTI_KERNEL_MANAGER.list_kernel_ids()
if kernel_id in kernel_ids:
kernel_manager = _MULTI_KERNEL_MANAGER.get_kernel(str(kernel_id))
await kernel_manager.shutdown_kernel()
_MULTI_KERNEL_MANAGER.remove_kernel(str(kernel_id))
del _timeout_at[kernel_id]
del _timeout[kernel_id]
1 / 1
ChatGPT
ChatGPT
The code provided appears to further develop the server-like application you shared previously. It adds definitions for asynchronous functions that control the life cycle of Jupyter kernels:
_kill_old_kernels
: This function continuously checks every two seconds if there are any kernels that have exceeded their allotted time (as defined in
_timeout_at
). If a kernel has exceeded its time, it is shut down (killed) and logged.
_fill_kernel_queue
: This function is responsible for creating and managing a queue of Jupyter kernels. It maintains an asyncio queue of size 1 to store the kernels. It continuously checks if the maximum kernel limit (
_MAX_KERNELS
) has been reached. If so, it deletes the oldest kernel. Then, it starts a new kernel and adds its kernel_id to the queue. If the first kernel has not been started yet, the
_first_kernel_started
flag is set to True. Any exceptions encountered during this process are logged and re-raised.
_delete_kernel
: This function accepts a kernel_id as its argument. If the kernel_id exists in the list of kernels managed by the
_MULTI_KERNEL_MANAGER
, it shuts down the kernel and removes it from the manager. It also removes the corresponding entries from the
_timeout_at
and
_timeout
dictionaries.
These functions suggest the system is managing Jupyter kernels in a pool-like fashion, creating new ones when needed, and shutting down older ones that are not in use or when a certain maximum kernel limit has been reached. The kernels appear to be used in a "first-in, first-out" manner as suggested by the queue-like handling.
The actual use of these kernels would become more apparent in other parts of the system code, such as where the kernels are retrieved from the queue and used. It would also help to know the context or purpose of the overall system where this code is part of, as it could be used for a variety of applications from data analysis to machine learning.
1 / 1
@app.on_event("startup")
async def startup():
global _timeout_task, _fill_kernel_queue_task
_timeout_task = asyncio.create_task(_kill_old_kernels())
_fill_kernel_queue_task = asyncio.create_task(_fill_kernel_queue())
@app.on_event("shutdown")
async def shutdown():
_timeout_task.cancel()
_fill_kernel_queue_task.cancel()
async def _SEND_CALLBACK_REQUEST(call: MethodCall):
raise NotImplementedError()
def _is_from_localhost(request: Request) -> bool:
return request.client.host == "127.0.0.1"
async def _forward_callback_from_kernel(call: MethodCall, request: Request):
if not _is_from_localhost(request):
raise HTTPException(status_code=403, detail="Forbidden")
logger.info(f"Forwarding callback request from kernel. {call}")
_response_to_callback_from_kernel_futures[call.request_id] = asyncio.Future()
await _SEND_CALLBACK_REQUEST(call)
response = await _response_to_callback_from_kernel_futures[call.request_id]
logger.info(f"Forwarding callback response to kernel: {call.request_id}.")
del _response_to_callback_from_kernel_futures[call.request_id]
return JSONResponse({"value": response})
app.include_router(routes.get_api_router(_forward_callback_from_kernel), prefix="")
def _respond_to_callback_from_kernel(response: MethodCallReturnValue):
logger.info("Received callback response.")
_response_to_callback_from_kernel_futures[response.request_id].set_result(response.value)
@app.get("/check_liveness")
async def check_liveness():
code = "print(f'{400+56}')\n100+23\n"
logger.info("Health check: running...")
start_time = time.monotonic()
kernel_id = await _create_kernel(timeout=30.0)
kernel_manager = _MULTI_KERNEL_MANAGER.get_kernel(kernel_id)
assert isinstance(kernel_manager, AsyncKernelManager)
try:
execute_result, error_stacktrace, stream_text = await run_jupyter.async_run_code(
kernel_manager, code, shutdown_kernel=False
)
status_code = 200
status = "live"
if error_stacktrace is not None:
status_code = 500
status = "error"
elif execute_result != {"text/plain": "123"} or stream_text != "456\n":
status_code = 500
status = "unexpected_result"
result = {
"execute_result": execute_result,
"stream_text": stream_text,
"error_stacktrace": error_stacktrace,
"status": status,
}
finally:
await _delete_kernel(kernel_id)
end_time = time.monotonic()
logger.info(f"Health check took {end_time - start_time} seconds and returned {result}")
return JSONResponse(content=result, status_code=status_code)
1 / 1
ChatGPT
ChatGPT
This part of the code defines a few additional functions and registers some of them as event handlers in the FastAPI application. Here's a detailed explanation:
startup
: This function is registered to be called when the FastAPI application starts up. It starts two asynchronous tasks using
asyncio.create_task()
,
_kill_old_kernels()
and
_fill_kernel_queue()
. These tasks run continuously in the background, managing the lifecycle of the Jupyter kernels.
shutdown
: This function is registered to be called when the FastAPI application shuts down. It cancels the
_kill_old_kernels()
and
_fill_kernel_queue()
tasks that were started during the application startup.
_SEND_CALLBACK_REQUEST
: This is a placeholder function for sending a callback request. It is currently not implemented.
_is_from_localhost
: This function checks if the HTTP request originated from the same machine where this FastAPI app is running. It's typically used for security reasons.
_forward_callback_from_kernel
: This function takes a method call and a request as parameters. It checks if the request is from the localhost, and if not, raises an HTTP exception with a 403 Forbidden status. It then logs the call and creates an
asyncio.Future
object for the response to the callback from the kernel. The response is awaited and returned as a JSON response.
_respond_to_callback_from_kernel
: This function logs the receipt of a callback response and sets the result of the corresponding
asyncio.Future
object.
/check_liveness
: This function is an HTTP GET endpoint that checks the liveness of the service. It creates a kernel, executes a code snippet using that kernel, and then deletes the kernel. If the execution results in an error or an unexpected result, it sets the HTTP status code to 500 (Internal Server Error) and the status to 'error' or 'unexpected_result'. Otherwise, it sets the HTTP status code to 200 (OK) and the status to 'live'. It logs the duration of the health check and the result and returns them as a JSON response.
These additions further support the idea that this code is part of an HTTP server application designed to manage and interact with Jupyter kernels. The liveness endpoint would typically be used for monitoring or health checks, such as by a load balancer or an orchestration service like Kubernetes.
1 / 1
@app.get("/check_startup")
async def check_startup():
if not _first_kernel_started:
logger.info("Failed health check")
return JSONResponse(
content={"status": "failed", "reason": "kernel queue is not initialized"},
status_code=500,
)
logger.info("Passed health check")
return JSONResponse(content={"status": "started"})
@app.post("/upload")
async def upload(upload_request: str = Form(), file: UploadFile = File()):
logger.info("Upload request")
request = parse_obj_as(UploadFileRequest, json.loads(upload_request))
try:
total_size = 0
with open(request.destination, "wb") as f:
while chunk := file.file.read():
total_size += len(chunk)
if total_size > _MAX_UPLOAD_SIZE:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="File too large",
)
f.write(chunk)
except Exception:
try:
os.remove(request.destination)
except Exception as e:
logger.exception(f"Error while removing file: {request.destination}", exc_info=e)
raise
logger.info(f"Upload request complete. {upload_request}")
return JSONResponse(content={})
@app.get("/download/{path:path}")
async def download(path: str):
path = urllib.parse.unquote(path)
if not os.path.isfile(path):
raise HTTPException(404, f"File not found: {path}")
logger.info(f"Download request. {path}")
def iterfile():
with open(path, "rb") as f:
while chunk := f.read(_DOWNLOAD_CHUNK_SIZE):
yield chunk
return StreamingResponse(
iterfile(),
headers={"Content-Length": f"{os.path.getsize(path)}"},
media_type="application/octet-stream",
)
@app.get("/check_file/{path:path}")
async def check_file(path: str):
path = "/" + urllib.parse.unquote(path)
logger.info(f"Check file request. {path}")
exists = os.path.isfile(path)
size = os.path.getsize(path) if exists else 0
return CheckFileResponse(exists=exists, size=size, too_large=False)
@app.get("/kernel/{kernel_id}")
async def kernel_state(kernel_id: str):
logger.info(f"Get kernel state request. {kernel_id}")
if kernel_id not in _timeout_at:
time_remaining_ms = 0.0
else:
time_remaining_ms = max(0.0, _timeout_at[kernel_id] - time.monotonic()) * 1000.0
return GetKernelStateResponse(time_remaining_ms=time_remaining_ms)
async def _create_kernel(timeout: float):
assert _kernel_queue is not None, "Queue should be initialized once health checks pass."
kernel_id = await _kernel_queue.get()
_timeout[kernel_id] = timeout
_timeout_at[kernel_id] = time.monotonic() + timeout
return kernel_id
1 / 1
ChatGPT
ChatGPT
This additional section of code sets up more routes for the FastAPI application, namely
/check_startup
,
/upload
,
/download/{path:path}
,
/check_file/{path:path}
, and
/kernel/{kernel_id}
:
/check_startup
: This is a GET endpoint that checks whether the first kernel has been started successfully. If it hasn't, it returns an HTTP 500 response indicating a "failed" status with a reason. If the kernel has started, it returns a response indicating a "started" status.
/upload
: This is a POST endpoint used to upload a file to the server. The request is expected to contain JSON data and a file. The file is saved to a location specified in the JSON data. The server also checks to ensure the file doesn't exceed a maximum upload size. If an error occurs during the file upload, any part of the file that was uploaded is removed.
/download/{path:path}
: This is a GET endpoint for downloading a file from the server. The path to the file is provided in the URL. If the file does not exist, a 404 error is returned. Otherwise, the file is streamed to the client as a response.
/check_file/{path:path}
: This is a GET endpoint that checks whether a specific file exists on the server and returns information about it, including its size and whether it's too large.
/kernel/{kernel_id}
: This is a GET endpoint that returns the remaining time for a kernel specified by its kernel_id. It checks the kernel_id against the _timeout_at dictionary.
_create_kernel
: This is a helper function to create a new Jupyter kernel with a specified timeout. It updates the _timeout and _timeout_at dictionaries with the kernel_id and its associated timeout information.
Overall, these endpoints and functions facilitate operations such as checking server readiness, uploading and downloading files, checking the existence and size of files, and querying the status of a Jupyter kernel.
1 / 1
@app.post("/kernel")
async def create_kernel(create_kernel_request: CreateKernelRequest):
logger.info(f"Create kernel request. {create_kernel_request}")
timeout = create_kernel_request.timeout
kernel_id = await _create_kernel(timeout=timeout)
logger.info(f"Got kernel id from queue. {create_kernel_request}")
return CreateKernelResponse(kernel_id=kernel_id)
@app.websocket("/channel")
async def channel(websocket: WebSocket):
async def send_callback_request(call: MethodCall):
await websocket.send_text(call.json())
logger.info("Setting global forward function.")
global _SEND_CALLBACK_REQUEST
_SEND_CALLBACK_REQUEST = send_callback_request
await websocket.accept(headers=[(_SELF_IDENTIFY_HEADER_KEY_BYTES, _SELF_IDENTIFY_BYTES)])
clients: Dict[str, AsyncKernelClient] = {}
recv_from_api_server = asyncio.create_task(websocket.receive_text())
recv_from_jupyter = None
try:
while True:
logger.info(f"Waiting for message. {recv_from_api_server}, {recv_from_jupyter}")
done, _ = await asyncio.wait(
[task for task in [recv_from_api_server, recv_from_jupyter] if task is not None],
return_when=asyncio.FIRST_COMPLETED,
)
logger.info(f"Got messages for {done}.")
if recv_from_api_server in done:
done_future = recv_from_api_server
recv_from_api_server = asyncio.create_task(websocket.receive_text())
request = parse_obj_as(UserMachineRequest, json.loads(done_future.result()))
logger.info(f"Received message from API server. {request}")
if isinstance(request, RegisterActivityRequest):
logger.info(f"Registering activity. {request}")
_timeout_at[request.kernel_id] = time.monotonic() + _timeout[request.kernel_id]
elif isinstance(request, MethodCallReturnValue):
_respond_to_callback_from_kernel(request)
elif isinstance(request, MethodCall):
async def run(request: UserMachineRequest):
try:
object_reference = request.object_reference
if object_reference.type == "multi_kernel_manager":
referenced_object = _MULTI_KERNEL_MANAGER
elif object_reference.type == "kernel_manager":
referenced_object = _MULTI_KERNEL_MANAGER.get_kernel(
object_reference.id
)
elif object_reference.type == "client":
referenced_object = clients[object_reference.id]
else:
raise Exception(
f"Unknown object reference type: {object_reference.type}"
)
qualified_method = f"{object_reference.type}.{request.method}"
logger.info(
f"Method call: {qualified_method} args: {request.args} kwargs: {request.kwargs}"
)
value = getattr(referenced_object, request.method)(
*request.args, **request.kwargs
)
if inspect.isawaitable(value):
value = await value
return (request.request_id, value, None)
except Exception as e:
return (request.request_id, None, e)
assert recv_from_jupyter is None
recv_from_jupyter = asyncio.create_task(run(request))
if recv_from_jupyter in done:
done_future = recv_from_jupyter
recv_from_jupyter = None
request_id, value, e = done_future.result()
if e is None:
logger.info(f"Received result from Jupyter. {value}")
if isinstance(value, AsyncKernelClient):
client_id = str(uuid.uuid4())
clients[client_id] = value
result = MethodCallObjectReferenceReturnValue(
request_id=request_id,
object_reference=ObjectReference(type="client", id=client_id),
)
elif isinstance(value, AsyncKernelManager):
result = MethodCallObjectReferenceReturnValue(
request_id=request_id,
object_reference=ObjectReference(
type="kernel_manager", id=value.kernel_id
),
)
else:
result = MethodCallReturnValue(request_id=request_id, value=value)
else:
logger.info(f"Received result from Jupyter. Exception: {value}")
result = MethodCallException(
request_id=request_id,
type=type(e).__name__,
value=str(e),
traceback=traceback.format_tb(e.__traceback__),
)
del e
1 / 1
ChatGPT
ChatGPT
This code snippet includes the definitions for two routes,
/kernel
and
/channel
:
/kernel
: This is a POST endpoint for creating a new Jupyter kernel with a given timeout. It accepts a JSON request containing the desired timeout, creates a new kernel with that timeout, and returns the ID of the newly created kernel.
/channel
: This is a websocket endpoint that allows two-way communication between the client and the server. This communication channel is used for several purposes, including registering kernel activity, managing the execution of methods on various objects, and sending callback requests from kernels.
This is a complex endpoint, so here's a breakdown of what's going on:
First, it defines a helper function
send_callback_request
that sends a message over the websocket connection. This function is then stored in the global variable
_SEND_CALLBACK_REQUEST
.
The endpoint then accepts the incoming websocket connection.
The endpoint creates a dictionary
clients
to hold instances of
AsyncKernelClient
, which are used to interact with Jupyter kernels.