Knaph

Giving It Tools11 of 37

The Tool Dispatcher

In [Running a Tool Call](running-a-tool-call) you saw how a harness answers the model's tool calls. Here you'll write that part yourself, the way mini does it, and the tests will check every rule from the lesson. There's no model here and no internet: the program is given the content of one assistant message, as the model would have written it, and prints the user message your harness would send back. That's the honest truth about harness code: it's ordinary code, and you can test it without a model. ## The input The content of one assistant message, as JSON: a list of blocks. Some are tool_use blocks, some may be text or thinking: ``json [ {"type": "text", "text": "Let me add those."}, {"type": "tool_use", "id": "toolu_01", "name": "add", "input": {"a": 2, "b": 3}} ] ` In the real SDK the blocks are objects (block.name); here they are plain dictionaries (block["name"]), with the same fields. ## The tools The starter code already has three tools in a table, each with the names of its inputs: - add(a, b) adds two numbers; - word_count(text) counts the words in a text; - read_note(name) returns one of two notes, shopping or todo, and raises an error for any other name. ## What to write **run_tool(block)** takes one tool_use block and returns its tool_result block: - "type": "tool_result" and "tool_use_id", the block's id, in every result; - if there is no tool with that name: "content": "Error: no tool called <name>" and "is_error": true; - if an input is missing: "content": "Error: missing input <input>", naming the first missing one in the order the table lists them, and "is_error": true; - if the tool raises an error: "content": "Error: <the error's message>" (that's str(error)) and "is_error": true; - otherwise "content" is str() of what the tool returned, with no is_error key. **results_message(content)** returns the user message that answers every tool_use block in the content, in order: {"role": "user", "content": [...results...]}. It skips text and thinking blocks, and returns None if there are no tool calls at all. For the example above, the program prints: `json { "content": [ { "content": "5", "tool_use_id": "toolu_01", "type": "tool_result" } ], "role": "user" } ` (The keys come out in alphabetical order because the printing code sorts them, so you don't have to.) Hint: function(**args) calls a function with a dictionary as its named arguments, and try / except Exception as error` catches whatever a tool raises.

Sign in to try this exercise.