while True: reply = model(messages, tools) calls = [b for b in reply if b.type == "tool_use"] if not calls: # plain text, no tool call: the job is done return reply.text messages += [reply, run_all(calls)]