Start learning free

LESSON 49 OF 129 · AI ENGINEERING: TOOL USE

Log Every Tool Call in Python

Practice

This conversation takes three rounds: the model finds the customer's orders, asks for a refund tool it doesn't have, and then starts two returns. Tomorrow the customer asks "why did it do that?", and the lines printed on your screen are gone. An audit log is a file that keeps one line for every tool call: in which round, which tool, with what input, and how it ended.

The usual format is JSON Lines (.jsonl): one JSON object per line. You open the file with the mode "a", which appends: each write goes to the end of the file and what is already there stays. Here a website logs the pages people visit:

visit = {"page": "/cart", "user": 3}
with open("visits.jsonl", "a") as visits_file:
    visits_file.write(json.dumps(visit) + "\n")

json.dumps turns the dictionary into text, and "\n" ends the line: write adds no line break by itself. To show the file, open it again with no mode (reading is the default) and print visits_file.read() with end="", because the last line already ends with a line break.

Your log must also hold the calls your code refuses: they are the ones you most want to know about later. After the conversation, your program must print:

Rounds: 3
Answer: I can't send refunds myself, but I've started the return of order 7, and the shop's team refunds you when it arrives. Order 4 is 53 days old, and returns are accepted for 30 days, so I couldn't start that one.
Audit log:
{"round": 1, "tool": "find_orders", "input": {"email": "chloe@example.com"}, "status": "ok"}
{"round": 2, "tool": "issue_refund", "input": {"amount": 89, "order_ids": [4, 7]}, "status": "error"}
{"round": 3, "tool": "start_return", "input": {"order_id": 4}, "status": "error"}
{"round": 3, "tool": "start_return", "input": {"order_id": 7}, "status": "ok"}

Your task: write the function log_tool_call(round_number, name, tool_input, is_error), which builds an entry with the keys "round", "tool", "input" and "status" ("ok" or "error") and appends it to tool_log.jsonl as one line of JSON. Call it in run_tools for every tool that runs and for every tool you refuse, and print the title "Audit log:" and the file at the end of the program.


Assignment
Follow the Coding Tutorial to write every tool call to tool_log.jsonl and print the audit log at the end.


Hint
The round number is rounds, the counter of the loop at the bottom. A refused tool never reaches the line below is_error = "error" in result, because continue skips it: it needs its own call to log_tool_call, with True as the last argument.


STEP 1 OF 11
    Ctrl + Enter to check

    Ai Log Tool Calls in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free