Run these cells in order in a disposable JupyterLab project. The setup asks for the absolute Jupyter server root and checks that it exists and contains this kernel’s working folder before making server-root-relative file references. Enter the folder JupyterLab serves, even when this notebook and its kernel are in a nested folder. Use a live kernel and selected ChatGPT connection.
Tool catalog: notebook outputs and canvas
Run these cells in order in a disposable JupyterLab project. The setup asks for the absolute Jupyter server root and checks that it exists and contains this kernel’s working folder before making server-root-relative file references. Enter the folder JupyterLab serves, even when this notebook and its kernel are in a nested folder. Use a live kernel and selected ChatGPT connection.
The PNG, SVG, text, and structured outputs below are generated here and are actual live notebook outputs. The early read_selection cells show the honest empty state; the final selected-text section shows how to read text after focusing its editor while the request is pending. Canvas controls depend on whether JupyterLab keeps the plain HTML canvas in its output; an unsupported result is honest and does not justify substituting a fake canvas. Wait for each browser receipt before inspecting it. The final AI questions request real tool calls against these exact output cells.
from io import BytesIO
from pathlib import Path, PurePosixPath
import hashlib
from PIL import Image as PILImage
from IPython.display import display, Image, SVG, HTML, Javascript
from nbinlineai.tools import (read_notebook_view, read_selection, list_outputs, read_output, export_output, list_canvases, capture_canvas, export_canvas, start_canvas, capture_notebook_region, operation_status, release_media, stop_source)
root_text =input('Absolute Jupyter server root (the folder served by JupyterLab): ').strip()
root_choice = Path(root_text).expanduser()
ifnot root_choice.is_absolute():
raiseValueError('Enter an absolute Jupyter server-root folder; do not use the kernel working directory as a guess.')
server_root = root_choice.resolve(strict=True)
ifnot server_root.is_dir() ornot Path.cwd().resolve().is_relative_to(server_root):
raiseValueError('The server root must be an existing folder containing this kernel working directory.')
defserver_ref(path):
"""Make a server-root-relative path for an owned file or save destination."""
target = Path(path).resolve()
return target.relative_to(server_root).as_posix()
defserver_file(reference):
"""Map a server-returned relative path to the configured local root."""ifnotisinstance(reference, str) ornot reference or'\\'in reference:
raiseValueError('Expected a server-root-relative media path.')
relative = PurePosixPath(reference)
if relative.is_absolute() or relative.as_posix() != reference or reference =='.'or'..'in relative.parts:
raiseValueError('Media path must be a clean server-root-relative path.')
candidate = server_root / reference
ifnot candidate.resolve().is_relative_to(server_root):
raiseValueError('Media path escapes the configured server root.')
return candidate
image = PILImage.new('RGB', (8, 8), '#d4402f')
stream = BytesIO(); image.save(stream, format='PNG')
PNG_BYTES = stream.getvalue()
SVG_MARKUP ='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="18"><rect width="24" height="18" fill="#2542a3"/></svg>'print('Disposable PNG and original SVG are ready; no file was saved.')
Disposable PNG and original SVG are ready; no file was saved.
display(Image(data=PNG_BYTES))
print('Existing output text: red square and blue vector')
Existing output text: red square and blue vector
display(SVG(data=SVG_MARKUP))
Existing structured output
This small data-resource MIME output is read from the live model; exporting it returns exact UTF-8 JSON bytes and may save a new .json file. No renderer or code execution is triggered by discovery.
print('Selection:', selection.status, selection.result, selection.error)
print('An empty selection is expected if no text was selected in this editor.')
Selection: completed {'cell_id': None, 'text': '', 'truncated': False} None
An empty selection is expected if no text was selected in this editor.
The next cell creates a 64×32 canvas and draws red and blue blocks using a short local drawing command. It is an ordinary notebook output, not an app or widget. Some JupyterLab sanitizers remove or disable canvas content; the list/capture tools must report that result honestly. Do not substitute a simulated canvas.
display(HTML('<canvas id="catalog-output-canvas" width="64" height="32" aria-label="Disposable red and blue canvas"></canvas>'))
display(Javascript("const canvas = document.getElementById('catalog-output-canvas'); if (canvas) { const context = canvas.getContext('2d'); context.fillStyle = '#d4402f'; context.fillRect(0, 0, 32, 32); context.fillStyle = '#2542a3'; context.fillRect(32, 0, 32, 32); }"))
<IPython.core.display.Javascript object>
canvas_listing = list_outputs('output-canvas')
print(canvas_listing.status, canvas_listing.result, canvas_listing.error)
canvas_output_ref = canvas_listing.result['outputs'][0] if canvas_listing.result and canvas_listing.result['outputs'] elseNone
canvases = list_canvases(canvas_output_ref['cell_id'], canvas_output_ref['output_id'], canvas_output_ref['revision']) if canvas_output_ref elseNone
print(canvases.status, canvases.result, canvases.error) if canvases elseprint('List the canvas output first.')
canvas_ref = canvases.result['canvases'][0] if canvases and canvases.result and canvases.result.get('canvases') elseNone
canvas_still = capture_canvas(canvas_ref) if canvas_ref elseNone
print(canvas_still.status, getattr(canvas_still.result, 'size', None), canvas_still.error) if canvas_still elseprint('Canvas unavailable in this renderer.')
if canvas_still and canvas_still.status =='completed':
print('Canvas pixel (4, 4):', canvas_still.result.getpixel((4, 4)))
display(canvas_still.result.resize((128, 128)))
canvas_source = start_canvas(canvas_ref, frame_rate=12) if canvas_ref elseNone
print(canvas_source.status, canvas_source.result, canvas_source.error) if canvas_source elseprint('Canvas unavailable in this renderer.')
print('The cleanup cell below stops an opened source through the shared source control.')
completed {'source_id': '[opaque hardware reference]', 'kind': 'canvas', 'video': True, 'audio': False, 'requested_frame_rate': 12, 'actual_frame_rate': 12, 'width': 64, 'height': 32, 'note': 'Canvas frames may be throttled when the notebook is in the background.'} None
The cleanup cell below stops an opened source through the shared source control.
Capture a supported visible output region
Scroll so the raster output below is completely visible. The region includes its displayed output rectangle only, not code or inputs. Unsupported or partly hidden output is an explicit error.
display(Image(data=PNG_BYTES))
region = capture_notebook_region(['region-raster'])
print(region.status, getattr(region.result, 'size', None), region.error)
if region.status =='completed':
display(region.result.resize((128, 128)))
completed (8, 8) None
if canvas_source and canvas_source.result and canvas_source.result.get('source_id'):
stopped_source = stop_source(canvas_source.result['source_id'])
released_outputs = {}
seen_media_ids =set()
for label, receipt in [
('raster export', raster_export), ('vector export', vector_export),
('data export', data_export), ('saved data', data_saved),
('canvas still', canvas_still), ('canvas export', canvas_saved),
('region', region),
]:
descriptor = receipt.media if receipt and receipt.status =='completed'elseNone
media_id = descriptor.get('media_id') ifisinstance(descriptor, dict) elseNoneif media_id and media_id notin seen_media_ids:
seen_media_ids.add(media_id)
released_outputs[label] = release_media(media_id)
for receipt in (data_saved, canvas_saved):
descriptor = receipt.media if receipt and receipt.status =='completed'elseNoneifisinstance(descriptor, dict) and descriptor.get('path'):
saved_path = server_file(descriptor['path'])
ifnot saved_path.is_file() or hashlib.sha256(saved_path.read_bytes()).hexdigest() != descriptor['sha256']:
raiseRuntimeError(f'Saved file is missing or changed; inspect before cleanup: {descriptor["path"]}')
saved_path.unlink()
print('Requested release for', len(released_outputs), 'owned outputs; removed matching generated files.')
Requested release for 7 owned outputs; removed matching generated files.
print('Canvas source:', stopped_source.status, stopped_source.error) if'stopped_source'inglobals() elseprint('No canvas source to stop.')
for label, receipt in released_outputs.items():
print('Release', label, receipt.status, receipt.error)
Canvas source: completed None
Release raster export completed None
Release vector export completed None
Release data export completed None
Release saved data completed None
Release canvas still completed None
Release canvas export completed None
Release region completed None
Ask ChatGPT about the live outputs
Run these questions one at a time. Each browser action first returns an operation ID and a running or waiting state. After the media row completes, run its later status question before using its output ID, canvas ID, source ID, or managed media ID. Select text for the selection question. Near the region question, execute the adjacent disposable raster cell and keep its output fully visible.
Use &read_notebook_view for this open notebook. Report only its immediate operation ID/state; the later status question will describe the view.
Use &operation_status on the preceding read_notebook_view operation ID after its media row completes. Report the actual notebook and active-cell facts; if still running, stop and retry later.
The notebook has 68 cells. The active cell is source-stop-inspect (index 39), also the only selected cell. It’s in command mode; four cells are visible, from outputs-cleanup to outputs-ai-view-selection.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Use &operation_status on that list_outputs operation ID after completion. Report the actual output ID, revision, and MIME type; if still running, retry later.
output-text has output ID 55dc7920f34e5de633de570e694c7a46, revision 0, and MIME type text/plain.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Use &read_output on the exact cell ID, output ID, and revision in $text_ref, with max_chars=120. Report its immediate operation ID/state, not the text yet.
{“operation_id”:“6oRikkpO4o31I400ioMyy-lvhCSN5nRC”,“status”:“completed”,“result”:{“cell_id”:“output-text”,“output_id”:“55dc7920f34e5de633de570e694c7a46”,“revision”:0,“mime”:“text/plain”,“text”:“Existing output text: red square and blue vector\n”,“start”:0,“next_start”:null,“total_chars”:49}}
Use &export_output on the exact cell ID, output ID, and revision in $raster_ref, with save_to=None. Report the immediate operation ID/state; no file should be written.
Use &operation_status on that export_output operation ID after completion. Report actual image dimensions, MIME type, SHA-256, and managed media ID if provided; do not put pixels in text.
Export completed: 8 × 8 PNG (image/png); SHA-256 269661e8dbcb389941d2a1c41323776fac18a1ee3a08e9582a6c485291b53a88; managed media ID RpVgbq9HQKIR6bW41PD2vvsqmdma0XHz.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Use &list_canvases on the exact cell ID, output ID, and revision in $canvas_output_ref. Report its immediate operation ID/state. If this renderer strips the canvas, do not claim one exists.
Use &operation_status on the prior list_canvases operation ID. Report the actual canvas ID/descriptor only if completed; otherwise describe the real unsupported or pending result.
If the preceding status returned a supported canvas, use &capture_canvas on that exact descriptor. Report only its immediate operation ID/state; otherwise stop without making up a canvas.
Use &operation_status on the capture_canvas operation ID after completion. Report actual dimensions, encoded hash, and managed media ID if returned; the direct Python inspection above shows the sampled pixel. If still running or unsupported, say so.
If a supported canvas descriptor was verified above, use &export_canvas on it with save_to=None. Report the immediate operation ID/state; otherwise stop without claiming a file or image.
Use &operation_status on that export_canvas operation ID after completion. Report actual image dimensions, hash, and managed media ID if returned; this in-memory request writes no file.
Canvas export completed in memory: 64 × 32 PNG; SHA-256 86288e0fa1dc75499ca89bc4c9aa63a44ad6c8981502445adf1f14a9d123f175; managed media ID LLe0rl3jMbQOXTmnL8mwA92c_BZLdOe9. No file was written.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
If a supported canvas descriptor was verified above, use &start_canvas at 12 frames per second. Report only its immediate operation ID/state; otherwise stop.
{“operation_id”:“snkrUPcGyEeOXfgHDTRlYumITbabd-Ov”,“status”:“completed”,“result”:{“source_id”:“[opaque hardware reference]”,“kind”:“canvas”,“video”:true,“audio”:false,“requested_frame_rate”:12,“actual_frame_rate”:12,“width”:64,“height”:32,“note”:“Canvas frames may be throttled when the notebook is in the background.”}}
Use &stop_source only on the exact canvas source ID verified in the previous status. Report its immediate stop operation ID/state.
Use &operation_status on the preceding canvas stop_source operation ID. Confirm the canvas source actually stopped before continuing to region capture or release; if still active, stop and retry later.
Run the next disposable cell now. Keep its small PNG output visible beside the AI question that follows; the earlier direct-example raster is farther up the notebook.
display(Image(data=PNG_BYTES))
After running the adjacent region-ai-raster code cell, keep its 8×8 output fully visible while asking this question. Use &capture_notebook_region with cell_ids=["region-ai-raster"] and save_to=None. Report only the immediate operation ID/state; do not capture other content or target the earlier direct-example raster.
Use &operation_status on the prior region-capture operation ID after completion. Report actual dimensions and managed media ID, or a concrete visibility error, without inventing pixels.
Region capture completed: 8 × 8 pixels. Managed media ID: 7z8mBc-y4phUfJ5XNdVoSCyal_Xvoyik.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Use &release_media only on exact managed media IDs reported by completed AI export, canvas capture/export, and region-capture statuses above. Report each release operation ID/state. Skip missing IDs rather than guessing. Saved notebook displays remain visible.
All four releases succeeded:
Raster: 2g3sYVZ4cRGBnNzRDMI6D6Y9p0QFj4rY — released
Canvas capture: 3krOkauOhrGvxVFR9cxxioCzVvfEiXj4 — released
Canvas export: aGT5q7GbuiO1frLhjSEGykGojzXMm6wq — released
Region capture: Y1WqyIQdOa7EYVS-SZpoDZvlFdU0E7zv — released
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
After the release rows finish, use &operation_status on each exact release operation ID from the prior answer. Report actual terminal states; do not claim release from initial snapshots.
All four releases completed with released: true: raster, canvas capture, canvas export, and region capture.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
The first selection example above returned an empty result. Run the next call cell, then during its five-second preparation interval click the selection-normal-target editor and select its entire SELECT_ME = "blue square" line. Keep that editor focused until the call returns. Start the call before selecting because running a cell can change editor focus. The delay gives you time to make an ordinary JupyterLab selection; it does not wait for a browser receipt. If you miss the interval, rerun the call and select again.
SELECT_ME ="blue square"
import asyncio
await asyncio.sleep(5) # Select the SELECT_ME line in selection-normal-target now.
selected_text = read_selection(max_chars=120)
selected_text
print("Selected text:", selected_text.status, selected_text.result, selected_text.error)
if selected_text.status =="completed":
assert selected_text.result["cell_id"] =="selection-normal-target"assert selected_text.result["text"] =='SELECT_ME = "blue square"', "Rerun the call, then select the line during its preparation interval."
Run the next small fixture once. Start the AI question below it, then promptly click its editor and select selected blue square while the tool request is pending. Keep the selection focused until the tool reports an operation ID. The model must report the actual result from the later status question, not copy these words from notebook source. If it reads an empty selection, retry with the editor focused.
AI_SELECTION_EXAMPLE ="selected blue square"
Use &read_selection with max_chars=120 for the text I select in the selection-ai-target editor immediately after starting this question. Report the immediate operation ID and state only; do not infer selected text from the fixture source.
Use &operation_status on the preceding read_selection operation ID. If completed, quote its actual cell_id and selected text. If it is still running or empty, report that state honestly so I can retry with the editor focused.
Cell selection-ai-target: “selected blue square”.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
{“operation_id”:“zqqFIo_hmJ2AhqFvgAT06LUGwB8ZQdXU”,“status”:“completed”,“result”:{“cell_id”:“selection-ai-target”,“text”:“selected blue square”,“truncated”:false}}