Live values and Python tools

This notebook shows the difference between reading a live variable and letting AI call a Python function. The worked answers show one run; choose your own provider and model in Configure AI to try the questions again. No API key is saved here.

Live values and Python tools

This notebook shows the difference between reading a live variable and letting AI call a Python function. The worked answers show one run; choose your own provider and model in Configure AI to try the questions again. No API key is saved here.

Run the setup cells in order, then run each AI Prompt with Shift+Enter. Normal Run All Cells also runs them in order, but can make provider calls and repeat a tool side effect if you turn Keep AI answers off. The notebook starts with Keep on. The first code cell resets the demonstration state whenever it runs.

sample_values: list[int] = [3, 7, 8]
tool_state: dict[str, int] = {"calls": 0, "bonus": 0}


def record_bonus(
    points: int,  # Points to add to the running bonus.
) -> int:  # Updated bonus stored in this kernel.
    """Record one bonus call in the live kernel and return its new total."""
    tool_state["calls"] += 1
    tool_state["bonus"] += points
    return tool_state["bonus"]


def average_score(
    values: list[int],  # Nonempty values to average.
) -> float:  # Arithmetic mean of the values.
    """Calculate the arithmetic mean without changing kernel state."""
    return sum(values) / len(values)


sample_values, tool_state
([3, 7, 8], {'calls': 0, 'bonus': 0})

Declare tools once above the questions

The next ordinary code cell prints & references for the custom functions in this kernel. Put only the functions you want to offer in the ordinary Markdown declaration below. Both lower AI questions inherit those declarations; they do not need repeated & names. A lower question can call a declared function only while the Python kernel still has its definition. The $ form works differently. Put $sample_values` in each question that needs its live value.

available_tool_names: list[str] = ["record_bonus", "average_score"]
selected_tool_names: list[str] = ["record_bonus", "average_score"]
selected_references: str = " ".join(f"&`{name}`" for name in selected_tool_names)
all_references: str = " ".join(f"&`{name}`" for name in available_tool_names)

print(f"Selected tools: {selected_references}")
print(f"All tools: {all_references}")
print("Live variable: $`sample_values`")
Selected tools: &`record_bonus` &`average_score`
All tools: &`record_bonus` &`average_score`
Live variable: $`sample_values`

Tools offered to the questions below

  • &record_bonus: add points to the live bonus counter.
  • &average_score: calculate the mean of a list.

A tool that changes the kernel

The declaration above offers record_bonus to lower AI questions. The next question asks for exactly one call without repeating its & reference. A declaration permits a call; the model may still choose not to call it. Watch the live state in the following code cell to see what actually happened.

Read the live list $sample_values. Use the available record_bonus function exactly once with points=4. State the returned bonus and tell me how the next code cell can confirm whether the call changed this kernel.

record_bonus(points=4) returned 4. The next code cell can inspect tool_state: calls should be 1 and bonus should be 4, confirming the call changed this kernel.

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

Tool Result state Submitted arguments Observed result
record_bonus completed {“points”:4} 4
print(f"Tool calls observed: {tool_state['calls']}")
print(f"Bonus now in the Python kernel: {tool_state['bonus']}")
if tool_state["calls"] == 0:
    print("No function call occurred. Try revising the AI prompt if you want to see one.")
Tool calls observed: 1
Bonus now in the Python kernel: 4

A different tool in a later question

The declaration above also offers average_score to this lower question. Neither function name needs repeating here. Ask for the one you need and check what the AI actually called. If you want to remove a tool from later questions, delete its line from the declaration or place the question in a different notebook. Keep answer protects completed answers from accidental replay of a state-changing call.

Use the available average_score function with values equal to the live $sample_values. Report the mean in one sentence. Do not change kernel state.

The mean of [3, 7, 8] is 6.0.

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

Tool Result state Submitted arguments Observed result
average_score completed {“values”:[3,7,8]} 6.0

Try an edit

Change sample_values in the setup cell and run that cell again. Then turn off Keep answer on the second prompt and rerun it to see a fresh live value. The existing paired answer is replaced. To keep an answer, leave its effective Keep setting on. Remember that rerunning the setup cell resets tool_state.

Optional: add a declaration from Python

In JupyterLab, run the next code cell by itself to insert an editable ordinary Markdown tool declaration immediately below it. The helper makes no AI request. Wait until the insertion finishes, then run the later inspection cell and compare the new record_bonus declaration with the manual one above. Save the notebook if you want to keep the inserted cell; delete either note when finished. The Python helper needs the live JupyterLab extension, so headless execution skips these two UI cells.

from nbinlineai.tools import insert_tools

receipt = insert_tools(["record_bonus"], custom={"record_bonus": record_bonus})
receipt
InsertToolsReceipt(requested; wait for the new Markdown cell, then save the notebook)

Available tools (delete any line you do not want to offer):

  • &record_bonus — Record one bonus call in the live kernel and return its new total.
print(receipt.status, receipt.cell_id, receipt.error)
assert receipt.status == "inserted", "Wait for insertion, then rerun this cell."
assert receipt.cell_id, "The inserted declaration needs a stable cell ID."
inserted 4ce8d799-09fb-49d8-aa6a-e0a8098f7094 None

Optional: insert a tool catalog group

Run the next cell by itself in JupyterLab to put an editable Markdown declaration immediately below it. The code group contains nine tools; change the group to notebook, web, or another name from tool_catalog(). With no argument, insert_tool_catalog() uses the 19-tool starter group. Importing the toolbox makes its names available in this kernel; the inserted references choose which ones later questions can call. Delete unwanted lines and save the notebook.

Run the receipt inspection cell separately after the note appears. This setup makes no model request.

from nbinlineai.tools import *

catalog_receipt = insert_tool_catalog(group="code")
catalog_receipt
InsertToolsReceipt(requested; wait for the new Markdown cell, then save the notebook)

Available tools (delete any line you do not want to offer):

  • &search_files — Search saved project text with bounded results and file filters.
  • &search_notebooks — Search saved notebook cell source; include stable saved cell IDs.
  • &source_doc — Read Python source documentation statically, without importing the file.
  • &source_files — Find nearby Python source files for a live symbol or imported module.
  • &view_file — Read a bounded range of one UTF-8 text file with one-based line numbers.
  • &view_file_hashes — Show numbered lines and the SHA-256 digest for a saved text file.
  • &file_replace_checked — Replace one literal only when the whole file has the expected SHA-256.
  • &inspect_python — Inspect a live Python name’s help, signature, or available source.
  • &show_doc — Show docs for a live name, or import module and inspect its public name.
print(catalog_receipt.status, catalog_receipt.cell_id, catalog_receipt.error)
assert catalog_receipt.status == "inserted", "Wait for the note, then rerun this cell."
assert catalog_receipt.cell_id
inserted 58d1d88c-bc7d-41ec-b39c-7fe526aacca0 None

← Examples guide · Download this notebook