Python documentation and text-file tools

This lesson compares direct Python calls with AI tool use on a small disposable text file. Run setup first. The file lives in a temporary directory separate from the notebook; this example supplies its explicit path.

Python documentation and text-file tools

This lesson compares direct Python calls with AI tool use on a small disposable text file. Run setup first. The file lives in a temporary directory separate from the notebook; this example supplies its explicit path.

Direct calls need no AI connection. Connect ChatGPT or an API provider before the AI questions. A kept completed answer avoids repeating its edit; cancellation does not undo an edit that has already completed. Review the saved file in the final code cell.

from pathlib import Path
from tempfile import TemporaryDirectory
from nbinlineai.fastcore_tools import (
    show_doc, path_info, list_files, view_file, create_file,
    file_str_replace, file_insert_line, file_replace_lines,
)
from nbinlineai.tools import tools_markdown

study_workspace = TemporaryDirectory(prefix="nbinlineai-lesson-")
study_folder = study_workspace.name
study_path = Path(study_folder) / "study-note.txt"
create_file(str(study_path), "Status: planned\nTopic: pollinator visits\n")
print("A disposable study-note.txt is ready.")

def lesson_rate(
    visits: int,  # Number of observed visits.
    flowers: int = 10,  # Number of flowers observed.
) -> float:  # Visits per flower.
    """Calculate the visit rate for a small field observation."""
    return visits / flowers
A disposable study-note.txt is ready.

Formatted documentation

Run the next cell to see a signature with the parameter and return descriptions from fastcore-style comments. The documented function is not called. The same result is returned as Markdown text when an AI calls the tool.

show_doc("lesson_rate")

lesson_rate

def lesson_rate(
    visits:int, # Number of observed visits.
    flowers:int=10, # Number of flowers observed.
)->float: # Visits per flower.

Calculate the visit rate for a small field observation.

def compare_visits(first: int, second: int) -> int:
    """Compare two observations.

    Parameters
    ----------
    first : int
        Visits in the first observation.
    second : int
        Visits in the second observation.

    Returns
    -------
    int
        The difference between the observations.
    """
    return first - second

show_doc("compare_visits")

compare_visits

def compare_visits(
    first:int, # Visits in the first observation.
    second:int, # Visits in the second observation.
)->int: # The difference between the observations.

Compare two observations.

The next call imports the installed json module and documents dumps. To read module-level docs, use show_doc("", module="json"). Imports execute module initialization; the tool does not install a package or run the documented function. A Python module name is not a filesystem path.

show_doc("dumps", module="json")

dumps

def dumps(
    obj, *, skipkeys:bool=False, ensure_ascii:bool=True, check_circular:bool=True, allow_nan:bool=True,
    cls:NoneType=None, indent:NoneType=None, separators:NoneType=None, default:NoneType=None, sort_keys:bool=False,
    **kw
):

Serialize obj to a JSON formatted str.

If skipkeys is true then dict keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If ensure_ascii is false, then the return value can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an RecursionError (or worse).

If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.

To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

Tools offered to the questions below

Remove a line to stop offering that tool, or disable Tools on this cell.

  • &show_doc: Show formatted Python or module documentation.
  • &path_info: Describe a filesystem path and the kernel working directory.
  • &list_files: List matching files in an explicit directory.
  • &view_file: Read a numbered text-file excerpt.
  • &create_file: Create a new file without overwriting one.
  • &file_str_replace: Replace literal text after checking its occurrence count.
  • &file_insert_line: Insert after a line; line 0 inserts at the beginning.
  • &file_replace_lines: Replace an explicit inclusive line range.

Use show_doc to explain lesson_rate, including what each parameter means. Do not run the function.

lesson_rate(visits, flowers=10) -> float calculates visits per flower. visits is the number of observed visits; flowers is the number of flowers observed and defaults to 10. The function was not run.

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

Tool Result state Submitted arguments Observed result
show_doc completed {“name”:“lesson_rate”} ‘### lesson_rate\n\npython\ndef lesson_rate(\n visits:int, # Number of observed visits.\n flowers:int=10, # Number of flowers observed.\n)->float: # Visits per flower.\n\n\nCalculate the visit rate for a small field observation.’

The disposable lesson directory is $study_folder. Use list_files to find study-note.txt, then read it with view_file. Change its status from “planned” to “reviewed” using file_str_replace with exactly one expected match. Show me the edit and explain where the change was saved.

-Status: planned
+Status: reviewed
 Topic: pollinator visits

The change was saved in `[temporary local path] the disposable lesson directory—not the notebook folder.

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

Tool Result state Submitted arguments Observed result
list_files completed {“path”:“[local path]”,“pattern”:“study-note.txt”} ‘Files under [local path]’
view_file completed {“path”:“[local path]”} ‘File: [local path] Status: planned\n2: Topic: pollinator visits’
file_str_replace completed {“path”:“[local path]”,“old_str”:“Status: planned”,“new_str”:“Status: reviewed”,“expected_matches”:1} ‘Updated: [local path] -1,2 +1,2 @@\n-Status: planned\n+Status: reviewed\n Topic: pollinator visits’

Review the saved text

Run the next cell before or after the AI question to read the current file directly. File changes are saved immediately; they are separate from saving this notebook. Rerunning setup creates a fresh disposable workspace.

For line edits, file_insert_line(path, 0, text) prepends; file_insert_line(path, 2, text) inserts after line 2. file_replace_lines(path, 1, 2, text) replaces lines 1 through 2. These tools reject notebook .ipynb writes; use the notebook’s live-cell controls for its contents.

print(view_file(str(study_path)))
File: [temporary local path]
1: Status: planned
2: Topic: pollinator visits

← Examples guide · Download this notebook