API examples

Build a phylogenetic tree with IQ-TREE

Build a maximum likelihood tree of nine primate mitochondrial genomes in Python, then read the chosen model and list every clade with its support.

Download Python example · Shared job runner · Example code license

Mitochondrial genomes are a good test for a tree builder because the answer is known. Humans and Neanderthals pair up, chimpanzees and bonobos pair up, the two pairs join before the gorilla does, and the orangutans branch off before all of them. A method that gets these apes in the wrong order on 16,000 base pairs of data has a problem, and any tree you build for unknown species deserves the same checks.

IQ-TREE recovers that tree from nine primate mitochondrial genomes in 18 seconds, after choosing its own substitution model. This example runs it from Python with the ProteinIQ SDK, then reads the two things you need from the output: which model was chosen and how decisively, and which groups the tree contains and how well each is supported.

The result

The public example job ran IQ-TREE 3.1.1 on 3 November 2026 in 18 seconds of compute. Run on its output with the rhesus macaque as the outgroup, the script prints:

Text
9 sequences, 17309 sites, nucleotide
Best-fit model (BIC): TVM+F+I+G4, log-likelihood -64507.592
  TVM+F+I+G4     logL -64507.408  BIC 129249.032  weight 0.863
  TPM2u+F+I+G4   logL -64519.658  BIC 129254.014  weight 0.0715
  GTR+F+I+G4     logL -64505.210  BIC 129254.395  weight 0.0591
Clades with SH-aLRT/UFBoot support, rooted on Rhesus_macaque:
  + (100/100)
    + (100/100)
      + (100/100)
        + (100/100)
          Bonobo
          Chimpanzee
        + (100/100)
          Human
          Neanderthal
      Gorilla
    + (100/100)
      Bornean_orangutan
      Sumatran_orangutan
  Lar_gibbon
  Rhesus_macaque

Read from the root down, that is the accepted ape tree: the great apes together, the orangutans splitting from the African apes, the gorilla outside the human and chimpanzee lineages, and humans with Neanderthals as the sister of chimpanzees with bonobos. The gibbon and the macaque sit at the base because rooting on the macaque puts them there. Every one of the six internal branches has 100% support on both tests.

ModelFinder chose TVM+F+I+G4 by the Bayesian information criterion, with a BIC weight of 0.863. GTR+F+I+G4 fits the data slightly better, with a log-likelihood about 2.2 units higher, and it wins on the Akaike criterion.

BIC charges more for each extra parameter on a long alignment, and GTR's one extra rate does not pay for itself. In the chosen model, both transition rates are about 34 times the G to T transversion rate, 42% of sites are estimated not to vary at all, and the rest follow a gamma distribution with shape 1.05.

Set up

You need Python 3.10 or later and version 0.2.0 or later of the ProteinIQ SDK; the SDK page covers installation. Create an API key with the jobs:write and jobs:read scopes for a workspace with API access, and set it as PROTEINIQ_API_KEY in your environment rather than in the script.

Download build_tree.py and proteiniq_job.py from the links at the top of this page into one folder. The first holds everything specific to IQ-TREE; the second is the job runner that every Python example on these pages shares. Then download the alignment the public job used:

Bash
curl -O https://proteiniq.io/data/guides/phylogenetic-tree/primate_mtdna.aln.fasta

It holds the complete NCBI RefSeq mitochondrial genomes of human (NC_012920.1), Neanderthal (NC_011137.1), chimpanzee (NC_001643.1), bonobo (NC_001644.1), gorilla (NC_011120.1), Bornean orangutan (NC_001646.1), Sumatran orangutan (NC_002083.1), lar gibbon (NC_002082.1) and rhesus macaque (NC_005943.1).

We aligned them with MAFFT 7.526 in --auto mode for the phylogenetic tree guide; the genomes range from 16,389 to 16,569 base pairs and the alignment is 17,309 columns long. To align your own sequences first, MAFFT runs the same way from the API.

Building the request

IQ-TREE takes an aligned file in a slot called alignment. Before anything is sent, the script checks that the FASTA rows all have the same length, which unaligned sequences rarely are, and that there are at least four of them, the minimum for ultrafast bootstrap.

Python
def check_alignment(path: Path) -> int:
    """Count the sequences and stop early if the rows are not aligned."""
    lengths, names = {}, []
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.startswith(">"):
            names.append(line[1:].strip())
            lengths[names[-1]] = 0
        elif names:
            lengths[names[-1]] += len(line.strip())
    if len(names) < 4:
        raise ValueError("Ultrafast bootstrap needs at least 4 aligned sequences.")
    if len(set(names)) != len(names):
        raise ValueError("Sequence names must be unique.")
    if len(set(lengths.values())) != 1:
        raise ValueError("Sequences differ in length; align them first, for example with MAFFT.")
    return len(names)

The settings match the public job and are written out so that request.json records exactly what ran. model is AUTO, which leaves IQ-TREE on its default: ModelFinder picks the model, then the same run searches for the tree. bootstrap asks for 1,000 ultrafast bootstrap (UFBoot) replicates and alrt for 1,000 SH-aLRT replicates, the two support tests whose values the tree carries. The fixed seed makes the search and the bootstrap repeatable.

Python
def make_request(alignment: Path) -> dict:
    check_alignment(alignment)
    data = proteiniq_job.file_input(alignment, "alignment", "msa", FORMATS)
    settings = {"interface": "native", "sequence_type": "auto", "model": "AUTO",
                "bootstrap": 1000, "alrt": 1000, "seed": 12345, "custom_model": "",
                "custom_sequence_type": "", "native_options": "[]"}
    return {"tool": "iq-tree", "input": {"inputs": [data]}, "settings": settings}

Quoting, submitting and resuming

proteiniq_job.py handles the parts of running a job that are the same for every tool. It prices the request before anything is charged and stops if the quote has blocking errors or exceeds your limit. IQ-TREE is billed by runtime at 4 credits per minute, so the quote is an estimate, and this script also sends your limit as the job's spending cap: if the run reaches it, IQ-TREE stops and the reserved credits are charged. It writes the request and an idempotency key to disk before submitting, so a retry after a dropped connection returns the job that already started instead of paying for a second one. Then it waits, saves the structured result to results.json and downloads each file with its SHA-256.

Python
def run(args: argparse.Namespace, client: ProteinIQ, build_request: Callable[[], dict],
        metered: bool = False) -> dict | None:
    """Quote, then submit at most one job and collect it. Returns the result once complete.

    With metered=True a runtime-billed quote is accepted, and --max-credits is sent
    with the quote and the submission as the spending cap (billing.max_reserved_credits).
    """
    output = args.output
    state_path = output / "request.json"
    workspace_id = client.account.get().workspace.get("id")
    if not workspace_id:
        raise ValueError("Account response did not identify the workspace.")
    if state_path.exists():
        if not args.resume:
            raise ValueError("This output directory already contains a request. Use --resume or a new directory.")
        state = json.loads(state_path.read_text(encoding="utf-8"))
        if state["base_url"] != client.base_url or state["workspace_id"] != workspace_id:
            raise ValueError("Resume with the same ProteinIQ server and workspace as the original request.")
        if state.get("job_id"):
            return collect(client, state, output, args.timeout)
        if not args.submit:
            raise ValueError("Retrying an unconfirmed submission also requires --submit.")
        if state.get("submission"):
            # Resend exactly what the first attempt sent, so the idempotency key
            # returns that job instead of a new quote changing the request.
            return submit_and_collect(client, state, state_path, output, args.timeout)
        request, ceiling = state["request"], state["max_credits"]
    else:
        if args.resume:
            raise ValueError("No saved request to resume.")
        request = build_request()
        ceiling = args.max_credits
        state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
                 "base_url": client.base_url, "workspace_id": workspace_id}
    spending_cap = {"billing": {"max_reserved_credits": ceiling}} if metered and ceiling and ceiling > 0 else {}
    quote = client.jobs.quote(**request, **spending_cap)
    print(json.dumps(quote.raw, indent=2))
    check_quote(quote, ceiling, metered)
    if not args.submit:
        print("Quote only. No job submitted.")
        return None
    if ceiling is None or ceiling < 1:
        raise ValueError("Submission requires a positive integer --max-credits.")
    state["submission"] = {**request, **(spending_cap if quote.billing.get("mode") != "fixed" else {}),
                           "name": args.job_name, "max_quoted_credits": ceiling}
    return submit_and_collect(client, state, state_path, output, args.timeout)

The MolProbity example walks through each of those steps in more detail. Run the script without --submit first to see the quote:

Bash
python build_tree.py --alignment primate_mtdna.aln.fasta --output primates

When the price looks right, add --submit and replace YOUR_LIMIT with the credits you approve. --outgroup only changes how the script reports the tree, not what IQ-TREE computes.

Bash
python build_tree.py --alignment primate_mtdna.aln.fasta --output primates --outgroup Rhesus_macaque --submit --max-credits YOUR_LIMIT

If the script is interrupted, run it again with --output primates --resume and it picks up the same job. The script waits an hour by default; large alignments can run for several hours, so pass a longer --timeout in seconds or resume later.

Reading the tree

The public job returned ten files: output.treefile, output.contree, output.iqtree, output.log, output.command.log, output.bionj, output.mldist, output.splits.nex, output.model.gz and output.ckp.gz. The maximum likelihood tree is in output.treefile, in Newick format:

Text
(Human:0.0073821191,Neanderthal:0.0058642194,((Chimpanzee:0.0252473683,Bonobo:0.0228822938)100/100:0.0375956248,(Gorilla:0.0808103988,((Bornean_orangutan:0.0440103298,Sumatran_orangutan:0.0408442288)100/100:0.1164703114,(Lar_gibbon:0.1693826188,Rhesus_macaque:0.4243599793)100/100:0.0481239110)100/100:0.0587211124)100/100:0.0224908626)100/100:0.0537065925);

Each pair of parentheses is a node, the number after a colon is a branch length in expected substitutions per site, and the label after a closing parenthesis is the support for the branch above that node, SH-aLRT first and UFBoot second. The parser reads the string in one pass, recursing into each pair of parentheses, and keeps names, labels and lengths separate.

Python
def parse_newick(text: str) -> dict:
    """Read a Newick string into nested nodes with name, label, length and children."""
    position = 0

    def node() -> dict:
        nonlocal position
        children = []
        if text[position] == "(":
            position += 1
            children.append(node())
            while text[position] == ",":
                position += 1
                children.append(node())
            if text[position] != ")":
                raise ValueError(f"Expected ')' at character {position}")
            position += 1
        match = re.compile(r"([^:,();]*)(?::([^,();]+))?").match(text, position)
        position = match.end()
        name = match.group(1).strip()
        return {"name": "" if children else name, "label": name if children else "",
                "length": float(match.group(2)) if match.group(2) else None, "children": children}

    text = text.strip()
    tree = node()
    if text[position:] != ";":
        raise ValueError("Newick tree must end with ';'")
    return tree

The rest of the script compares groups of tips as sets of names, which leaves collects for any node.

Python
def leaves(node: dict) -> frozenset[str]:
    if not node["children"]:
        return frozenset([node["name"]])
    return frozenset().union(*(leaves(child) for child in node["children"]))

The tree IQ-TREE writes is unrooted. Its report says so and notes that the first taxon, Human, is only drawn at the root. Read naively, that string seems to put Gorilla, the orangutans, the gibbon and the macaque in one group, which is an artifact of where the drawing starts. The real information is in the branches: each internal branch splits the nine genomes into two sets, and support values belong to those splits.

To turn splits into clades you need to know which taxon lies outside the group you care about. clades takes that outgroup and, for every internal branch, keeps the side that does not contain it. The macaque, an Old World monkey, is outside the apes on independent evidence, which is what makes it a fair choice here; rooted and unrooted trees covers the alternatives.

Python
def clades(tree: dict, outgroup: str) -> list[tuple[frozenset[str], str]]:
    """Every internal branch as the group it separates from the outgroup, with its support label."""
    taxa = leaves(tree)
    if outgroup not in taxa:
        raise ValueError(f"Outgroup {outgroup} is not in the tree")
    found, seen = [], set()

    def visit(node: dict) -> None:
        for child in node["children"]:
            if child["children"]:
                side = leaves(child)
                # An unrooted tree has no direction; take the side without the outgroup.
                group = side if outgroup not in side else taxa - side
                if 1 < len(group) < len(taxa) - 1 and group not in seen:
                    seen.add(group)
                    found.append((group, child["label"]))
                visit(child)

    visit(tree)
    return sorted(found, key=lambda item: (-len(item[0]), sorted(item[0])))

draw nests each clade under the smallest clade that contains it, which gives the indented tree in the result above. report also writes the clades to clades.csv with SH-aLRT and UFBoot in separate columns:

Python
def draw(taxa: frozenset[str], groups: list[tuple[frozenset[str], str]], depth: int = 0) -> list[str]:
    """Indent nested clades so the tree reads from the root down."""
    lines, placed = [], set()
    for group, label in groups:
        if group <= taxa and group != taxa and not group & placed:
            inner = [(g, l) for g, l in groups if g < group]
            lines.append(f"{'  ' * depth}+ ({label or 'no support'})")
            lines += draw(group, inner, depth + 1)
            placed |= group
    lines += [f"{'  ' * depth}{name}" for name in sorted(taxa - placed)]
    return lines
Text
taxa,size,sh_alrt,ufboot
Bonobo Bornean_orangutan Chimpanzee Gorilla Human Neanderthal Sumatran_orangutan,7,100,100
Bonobo Chimpanzee Gorilla Human Neanderthal,5,100,100
Bonobo Chimpanzee Human Neanderthal,4,100,100
Bonobo Chimpanzee,2,100,100
Bornean_orangutan Sumatran_orangutan,2,100,100
Human Neanderthal,2,100,100

The IQ-TREE developers advise trusting a branch when UFBoot is at least 95%, and more so when SH-aLRT is also at least 80%. Every branch here clears both bars with room to spare. That is what 17,309 columns, 3,437 of them parsimony informative, should give for splits this deep. Cut the same alignment into 1,000-column windows and some of that support starts to drop.

Reading the model choice

The structured result already holds the chosen model and the final log-likelihood. The runners-up are only in output.iqtree, in the table ModelFinder writes after scoring every candidate. The run log shows it tested up to 968 DNA models, and that step took about 13 of the 18 seconds. The script reads the first rows of that table:

Python
def model_ranking(report: Path, count: int = 3) -> list[tuple[str, float, float, float]]:
    """The first rows of ModelFinder's BIC table: model, log-likelihood, BIC and BIC weight."""
    lines = report.read_text(encoding="utf-8").splitlines()
    start = next(i for i, line in enumerate(lines) if line.startswith("List of models sorted by BIC"))
    rows = []
    for line in lines[start + 3:]:
        fields = line.split()
        if len(fields) != 11:
            break
        rows.append((fields[0], float(fields[1]), float(fields[8]), float(fields[10])))
    return rows[:count]

ModelFinder scores each candidate on a quick starting tree before the full tree search, so its log-likelihood for TVM+F+I+G4, -64507.408, differs slightly from the -64507.592 of the final tree in results.json. Compare models with the table and report the final value for the tree.

Python
def report(result: dict, output: Path, outgroup: str | None = None) -> None:
    summary = result["summary"]
    (treefile,) = proteiniq_job.output_files(output, r"\.treefile$")
    (iqtree,) = proteiniq_job.output_files(output, r"\.iqtree$")
    tree = parse_newick(treefile.read_text(encoding="utf-8"))
    taxa = leaves(tree)
    # Without an outgroup, follow IQ-TREE and put the first taxon at the root.
    first = tree
    while first["children"]:
        first = first["children"][0]
    outgroup = outgroup or first["name"]
    groups = clades(tree, outgroup)
    print(f"{summary['sequences']} sequences, {summary['sites']} sites, {summary['sequence_type']}")
    print(f"Best-fit model (BIC): {summary['model']}, log-likelihood {summary['log_likelihood']:.3f}")
    for model, log_likelihood, bic, weight in model_ranking(iqtree):
        print(f"  {model:<14} logL {log_likelihood:.3f}  BIC {bic:.3f}  weight {weight:.3g}")
    print(f"Clades with SH-aLRT/UFBoot support, rooted on {outgroup}:")
    for line in draw(taxa, groups):
        print(f"  {line}")
    with open(output / "clades.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["taxa", "size", "sh_alrt", "ufboot"])
        for group, label in groups:
            alrt, _, ufboot = label.partition("/")
            writer.writerow([" ".join(sorted(group)), len(group), alrt, ufboot])
    print(f"Clade table: {output / 'clades.csv'}")

Going further

This alignment is easy: long, clean and about closely related species. On harder data the choice of program and the support scale start to matter, and IQ-TREE vs RAxML-NG vs FastTree measures how often each program's well-supported branches are wrong.

To cross-check this tree, run the same alignment through RAxML-NG or FastTree. For proteins, build the alignment first as in the Clustal Omega example; with model left at AUTO, ModelFinder also chooses among protein models.

Complete script

Python
"""Build a maximum likelihood tree with IQ-TREE and list its clades with support.

Quotes by default. Add --submit --max-credits N to run one job. Keep the output
folder to resume. Needs proteiniq_job.py from the same page in this folder.
"""
from __future__ import annotations

import csv
from pathlib import Path
import re

import proteiniq_job

FORMATS = {".fasta": "fasta", ".fa": "fasta", ".fas": "fasta"}


def check_alignment(path: Path) -> int:
    """Count the sequences and stop early if the rows are not aligned."""
    lengths, names = {}, []
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.startswith(">"):
            names.append(line[1:].strip())
            lengths[names[-1]] = 0
        elif names:
            lengths[names[-1]] += len(line.strip())
    if len(names) < 4:
        raise ValueError("Ultrafast bootstrap needs at least 4 aligned sequences.")
    if len(set(names)) != len(names):
        raise ValueError("Sequence names must be unique.")
    if len(set(lengths.values())) != 1:
        raise ValueError("Sequences differ in length; align them first, for example with MAFFT.")
    return len(names)


def make_request(alignment: Path) -> dict:
    check_alignment(alignment)
    data = proteiniq_job.file_input(alignment, "alignment", "msa", FORMATS)
    settings = {"interface": "native", "sequence_type": "auto", "model": "AUTO",
                "bootstrap": 1000, "alrt": 1000, "seed": 12345, "custom_model": "",
                "custom_sequence_type": "", "native_options": "[]"}
    return {"tool": "iq-tree", "input": {"inputs": [data]}, "settings": settings}


def parse_newick(text: str) -> dict:
    """Read a Newick string into nested nodes with name, label, length and children."""
    position = 0

    def node() -> dict:
        nonlocal position
        children = []
        if text[position] == "(":
            position += 1
            children.append(node())
            while text[position] == ",":
                position += 1
                children.append(node())
            if text[position] != ")":
                raise ValueError(f"Expected ')' at character {position}")
            position += 1
        match = re.compile(r"([^:,();]*)(?::([^,();]+))?").match(text, position)
        position = match.end()
        name = match.group(1).strip()
        return {"name": "" if children else name, "label": name if children else "",
                "length": float(match.group(2)) if match.group(2) else None, "children": children}

    text = text.strip()
    tree = node()
    if text[position:] != ";":
        raise ValueError("Newick tree must end with ';'")
    return tree


def leaves(node: dict) -> frozenset[str]:
    if not node["children"]:
        return frozenset([node["name"]])
    return frozenset().union(*(leaves(child) for child in node["children"]))


def clades(tree: dict, outgroup: str) -> list[tuple[frozenset[str], str]]:
    """Every internal branch as the group it separates from the outgroup, with its support label."""
    taxa = leaves(tree)
    if outgroup not in taxa:
        raise ValueError(f"Outgroup {outgroup} is not in the tree")
    found, seen = [], set()

    def visit(node: dict) -> None:
        for child in node["children"]:
            if child["children"]:
                side = leaves(child)
                # An unrooted tree has no direction; take the side without the outgroup.
                group = side if outgroup not in side else taxa - side
                if 1 < len(group) < len(taxa) - 1 and group not in seen:
                    seen.add(group)
                    found.append((group, child["label"]))
                visit(child)

    visit(tree)
    return sorted(found, key=lambda item: (-len(item[0]), sorted(item[0])))


def draw(taxa: frozenset[str], groups: list[tuple[frozenset[str], str]], depth: int = 0) -> list[str]:
    """Indent nested clades so the tree reads from the root down."""
    lines, placed = [], set()
    for group, label in groups:
        if group <= taxa and group != taxa and not group & placed:
            inner = [(g, l) for g, l in groups if g < group]
            lines.append(f"{'  ' * depth}+ ({label or 'no support'})")
            lines += draw(group, inner, depth + 1)
            placed |= group
    lines += [f"{'  ' * depth}{name}" for name in sorted(taxa - placed)]
    return lines


def model_ranking(report: Path, count: int = 3) -> list[tuple[str, float, float, float]]:
    """The first rows of ModelFinder's BIC table: model, log-likelihood, BIC and BIC weight."""
    lines = report.read_text(encoding="utf-8").splitlines()
    start = next(i for i, line in enumerate(lines) if line.startswith("List of models sorted by BIC"))
    rows = []
    for line in lines[start + 3:]:
        fields = line.split()
        if len(fields) != 11:
            break
        rows.append((fields[0], float(fields[1]), float(fields[8]), float(fields[10])))
    return rows[:count]


def report(result: dict, output: Path, outgroup: str | None = None) -> None:
    summary = result["summary"]
    (treefile,) = proteiniq_job.output_files(output, r"\.treefile$")
    (iqtree,) = proteiniq_job.output_files(output, r"\.iqtree$")
    tree = parse_newick(treefile.read_text(encoding="utf-8"))
    taxa = leaves(tree)
    # Without an outgroup, follow IQ-TREE and put the first taxon at the root.
    first = tree
    while first["children"]:
        first = first["children"][0]
    outgroup = outgroup or first["name"]
    groups = clades(tree, outgroup)
    print(f"{summary['sequences']} sequences, {summary['sites']} sites, {summary['sequence_type']}")
    print(f"Best-fit model (BIC): {summary['model']}, log-likelihood {summary['log_likelihood']:.3f}")
    for model, log_likelihood, bic, weight in model_ranking(iqtree):
        print(f"  {model:<14} logL {log_likelihood:.3f}  BIC {bic:.3f}  weight {weight:.3g}")
    print(f"Clades with SH-aLRT/UFBoot support, rooted on {outgroup}:")
    for line in draw(taxa, groups):
        print(f"  {line}")
    with open(output / "clades.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["taxa", "size", "sh_alrt", "ufboot"])
        for group, label in groups:
            alrt, _, ufboot = label.partition("/")
            writer.writerow([" ".join(sorted(group)), len(group), alrt, ufboot])
    print(f"Clade table: {output / 'clades.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "iq-tree-output")
    arguments.add_argument("--alignment", type=Path, help="Aligned FASTA file with 4 or more sequences.")
    arguments.add_argument("--outgroup", help="Taxon to root the clade list on (default: the first taxon in the tree).")
    args = arguments.parse_args()
    if not args.resume and args.alignment is None:
        arguments.error("--alignment is required for a new run.")
    # IQ-TREE is billed by runtime: --max-credits also caps what the run may spend.
    proteiniq_job.main(args, lambda: make_request(args.alignment),
                       lambda result, output: report(result, output, args.outgroup), metered=True)

The shared job runner, proteiniq_job.py:

Python
"""Run one ProteinIQ job safely from a script. Python SDK 0.2.0+. MIT licensed.

Every API example imports this module. It quotes by default, submits only with
--submit and --max-credits, saves the request and idempotency key before the
network call, resumes interrupted runs, and downloads outputs with checksums.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Callable
import uuid

from proteiniq import ProteinIQ
from proteiniq.errors import ProteinIQError


def save_json(path: Path, value: object) -> None:
    with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as handle:
        temporary = Path(handle.name)
        json.dump(value, handle, indent=2)
        handle.write("\n")
    try:
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def text_input(slot: str, kind: str, format_name: str, content: str, label: str) -> dict:
    """One entry of a request's inputs[], with the file contents inline."""
    if not content.strip():
        raise ValueError(f"The {slot} input is empty.")
    return {"id": slot, "slotId": slot, "kind": kind, "format": format_name,
            "content": content, "label": label, "source": {"type": "text"}}


def file_input(path: Path, slot: str, kind: str, formats: dict[str, str]) -> dict:
    """Read a local file into an input, mapping its extension to an accepted format."""
    format_name = formats.get(path.suffix.lower())
    if format_name is None:
        raise ValueError(f"{path.name}: use one of {', '.join(sorted(formats))}.")
    return text_input(slot, kind, format_name, path.read_text(encoding="utf-8"), path.name)


def check_quote(quote, ceiling: int | None, metered: bool = False) -> None:
    if quote.blocking_errors:
        raise ValueError(f"Quote rejected: {quote.blocking_errors}")
    if quote.billing.get("mode") != "fixed" and not metered:
        raise ValueError("These examples only submit fixed-price jobs; inspect metered billing separately.")
    if ceiling is not None and quote.estimated_credits > ceiling:
        raise ValueError(f"Quote {quote.estimated_credits} exceeds your {ceiling}-credit limit.")


def collect(client: ProteinIQ, state: dict, output: Path, timeout: float) -> dict:
    """Wait for the job, save its structured result and download every file once."""
    job = client.jobs.wait(state["job_id"], timeout=timeout)
    if job.status != "COMPLETED":
        raise RuntimeError(f"Job {job.id}: {job.status}: {job.error}")
    result = client.results.wait(job.id, timeout=120)
    save_json(output / "results.json", result.results)
    manifest_path = output / "files.json"
    manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
    for index, file in enumerate(result.files, 1):
        if not file.url:
            raise RuntimeError(f"No download URL for output {file.name}; rerun to refresh links.")
        name = re.sub(r"[^a-zA-Z0-9._-]", "_", file.name or "result-file")[:160]
        destination = output / f"{index:02d}-{name}"
        if destination.exists():
            digest = hashlib.sha256(destination.read_bytes()).hexdigest()
            if manifest.get(destination.name, {}).get("sha256") != digest:
                raise RuntimeError(f"Existing file has no matching checksum: {destination}")
        else:
            client.download_url(file.url, destination)
            digest = hashlib.sha256(destination.read_bytes()).hexdigest()
            manifest[destination.name] = {"source_name": file.name, "sha256": digest}
            save_json(manifest_path, manifest)
    print(f"Completed job {job.id}. Files are in {output}")
    return result.results


def output_files(output: Path, pattern: str) -> list[Path]:
    """Downloaded files whose original server name matches a regular expression."""
    manifest = json.loads((output / "files.json").read_text(encoding="utf-8"))
    return [output / local for local, entry in manifest.items()
            if re.search(pattern, entry.get("source_name") or "")]


def run(args: argparse.Namespace, client: ProteinIQ, build_request: Callable[[], dict],
        metered: bool = False) -> dict | None:
    """Quote, then submit at most one job and collect it. Returns the result once complete.

    With metered=True a runtime-billed quote is accepted, and --max-credits is sent
    with the quote and the submission as the spending cap (billing.max_reserved_credits).
    """
    output = args.output
    state_path = output / "request.json"
    workspace_id = client.account.get().workspace.get("id")
    if not workspace_id:
        raise ValueError("Account response did not identify the workspace.")
    if state_path.exists():
        if not args.resume:
            raise ValueError("This output directory already contains a request. Use --resume or a new directory.")
        state = json.loads(state_path.read_text(encoding="utf-8"))
        if state["base_url"] != client.base_url or state["workspace_id"] != workspace_id:
            raise ValueError("Resume with the same ProteinIQ server and workspace as the original request.")
        if state.get("job_id"):
            return collect(client, state, output, args.timeout)
        if not args.submit:
            raise ValueError("Retrying an unconfirmed submission also requires --submit.")
        if state.get("submission"):
            # Resend exactly what the first attempt sent, so the idempotency key
            # returns that job instead of a new quote changing the request.
            return submit_and_collect(client, state, state_path, output, args.timeout)
        request, ceiling = state["request"], state["max_credits"]
    else:
        if args.resume:
            raise ValueError("No saved request to resume.")
        request = build_request()
        ceiling = args.max_credits
        state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
                 "base_url": client.base_url, "workspace_id": workspace_id}
    spending_cap = {"billing": {"max_reserved_credits": ceiling}} if metered and ceiling and ceiling > 0 else {}
    quote = client.jobs.quote(**request, **spending_cap)
    print(json.dumps(quote.raw, indent=2))
    check_quote(quote, ceiling, metered)
    if not args.submit:
        print("Quote only. No job submitted.")
        return None
    if ceiling is None or ceiling < 1:
        raise ValueError("Submission requires a positive integer --max-credits.")
    state["submission"] = {**request, **(spending_cap if quote.billing.get("mode") != "fixed" else {}),
                           "name": args.job_name, "max_quoted_credits": ceiling}
    return submit_and_collect(client, state, state_path, output, args.timeout)


def submit_and_collect(client: ProteinIQ, state: dict, state_path: Path, output: Path, timeout: float) -> dict:
    # Persist the exact submission and key BEFORE a network call can start a job.
    save_json(state_path, state)
    job = client.jobs.submit(**state["submission"], idempotency_key=state["idempotency_key"])
    state["job_id"] = job.id
    save_json(state_path, state)
    print(f"Job {job.id} submitted. Resume with --output {output} --resume")
    return collect(client, state, output, timeout)


def parser(description: str | None, default_output: str) -> argparse.ArgumentParser:
    """The flags every example shares. Add the example's own inputs to the result."""
    arguments = argparse.ArgumentParser(description=description)
    arguments.add_argument("--output", type=Path, default=Path(default_output))
    arguments.add_argument("--submit", action="store_true", help="Start the job after a successful quote.")
    arguments.add_argument("--max-credits", type=int, help="Highest quote you approve.")
    arguments.add_argument("--resume", action="store_true", help="Continue the request saved in --output.")
    arguments.add_argument("--timeout", type=float, default=3600, help="Seconds to wait locally.")
    arguments.add_argument("--job-name", default="API example")
    return arguments


def main(args: argparse.Namespace, build_request: Callable[[], dict],
         report: Callable[[dict, Path], None], metered: bool = False) -> None:
    """Run the job, then hand the structured result and output folder to report()."""
    args.output.mkdir(parents=True, exist_ok=True)
    # An exclusive lock prevents two local processes overwriting recovery state.
    lock = args.output / ".proteiniq.lock"
    try:
        descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        raise SystemExit(f"{args.output} is in use by another run. Delete {lock} if none is running.")
    try:
        with ProteinIQ() as client:
            result = run(args, client, build_request, metered)
        if result is not None:
            report(result, args.output)
    except (ProteinIQError, ValueError, RuntimeError, TimeoutError) as error:
        raise SystemExit(f"{error}\nKeep this directory and resume the same request. A timeout does not cancel compute.")
    finally:
        os.close(descriptor)
        lock.unlink(missing_ok=True)

How this example was checked

The script's request builder, Newick parser and report reader are tested offline, and its analysis is tested on the tree and report returned by the public IQ-TREE example job of 3 November 2026. The results shown come from that job, which analysed the same alignment with the same settings; the script itself has not yet been run against the live API.