From notebook output to an AI image question

Run this scenario cell by cell in a disposable JupyterLab project. The setup uses the owned runner’s NBINLINEAI_WORKED_ROOT when set, or 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 Python kernel and selected ChatGPT connection.

From notebook output to an AI image question

Run this scenario cell by cell in a disposable JupyterLab project. The setup uses the owned runner’s NBINLINEAI_WORKED_ROOT when set, or 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 Python kernel and selected ChatGPT connection.

A generated red output is exported, previewed, cropped, optionally saved, and attached to one question only after you click Attach image. The preflight question checks that no image was sent before that click. The saved worked run records a confirmed attachment and a final answer of red for the four-pixel image. After each browser operation finishes, inspect its receipt. Confirm your current image, then run the final question to repeat the example.

Make a disposable notebook output

from io import BytesIO
import hashlib
import os
from pathlib import Path, PurePosixPath
from PIL import Image as PILImage
from IPython.display import display, Image
from nbinlineai.tools import (list_outputs, export_output, open_media, close_media, crop_image, save_media, attach_media, release_media, operation_status)
root_text = os.environ.get('NBINLINEAI_WORKED_ROOT') or input('Absolute Jupyter server root (the folder served by JupyterLab): ').strip()
root_choice = Path(root_text).expanduser()
if not root_choice.is_absolute():
    raise ValueError('Enter an absolute Jupyter server-root folder; do not use the kernel working directory as a guess.')
server_root = root_choice.resolve(strict=True)
if not server_root.is_dir() or not Path.cwd().resolve().is_relative_to(server_root):
    raise ValueError('The server root must be an existing folder containing this kernel working directory.')

def server_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()

def server_file(reference):
    """Map a server-returned relative path to the configured local root."""
    if not isinstance(reference, str) or not reference or '\\' in reference:
        raise ValueError('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:
        raise ValueError('Media path must be a clean server-root-relative path.')
    candidate = server_root / reference
    if not candidate.resolve().is_relative_to(server_root):
        raise ValueError('Media path escapes the configured server root.')
    return candidate
source_image = PILImage.new('RGB', (8, 8), (212, 64, 47))
encoded = BytesIO(); source_image.save(encoded, format='PNG')
PNG_BYTES = encoded.getvalue()
print('Disposable 8x8 output image ready; no file saved.')
Disposable 8x8 output image ready; no file saved.
display(Image(data=PNG_BYTES))

Export the existing output

Run the list call, then its inspection cell after the browser answers. Export its exact output ID and revision into owned memory. Neither step reruns the image cell or creates a file.

listing = list_outputs('integration-output')
listing
BrowserReceipt(operation_id=None, status='running')
current_list_operation_id = listing.operation_id
print(listing.status, listing.error)
output_ref = listing.result['outputs'][0] if listing.status == 'completed' else None
print('Output reference:', {key: output_ref.get(key) for key in ('cell_id', 'output_id', 'revision', 'mime_types')} if output_ref else None)
completed None
Output reference: {'cell_id': 'integration-output', 'output_id': '3aad0bd3a931be2de51d15fef1f04aa3', 'revision': 0, 'mime_types': ['image/png', 'text/plain']}

Use &list_outputs for cell ID integration-output. Report only its immediate operation ID/state; do not invent an output ID or MIME type before the later status question.

Operation LNxZ4RV2bqn9Wejw4kgP56QrC_Yqp7I8: running.

Observed live tool calls for the answer above (actual subscription events; private fields shortened).

Tool Result state Submitted arguments Observed result
list_outputs receipt accepted {“cell_id”:“integration-output”} {“operation_id”:“LNxZ4RV2bqn9Wejw4kgP56QrC_Yqp7I8”,“status”:“running”}

Use &operation_status on the fresh operation ID in current live $current_list_operation_id from the direct list_outputs call above. The saved AI list_outputs answer belongs to an earlier run; do not query its historical ID. Report the actual output ID, revision, and MIME type of the generated red image only if this current operation completed. Do not rerun the output cell.

The current operation completed. The red image’s output ID is 3aad0bd3a931be2de51d15fef1f04aa3, revision 0, with MIME types image/png and text/plain.

Observed live tool calls for the answer above (actual subscription events; private fields shortened).

Tool Result state Submitted arguments Observed result
operation_status completed {“operation_id”:“YC4qTIKwUfOC0dVrSBsnRt0YKT4cfFQL”} {“operation_id”:“YC4qTIKwUfOC0dVrSBsnRt0YKT4cfFQL”,“status”:“completed”,“result”:{“outputs”:[{“cell_id”:“integration-output”,“output_id”:“3aad0bd3a931be2de51d15fef1f04aa3”,“revision”:0,“mime_types”:[“image/png”,“text/plain”],“output_type”:“display_data”}],“next_cursor”:null}}
assert output_ref, 'Wait for list_outputs and rerun its inspection cell.'
exported = export_output(output_ref['cell_id'], output_ref['output_id'], output_ref['revision'])
exported
BrowserReceipt(operation_id=None, status='running')
print(exported.status, exported.error)
if exported.status == 'completed':
    assert exported.result.size == (8, 8)
    assert exported.result.getpixel((0, 0))[:3] == (212, 64, 47)
    print('Exported memory hash:', exported.media['sha256'])
    exported_media_ref = exported.media
completed None
Exported memory hash: 269661e8dbcb389941d2a1c41323776fac18a1ee3a08e9582a6c485291b53a88

Preview the exported memory image

Opening a preview does not change the output or attach it to a question. Inspect its receipt in a later cell.

assert exported.status == 'completed', 'Wait for export_output first.'
preview = open_media(exported.media)
preview
BrowserReceipt(operation_id=None, status='running')
print(preview.status, preview.result, preview.error)
completed {'preview_id': 'a9e08cdf75dcb1ec306d6003f2f78a56', 'kind': 'image', 'width': 8, 'height': 8} None

Make a new four-pixel-square derivative

The crop remains in owned memory and leaves the eight-pixel source unchanged. The later inspection checks actual decoded pixels and reports the exact encoded PNG hash.

crop = crop_image(exported.media, 0, 0, 4, 4)
crop
BrowserReceipt(operation_id=None, status='running')
print(crop.status, crop.error)
if crop.status == 'completed':
    assert crop.result.size == (4, 4)
    assert crop.result.getpixel((0, 0))[:3] == (212, 64, 47)
    assert exported.result.size == (8, 8)
    print('Derivative memory hash:', crop.media['sha256'])
    crop_media_ref = crop.media
    display(crop.result.resize((80, 80)))
completed None
Derivative memory hash: b8927261e3dc400dae17dced7b23227990528469c73c3546d89a8f20d53d88af

Save the derivative as a separate file

This call writes a new server-root-relative PNG and keeps the in-memory derivative for the question. Its later cleanup removes only the generated saved path.

assert crop.status == 'completed', 'Wait for crop_image first.'
saved = save_media(crop.media, save_to='auto')
saved
BrowserReceipt(operation_id=None, status='running')
print(saved.status, saved.media, saved.error)
if saved.status == 'completed':
    assert saved.media['sha256'] == crop.media['sha256']
    assert hashlib.sha256(server_file(saved.media['path']).read_bytes()).hexdigest() == crop.media['sha256']
    import json
    sidecar_path = server_file(saved.media['sidecar_path'])
    assert sidecar_path.is_file()
    provenance = json.loads(sidecar_path.read_text())
    assert provenance['transform'] == 'crop_image'
    assert provenance['source_sha256'] == exported.media['sha256']
    assert provenance['output_sha256'] == crop.media['sha256']
    assert provenance['parameters'] == {'x': 0, 'y': 0, 'width': 4, 'height': 4}
    print('Saved path:', saved.media['path'])
    print('Sidecar path:', saved.media['sidecar_path'])
completed {'media_id': 'vYGhNxRvWWMgPnEaB7mwGapJrDl_uRXr', 'mime_type': 'image/png', 'bytes': 109, 'sha256': 'b8927261e3dc400dae17dced7b23227990528469c73c3546d89a8f20d53d88af', 'expires_at': 1792592237.895382, 'source_sha256': '269661e8dbcb389941d2a1c41323776fac18a1ee3a08e9582a6c485291b53a88', 'transform': 'crop_image', 'width': 4, 'height': 4, 'sidecar_path': 'media/capture-d8667b111da314d5.png.json', 'path': 'media/capture-d8667b111da314d5.png'} None
Saved path: media/capture-d8667b111da314d5.png
Sidecar path: media/capture-d8667b111da314d5.png.json

Ask without an attachment

Run this question with the selected ChatGPT connection before the attachment step. The generated output and preview alone do not send a native image to the model.

Before I confirm any image attachment, do you receive a native image from this notebook? Answer briefly.

No. I don’t receive a native image until you explicitly attach it.

Confirm only the derivative for the next question

Run the call, click Attach image in the visible confirmation, then rerun the inspection cell until the receipt is complete. Confirmation changes only the identified question; it never runs it.

assert crop.status == 'completed', 'Wait for the crop first.'
attached = attach_media(crop.media, 'integration-question', detail='auto')
attached
BrowserReceipt(operation_id=None, status='running')
print(attached.status, attached.result, attached.error)
completed {'confirmed': True, 'question_cell_id': 'integration-question', 'image_sha256': 'b8927261e3dc400dae17dced7b23227990528469c73c3546d89a8f20d53d88af', 'detail': 'auto'} None

Confirm, then ask about the image

The saved answer below came from a confirmed attachment in the worked run. To repeat it, confirm your current four-pixel crop, check its indicator in context preview, then run this question with the selected ChatGPT connection. The model receives the crop as a native image item rather than base64 in tool text.

What is the visible color in the four-pixel-square image I explicitly attached?

Red.

Clean up owned memory and optional file

Run after the question. The first cell closes the preview and releases managed bytes. The final cell removes only this example’s generated saved path, if the optional save ran.

closed_preview = close_media(preview.result['preview_id']) if preview.status == 'completed' else None
released_export = release_media(exported.media['media_id']) if exported.status == 'completed' else None
released_crop = release_media(crop.media['media_id']) if crop.status == 'completed' else None
print('Cleanup requested; inspect the receipts later.')
Cleanup requested; inspect the receipts later.
print('Preview:', closed_preview.status if closed_preview else 'none')
print('Export:', released_export.status if released_export else 'none')
print('Crop:', released_crop.status if released_crop else 'none')
Preview: completed
Export: completed
Crop: completed
if 'saved' in globals() and saved.status == 'completed':
    saved_path = server_file(saved.media['path'])
    assert saved_path.is_file()
    assert hashlib.sha256(saved_path.read_bytes()).hexdigest() == saved.media['sha256']
    sidecar_path = server_file(saved.media['sidecar_path'])
    assert sidecar_path.is_file()
    saved_path.unlink()
    sidecar_path.unlink()
    print('Optional generated file and sidecar removed:', not saved_path.exists() and not sidecar_path.exists())
else:
    print('No optional file was saved.')
Optional generated file and sidecar removed: True

← Examples guide · Download this notebook