Tools · practice
Look Up a Function by Name
A tool call names a function with a string: "read_note". Your program has to get from that string to the function read_note and call it. This lesson does that with a dictionary, and reads the three supplied tool functions on the way.
A function is a value
In Python, a function’s name refers to a value, just as count = 3 makes count refer to 3. Without parentheses, read_note is the function itself. With parentheses, read_note(...) calls it and gives you its result. Because the function is a value, you can store it in a dictionary and call it later through the dictionary:
def shout(arguments):
return arguments["text"].upper() + "!"
def whisper(arguments):
return arguments["text"].lower() + "..."
actions = {"shout": shout, "whisper": whisper}
name = "whisper"
function = actions[name]
print(function({"text": "Hello"}))
print(actions["shout"]({"text": "Hello"}))
actions[name] looks up the function, and the parentheses after it call the function with one argument. The last line does both in one expression. This is how a program can call a function whose name it only learns while running, such as from a model’s reply.
Leave the parentheses out when you build the dictionary. {"shout": shout()} would call shout right there, with no argument, and fail with TypeError. Even for a function that needs no arguments, the dictionary would then hold its result, a string, and there would be nothing left to call.
The tool functions
Now read the three finished functions at the top of tools.py.
def note_ids():
ids = []
for path in NOTES_DIR.glob("*.md"):
ids.append(path.stem)
ids.sort()
return ids
NOTES_DIR is Path("notes"), the notes folder as a pathlib path. NOTES_DIR.glob("*.md") gives a path for every file in it whose name ends in .md, and path.stem is the file name without the folder and the extension: 03-lists for notes/03-lists.md. The ids are sorted because glob promises no order. note_ids is a helper, not a tool: the model never asks for it by name.
def list_notes(arguments):
return "\n".join(note_ids())
list_notes is the first tool. It returns the ids as one string, one per line, because a tool’s result goes back to the model as text. It takes an argument it never uses, arguments, because every tool function in this chapter has the same shape: one argument, the decoded arguments dictionary, and a string result. That is what lets one line of code call any of them.
def read_note(arguments):
note_id = arguments.get("note_id")
if not isinstance(note_id, str):
raise ValueError("read_note needs a note_id string, such as 03-lists.")
if note_id not in note_ids():
raise ValueError(f"There is no note called {note_id}. Call list_notes to see the ids.")
with open(NOTES_DIR / f"{note_id}.md", "r", encoding="utf-8") as handle:
return handle.read()
read_note reads note_id with .get, so a missing key gives None instead of KeyError, and checks that it is a string. Then it checks the id against the real list of notes before it opens anything. NOTES_DIR / f"{note_id}.md" joins the folder and the file name into one path, notes/03-lists.md, and the file is read as UTF-8, as in Python in Practice.
That second check matters because of who wrote the id. The model did, not you, and a model can write any text. Without the check, read_note would open NOTES_DIR / f"{note_id}.md" for whatever it was given, and "../MODEL_SERVICE" would become notes/../MODEL_SERVICE.md, which is MODEL_SERVICE.md in your workspace folder, outside the notes folder. The .md on the end limits which files a model can reach this way, but not which folders: more ../ climbs higher. Matching against note_ids() means the only files read_note can open are the notes themselves. In general, a tool should never build a file path, a command or a query out of model text it has not checked against what is allowed.
Both checks raise ValueError with a message written for the model to read. In Lesson 6 those messages go back to the model instead of stopping your program.
Fill in TOOLS and build run_tool
In tools.py, replace the line TOOLS = {} with a dictionary that maps each tool’s name to its function:
TOOLS = {"list_notes": list_notes, "read_note": read_note}
The keys are the names from your descriptions, because those are the names the model writes. TOOLS comes after the three functions in the file, so the names exist when Python builds the dictionary.
Then build run_tool(call, tools). It takes one call dictionary from read_tool_calls, and a dictionary like TOOLS:
Decode the arguments with
json.loads(call["arguments"]).Look up the function with
tools[call["name"]].Call it once with the decoded dictionary, and return what it returns.
Use the tools parameter, not the global TOOLS. The project passes TOOLS, but the checks pass dictionaries of their own, and Chapter 7 passes different tools for different jobs.
This run_tool trusts the model completely. An unknown name raises KeyError, arguments that are not JSON raise an error from json.loads, and a missing note raises the ValueError from read_note. Lesson 6 fixes all of that.
Run it
Run python tools.py. The demonstration passes the two calls from Lesson 3 to your run_tool: first the list_notes call, then the read_note call, whose result is long, so it prints only the length and the first seven characters:
Running the calls:
01-variables
02-strings
03-lists
04-loops
05-functions
06-dictionaries
07-errors
08-files
09-modules
10-classes
11-comprehensions
12-testing
read_note returned 1226 characters. They start with: # Lists
Sending the result back:
Run stopped at the next function to build: assistant_turn is built in Lesson 5.
The model asked, and your program ran the function. The model has not seen either result yet. That is the next lesson.
What goes wrong with TOOLS = {"list_notes": list_notes(), "read_note": read_note}?
Why does read_note check note_id against note_ids() before it opens a file?
Why does list_notes take an arguments parameter it never uses?
Task
In tools.py:
Replace
TOOLS = {}with a dictionary that maps"list_notes"to the functionlist_notesand"read_note"to the functionread_note. Store the functions themselves, with no parentheses.Replace the unfinished body of
run_tool(call, tools): decodecall["arguments"]withjson.loads, look uptools[call["name"]], call that function once with the decoded dictionary, and return its result.
Use the tools parameter inside run_tool, not the global TOOLS. This version does not need to handle bad calls yet; Lesson 6 does that. Run python tools.py to see your program run the model’s calls, then check your work.