AlgoMaster Logo

Exercise: Structured Workflows with Tool Use

4 min readUpdated June 22, 2026
Listen to this chapter
Unlock Audio

Exercise 1: Run a Multi-Step Tool Workflow

Drive a workflow where the model uses tools across several turns to reach an answer, with each tool result feeding the next decision. Run the call loop until the model stops requesting tools.

A single tool call answers a single question. Real tasks often need a chain: look something up, use that result to look up something else, then combine them. Instead of hand-coding the sequence, you let the model decide which tool to call next based on what it has learned so far, and you keep running the loop until it is done.

Requirements

  • Provide two tools, for example get_population and get_country (which country a city is in).
  • Ask a question that needs both, such as the population of the country a city is in.
  • Loop: call the model, run any tool it requests, append the result, and repeat until the model returns a final answer with no tool call.
  • Print each tool call and the final answer.
main.py
Loading...

Expected Output

The model chains the two tools: first the country, then that country's population.

Solution

main.py
Loading...

The loop is the difference between a single tool call and a workflow. Each pass appends the assistant's tool request and the tool's result to the message history, so the next call sees everything learned so far and can decide the next step. The model sequences the tools itself: it cannot ask for the population until it has the country, so it requests the country first. The turn limit is a small but important safeguard, since a model that keeps requesting tools would otherwise never return.

Exercise 2: Recover from a Tool Error

Tools fail: bad arguments, unknown values, transient errors. A robust workflow returns the error to the model as a tool result and lets it correct itself, rather than crashing. Build a currency converter that rejects unknown codes, and let the model recover when it guesses wrong.

Requirements

  • Provide a convert tool that returns an error string for an unknown currency.
  • Loop: call the model, run the tool, and append the result (error or success).
  • When the result is an error, the model should retry with a valid code on the next turn. Print the final answer.
main.py
Loading...

Expected Output

If the model first guesses a wrong currency code, the error feeds back and it retries with GBP, then answers.

Solution

main.py
Loading...

Returning the error as an ordinary tool result, rather than raising an exception, keeps the loop alive and gives the model the information it needs to fix its call. A descriptive error (listing valid currencies) is what lets the model recover on the next turn instead of guessing again. This error-as-feedback pattern is what makes tool-using workflows resilient: the loop already re-prompts the model, so a well-written error message turns a failure into a self-correction.