API examples
Fold a protein with ESMFold
Predict E. coli thioredoxin from its sequence in Python, then turn the model's pLDDT column into a per-residue confidence table.
Download Python example · Shared job runner · Example code license
Thioredoxin is the small redox protein that every cell uses to reduce disulfide bonds in other proteins. The E. coli version is 108 residues long, its crystal structure (2TRX) has been known since 1975, and its fold, five β-strands wrapped in four helices, is shared by a whole superfamily of enzymes. That makes it a good first test for a structure predictor: there is a right answer, and a model that gets it wrong is easy to spot.
ESMFold folds it from the sequence alone in about eight seconds. This example does that from Python with the ProteinIQ SDK and then reads the model the way you should read any prediction: residue by residue. The headline confidence is one number, but the file holds 108 of them, and they show which parts of the model you can rely on.
The result
The public example job folded the mature thioredoxin sequence on 22 October 2026 in 8 seconds of compute. Run on the same sequence, the script prints:
108 residues, mean pLDDT 90.3 over atoms and 93.9 over Cα, pTM 0.90
very high: 102 residues
confident: 5 residues
low: 1 residues
very low: 0 residues
below 70: residues 1-1 (lowest 65.8)A pLDDT above 90 means ESMFold expects the local structure to be accurate down to side-chain positions, and 102 of 108 residues clear that bar. The pTM of 0.90 says the same about the global arrangement of the strands and helices. Only the first residue, Ser1, drops below 70. Ends of chains are usually the least confident part of a prediction because nothing holds them in place, and the three lowest residues here are Ser1, Asp2 and the last residue, Ala108. The crystal structure points the same way: in 2TRX, Ala108 has the highest B-factor of any Cα atom.
The active site sits where you would hope. The redox pair Cys32 and Cys35, in the conserved Trp-Cys-Gly-Pro-Cys motif, both score 95.
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 fold_protein.py and proteiniq_job.py from the links at the top of this page into one folder. The first holds everything specific to ESMFold; the second is the job runner that every Python example on these pages shares. Then save the sequence as a FASTA file:
cat > thioredoxin.fasta <<'EOF'
>thioredoxin E. coli, mature chain (UniProt P0AA25)
SDKIIHLTDDSFDTDVLKADGAILVDFWAEWCGPCKMIAPILDEIADEYQGKLTVAKLNIDQNPGTAPKYGIRGIPTLLLFKNGEVAASKVGALSKGQLKEFLDANLA
EOFBuilding the request
ESMFold takes protein sequences in a slot called protein. The script reads one sequence, rejects anything that is not one of the 20 standard amino acids, and sends it inline. ESMFold can fold up to 10 chains together as a complex, but this example sticks to one so the confidence report has a single chain to describe.
def read_sequence(fasta: Path) -> str:
lines = fasta.read_text(encoding="utf-8").splitlines()
if sum(line.startswith(">") for line in lines) > 1:
raise ValueError("Give one sequence per run; this example reports one chain.")
sequence = "".join(line.strip() for line in lines if not line.startswith(">")).upper()
unknown = set(sequence) - AMINO_ACIDS
if not sequence or unknown:
raise ValueError(f"Not a protein sequence; unexpected letters: {sorted(unknown)}")
return sequenceThe settings are written out rather than left to defaults so that request.json records exactly what ran. Four recycles is the number ESMFold was trained with; each recycle feeds the model's own output back in as a refinement step. The PAE matrix stays off here because a single compact domain has no domain arrangement for it to describe.
def make_request(fasta: Path) -> dict:
sequence = read_sequence(fasta)
protein = proteiniq_job.text_input("protein", "protein", "fasta", sequence, fasta.stem)
settings = {"model_type": "esmfold", "num_recycles": 4, "save_pae_matrix": False}
return {"tool": "esmfold", "input": {"inputs": [protein]}, "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, is billed by runtime, or exceeds your limit. 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.
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:
python fold_protein.py --sequence thioredoxin.fasta --output thioredoxinWhen the price looks right, add --submit and replace YOUR_LIMIT with the credits you approve. The server enforces the same ceiling through max_quoted_credits, so a price change between quote and submission cannot charge you more.
python fold_protein.py --sequence thioredoxin.fasta --output thioredoxin --submit --max-credits YOUR_LIMITIf the script is interrupted, run it again with --output thioredoxin --resume and it picks up the same job.
Reading confidence from the model
ESMFold returns one file, prediction_rank01.pdb, with pLDDT written into the B-factor column of every atom. Most viewers can color by that column directly. For a script, the useful view is one value per residue, so the parser keeps the Cα atom of each residue and reads columns 61 to 66, where PDB files store the B-factor.
def residue_plddt(pdb: Path) -> list[tuple[str, int, str, float]]:
"""ESMFold stores pLDDT in the B-factor column; read it from each Cα atom."""
residues = []
for line in pdb.read_text(encoding="utf-8").splitlines():
if line.startswith("ATOM") and line[12:16].strip() == "CA":
residues.append((line[21], int(line[22:26]), line[17:20], float(line[60:66])))
if not residues:
raise ValueError(f"No Cα atoms in {pdb.name}")
return residuesThe plddt value in results.json is the mean over all 820 atoms in the model, which is why it reads 90.3 while the Cα mean is 93.9. Side-chain atoms carry lower confidence than the backbone. Both numbers are correct; just compare like with like when you set a threshold.
Thresholds are easier to act on as stretches of sequence than as single residues, so the script groups consecutive residues below 70 into segments. A long low segment in the middle of a chain usually means a disordered loop or a region that only folds against a partner. A single low residue at the end is the normal fraying of a terminus.
def low_confidence_segments(residues, threshold: float = 70) -> list[tuple[int, int, float]]:
"""Runs of consecutive residues below the threshold, with their lowest pLDDT."""
segments, current = [], []
for _, number, _, plddt in residues + [("", -1, "", 100.0)]:
if plddt < threshold:
current.append((number, plddt))
elif current:
segments.append((current[0][0], current[-1][0], min(p for _, p in current)))
current = []
return segmentsreport prints the summary and band counts and writes every residue to plddt.csv, which you can sort, plot, or join to a mutation list:
chain,residue,name,plddt,band
A,1,SER,65.78,low
A,2,ASP,71.14,confident
A,3,LYS,86.71,confident
A,4,ILE,93.51,very highdef report(result: dict, output: Path) -> None:
summary = result["summary"]
(model,) = proteiniq_job.output_files(output, r"\.pdb$")
residues = residue_plddt(model)
with open(output / "plddt.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["chain", "residue", "name", "plddt", "band"])
writer.writerows([*residue, band(residue[3])] for residue in residues)
ca_mean = sum(plddt for *_, plddt in residues) / len(residues)
# The summary averages every atom; the per-residue Cα mean is usually higher.
print(f"{summary['total_residues']} residues, mean pLDDT {summary['best_plddt']:.1f} "
f"over atoms and {ca_mean:.1f} over Cα, pTM {summary['ptm']:.2f}")
for floor, name in BANDS:
count = sum(band(plddt) == name for *_, plddt in residues)
print(f" {name:>9}: {count} residues")
for start, end, lowest in low_confidence_segments(residues):
print(f" below 70: residues {start}-{end} (lowest {lowest:.1f})")
print(f"Per-residue table: {output / 'plddt.csv'}")Going further
High pLDDT tells you ESMFold is confident, not that it is right, though for well-studied folds like this one the two usually agree. To check, superpose the model on the crystal structure with USAlign as in the structure comparison example. For a geometry check of the model itself, the MolProbity example runs the same way.
ESMFold works from a single sequence, which makes it fast and lets it fold designed proteins with no natural relatives. For natural proteins with deep sequence families, AlphaFold2 builds a multiple sequence alignment first and is often more accurate; AlphaFold vs ESMFold vs RoseTTAFold compares them. When a prediction has several domains, set save_pae_matrix to True and read the PAE to see whether their relative placement is trustworthy.
Complete script
"""Fold a protein sequence with ESMFold and map where the model is confident.
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 proteiniq_job
AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWY")
# pLDDT bands used by AlphaFold DB and the ESMFold paper.
BANDS = [(90, "very high"), (70, "confident"), (50, "low"), (0, "very low")]
def read_sequence(fasta: Path) -> str:
lines = fasta.read_text(encoding="utf-8").splitlines()
if sum(line.startswith(">") for line in lines) > 1:
raise ValueError("Give one sequence per run; this example reports one chain.")
sequence = "".join(line.strip() for line in lines if not line.startswith(">")).upper()
unknown = set(sequence) - AMINO_ACIDS
if not sequence or unknown:
raise ValueError(f"Not a protein sequence; unexpected letters: {sorted(unknown)}")
return sequence
def make_request(fasta: Path) -> dict:
sequence = read_sequence(fasta)
protein = proteiniq_job.text_input("protein", "protein", "fasta", sequence, fasta.stem)
settings = {"model_type": "esmfold", "num_recycles": 4, "save_pae_matrix": False}
return {"tool": "esmfold", "input": {"inputs": [protein]}, "settings": settings}
def residue_plddt(pdb: Path) -> list[tuple[str, int, str, float]]:
"""ESMFold stores pLDDT in the B-factor column; read it from each Cα atom."""
residues = []
for line in pdb.read_text(encoding="utf-8").splitlines():
if line.startswith("ATOM") and line[12:16].strip() == "CA":
residues.append((line[21], int(line[22:26]), line[17:20], float(line[60:66])))
if not residues:
raise ValueError(f"No Cα atoms in {pdb.name}")
return residues
def band(plddt: float) -> str:
return next(name for floor, name in BANDS if plddt > floor or floor == 0)
def low_confidence_segments(residues, threshold: float = 70) -> list[tuple[int, int, float]]:
"""Runs of consecutive residues below the threshold, with their lowest pLDDT."""
segments, current = [], []
for _, number, _, plddt in residues + [("", -1, "", 100.0)]:
if plddt < threshold:
current.append((number, plddt))
elif current:
segments.append((current[0][0], current[-1][0], min(p for _, p in current)))
current = []
return segments
def report(result: dict, output: Path) -> None:
summary = result["summary"]
(model,) = proteiniq_job.output_files(output, r"\.pdb$")
residues = residue_plddt(model)
with open(output / "plddt.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["chain", "residue", "name", "plddt", "band"])
writer.writerows([*residue, band(residue[3])] for residue in residues)
ca_mean = sum(plddt for *_, plddt in residues) / len(residues)
# The summary averages every atom; the per-residue Cα mean is usually higher.
print(f"{summary['total_residues']} residues, mean pLDDT {summary['best_plddt']:.1f} "
f"over atoms and {ca_mean:.1f} over Cα, pTM {summary['ptm']:.2f}")
for floor, name in BANDS:
count = sum(band(plddt) == name for *_, plddt in residues)
print(f" {name:>9}: {count} residues")
for start, end, lowest in low_confidence_segments(residues):
print(f" below 70: residues {start}-{end} (lowest {lowest:.1f})")
print(f"Per-residue table: {output / 'plddt.csv'}")
if __name__ == "__main__":
arguments = proteiniq_job.parser(__doc__, "esmfold-output")
arguments.add_argument("--sequence", type=Path, help="FASTA file with one protein sequence.")
args = arguments.parse_args()
if not args.resume and args.sequence is None:
arguments.error("--sequence is required for a new run.")
proteiniq_job.main(args, lambda: make_request(args.sequence), report)The shared job runner, proteiniq_job.py:
"""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 is tested offline against simulated API responses, and its pLDDT parser is tested on the model returned by the public ESMFold example job of 22 October 2026. The results shown come from that job, which folded the same sequence with the same settings; the script itself has not yet been run against the live API.