Python reference
Lightweight operations, result models, clients, profiles, and compatibility.
Lookup material for the public deepmedchem names: operations, result models, clients, errors, profiles
and authentication, databases and prices, the command line, and the ordering helpers. The tables were
generated from deepmedchem 0.3.0b4 and from live calls. The tutorials are the
Python quickstart, the
Selection builder, and
Python durable runs.
The examples are shown as they appear in a Jupyter notebook. They assume you are signed in (see the quickstart).
1. Public operations
Five module-level functions, each with an aio twin in deepmedchem.aio. Each one creates a
short-lived client, makes one call, and closes it. For several calls, or for selections and runs, use a
Client.
| Function | Returns | What it does |
|---|---|---|
search(smiles, ...) | SearchResult | ranked similarity: method="morgan" (default), "shape", or "esp" |
substructure(query, ...) | SubstructureResult | exact containment, SMARTS (default) or SMILES; no ranking |
sample(...) | SampleResult | random molecules from one chemical space, optionally seeded |
catalog() | dict | the live catalog: libraries, releases, capabilities, limits, registries |
usage() | Usage | account plan and daily credits |
Operation-specific parameters and their defaults (a blank cell means the function does not take it):
| Parameter | search | substructure | sample |
|---|---|---|---|
smiles | required | ||
query | required | ||
database | required | required | required |
method | 'morgan' | ||
format | 'smarts' | ||
limit | 20 | 100 | |
timeout_seconds | 30 | ||
count | 100 | ||
seed | None | ||
include_synthons | False | False | False |
Every function also accepts the connection options shared with Client (section 4):
api_key, api_url, profile, credential_provider, timeout (seconds, default 45), and transport.
The API validates these ranges and reports a violation as an invalid_schema error:
| Argument | Range |
|---|---|
search limit | 1–200 |
substructure limit | 1–200 |
substructure timeout_seconds | 1–120 |
sample count | 1–1000 |
| SMILES length | 1–2048 characters |
2. Result models
SearchResult, SubstructureResult, and SampleResult are ordered sequences of SMILES: iteration,
indexing, slicing, and smiles all use the same ranking. Every attribute below is read locally from the
response you already have; none sends a request.
import pandas as pd
import deepmedchem as dmc
hits = dmc.search("CC(=O)Oc1ccccc1C(=O)O", database="enamine", limit=3, include_synthons=True)
hitsSearchResult(3 molecules, method='morgan', database='enamine-real-v5a')# aligned views, one entry per hit
pd.DataFrame({name: getattr(hits, name) for name in ("ranks", "smiles", "scores", "ids", "prices")}) ranks smiles scores ids prices
0 1 O=C(O)Oc1ccccc1C(=O)O 0.703704 d72ff65eda257ec576fbbefd 245
1 2 COC(=O)Oc1ccccc1C(=O)O 0.666667 edd180638b6c99968e5e6ec8 163
2 3 CC(C)(C)OC(=O)Oc1ccccc1C(=O)O 0.606061 326b09cf92a37112432f0845 163| Attribute | Type | Meaning |
|---|---|---|
smiles, scores, ids, ranks, prices | list | aligned columns. scores is None for substructure and sample; ids are product IDs; prices are whole US dollars or None |
hits | tuple[Hit, ...] | immutable typed rows (below) |
meta | SearchMeta | compact provenance (below) |
warnings | tuple | typed code / message pairs |
raw | dict | the complete, forward-compatible JSON response |
request_id, database_id, database_release, scorer, metric, counts, timing_ms | response fields | |
results | list[dict] | the response rows as plain dictionaries |
repr(result) is bounded and never includes the response. to_records(), to_pandas(), to_csv(),
to_sdf(), and to_file() are covered in section 3.
Hit (immutable row)
| Field | Type | Default |
|---|---|---|
smiles | str | required |
rank | int | required |
score | float | None | None |
product_id | str | None | None |
reaction_id | str | None | None |
metric | str | None | None |
price | int | None | None |
properties | dict[str, float] | None | None |
predicted_properties | dict[str, float] | None | None |
acquisition | PredictedPropertyAcquisitionHit | None | None |
Anything else the service returns is kept and exposed as hit.extra:
sorted(hits.hits[0].extra)['admet_acquisition_scores',
'admet_in_domain',
'approximate_properties',
'constraint_evidence',
'proposal_score',
'synthons']price is a positive whole number of US dollars, or None when no price is available. acquisition is
set only for predicted-property selections (see the
Selection builder). synthons appears only with
include_synthons=True.
SearchMeta and Usage
hits.metaSearchMeta(request_id='ccfbdac5-1968-4ce8-b4db-884e56f286a2', database='enamine-real-v5a', release='2026-09-06.2', method='morgan', metric='ECFP4 Tanimoto', returned=3, elapsed_ms=504.7299531288445)SearchMeta field | Type | Default |
|---|---|---|
request_id | str | None | None |
database | str | None | None |
release | str | None | None |
method | str | None | None |
metric | str | None | None |
returned | int | 0 |
elapsed_ms | float | None | None |
Usage field | Type | Default |
|---|---|---|
plan | str | None | None |
limit | int | None | None |
used | int | 0 |
remaining | int | None | None |
unlimited | bool | False |
window | str | None | 'day' |
reset_at | str | None | None |
seconds_to_reset | int | None | None |
promo | UsagePromotion | None | None |
user_id | str | None | None |
Usage.tier is an alias for plan (free, registered, private, premium, …). unlimited=True
means the credit counters do not apply.
What substructure and sample add
motif = dmc.substructure("C(=O)N1CCC1", database="enamine", limit=2)
draw = dmc.sample(database="enamine", count=2, seed=1)
extra = lambda r: [k for k in r.raw if k not in hits.raw]
{"substructure": extra(motif), "sample": extra(draw)}{'substructure': ['indexed_reactions',
'available_reactions',
'indexed_products',
'available_products',
'coverage_fraction',
'timed_out',
'search_complete',
'query'],
'sample': ['sampling_method',
'sampling_version',
'seed',
'requested',
'returned',
'deduplicated']}Substructure rows carry the exact atoms and bonds that matched; sample rows are indexed, not ranked:
sorted(motif.hits[0].extra), motif.raw["coverage_fraction"], motif.raw["timed_out"](['matched_atom_indices', 'matched_bond_indices', 'synthons'], 1.0, False)3. Exporting results
to_file(path) writes CSV, SDF, SMILES, or JSON and returns the number of molecules written. The format
comes from the suffix (.csv, .sdf/.sd/.mol, .smi/.smiles/.txt, .json) or from format=.
SDF needs RDKit and writes scores and prices as tags. to_records() returns the rows as dictionaries;
to_pandas() needs pandas.
import tempfile, pathlib
out = pathlib.Path(tempfile.mkdtemp())
{suffix: hits.to_file(out / f"hits.{suffix}") for suffix in ("csv", "smi", "json", "sdf")}{'csv': 3, 'smi': 3, 'json': 3, 'sdf': 3}The CSV starts with the common columns, then every other field that is set on at least one hit:
pd.read_csv(out / "hits.csv").columns.tolist()['rank',
'smiles',
'score',
'price',
'product_id',
'database_id',
'database_release',
'reaction_id',
'metric',
'proposal_score',
'synthons'](out / "hits.smi").read_text().splitlines()[:2]['O=C(O)Oc1ccccc1C(=O)O d72ff65eda257ec576fbbefd',
'COC(=O)Oc1ccccc1C(=O)O edd180638b6c99968e5e6ec8']4. Clients
Client (sync) and AsyncClient (async) hold one connection, so several calls reuse it. They offer the
same simple methods as the module-level functions plus the advanced selections and runs namespaces.
Use them as context managers (with Client() as client: and async with AsyncClient() as client:), or
call close() yourself (await client.close() for the async one).
| Parameter | Default | Meaning |
|---|---|---|
api_key | None | explicit key; highest precedence (section 7) |
api_url | None | override the API host |
profile | None | which profile to use (section 6) |
account_url | None | override the account-service host |
timeout | 45.0 | per-request timeout in seconds |
max_retries | 2 | retries for 429, 503, 504, and network errors |
retry_backoff | 0.25 | the delay doubles from this value up to 5 s and honours Retry-After (up to 30 s) |
credential_provider | None | a callable or object with get_api_key() (section 7) |
transport | None | an httpx transport, mainly for tests |
application | 'deepmedchem-python' | identifies your tool in request headers |
application_version | None | version reported in request headers |
from deepmedchem import Client, AsyncClient
client = Client()
{
"methods": [n for n in dir(client) if not n.startswith("_")],
"namespaces": [n for n in ("selections", "runs") if hasattr(client, n)],
}{'methods': ['catalog',
'close',
'runs',
'sample',
'search',
'search_cheese',
'search_substructure',
'selections',
'usage'],
'namespaces': ['selections', 'runs']}search_cheese is the shape/electrostatic route that search(method=...) uses internally:
r = client.search_cheese("CCO", database="enamine", scorer="shape", limit=2)
r, client.close()(SearchResult(2 molecules, method='shape', database='enamine-real-v5a'), None)5. Errors
Failures raise DeepMedChemError. Local mistakes such as a bad argument raise ValueError before any
request.
| Attribute | Meaning |
|---|---|
code | stable machine-readable code |
status_code | HTTP status, or None for errors raised locally |
retryable | whether retrying the same call can succeed |
request_id | quote it when contacting support |
from deepmedchem import DeepMedChemError
cases = {
"no credential": lambda: Client(profile="dev"),
"wrong key": lambda: Client(api_key="invalid").search("CCO", database="enamine", limit=1),
"server unreachable": lambda: Client(api_url="http://127.0.0.1:9", timeout=2, max_retries=0).search("CCO", database="enamine", limit=1),
"invalid SMILES": lambda: dmc.search("not-a-smiles", database="enamine"),
"unknown database": lambda: dmc.search("CCO", database="no-such-space"),
"limit too large": lambda: dmc.search("CCO", database="enamine", limit=500),
"unknown method": lambda: dmc.search("CCO", database="enamine", method="nope"),
"unknown profile": lambda: Client(profile="nope"),
}
rows = []
for label, call in cases.items():
try:
call()
except DeepMedChemError as e:
rows.append((label, "DeepMedChemError", e.code, e.status_code, e.retryable))
except ValueError as e:
rows.append((label, "ValueError", None, None, None))
pd.DataFrame(rows, columns=["case", "raised", "code", "status", "retryable"]) case raised code status retryable
0 no credential DeepMedChemError missing_api_key NaN False
1 wrong key DeepMedChemError unauthorized 401.0 False
2 server unreachable DeepMedChemError transport_error NaN True
3 invalid SMILES DeepMedChemError worker_error 400.0 False
4 unknown database DeepMedChemError unavailable_library 400.0 False
5 limit too large DeepMedChemError invalid_schema 422.0 False
6 unknown method ValueError NaN NaN None
7 unknown profile ValueError NaN NaN NoneCodes you will meet:
| Code | Status | Retryable | Meaning |
|---|---|---|---|
missing_api_key | none | no | no credential found for the profile |
unauthorized | 401 | no | missing or invalid key |
invalid_schema | 422 | no | an argument failed validation (range, length, pattern) |
invalid_request | 400 | no | a semantic problem, such as an unknown property or contradictory constraints |
unavailable_library | 400 | no | the chemical space is not loaded |
worker_error | 400 | no | the engine rejected the input, for example an invalid SMILES |
durable_required | 413 | no | the selection is over the synchronous budget; use a run |
run_not_found | 404 | no | unknown run ID |
idempotency_conflict | 409 | no | the idempotency key was already used with different content |
transport_error | none | yes | the request could not be completed (network) |
client_timeout | none | no | runs.wait(timeout=...) ran out of time |
429, 503, and 504 responses are retried automatically, then raised with retryable=True. See
errors for the HTTP error envelope.
6. Profiles and configuration
A profile bundles the three hosts the SDK talks to: the API, the web app used for login, and the account
service used for usage(). The SDK never derives one host from another.
| Profile | api_url | web_url | account_url |
|---|---|---|---|
default | https://api.deepmedchem.com | https://cheese.deepmedchem.com | https://api.cheese.deepmedchem.com |
dev | https://api-dev.deepmedchem.com | https://cheese-new-dev.deepmedchem.com | https://api.cheese-dev.deepmedchem.com |
Profile precedence: the profile= argument, then DEEPMEDCHEM_PROFILE, then the active profile in the
configuration file, then default. Non-secret settings live in a TOML file at a platform-specific path
that deepmedchem status prints; API keys are never written there.
deepmedchem statusprofile: default
api_url: https://api.deepmedchem.com
web_url: https://cheese.deepmedchem.com
account_url: https://api.cheese.deepmedchem.com
config_path: ~/Library/Application Support/deepmedchem/config.toml
authenticated: True| Environment variable | Effect |
|---|---|
DEEPMEDCHEM_API_KEY | API key (also DMC_API_KEY, CHEESE_API_KEY) |
DEEPMEDCHEM_PROFILE | select a profile |
DEEPMEDCHEM_API_URL (also DMC_API_URL), DEEPMEDCHEM_WEB_URL, DEEPMEDCHEM_ACCOUNT_URL | override the default profile's hosts |
DEEPMEDCHEM_CREDENTIAL_STORE | file or keyring to force one credential store (default auto) |
DEEPMEDCHEM_NO_BROWSER | make login print the approval URL instead of opening a browser |
7. Authentication
Credential precedence, first match wins:
- the
api_key=argument, DEEPMEDCHEM_API_KEY, thenDMC_API_KEY, thenCHEESE_API_KEY,- a
credential_provider(a callable returning a key orNone, or an object withget_api_key()), - the selected profile's stored key: the OS keychain, or a
0600credentials file next to the configuration file on hosts without a keychain.
deepmedchem login # approve this device in your browser and store the key
deepmedchem login --profile dev
deepmedchem status --verify # confirm the stored key is accepted by the API
deepmedchem logout --profile devlogin --token-stdin reads a key from standard input for headless setups.
A provider is only consulted after the explicit key and the environment variables:
def from_vault():
return None # return the key from your secret manager here
with Client(credential_provider=from_vault) as c:
account = c.usage()
accountUsage(plan='premium', credits=unlimited)deepmedchem status --verifyprofile: default
api_url: https://api.deepmedchem.com
web_url: https://cheese.deepmedchem.com
account_url: https://api.cheese.deepmedchem.com
config_path: ~/Library/Application Support/deepmedchem/config.toml
authenticated: True
verified: True
plan: premium
credits_remaining: unlimited
credits_limit: 10000008. Databases and prices
Use the catalog to see what is available. Database IDs are release-pinned names such as
enamine-real-v5a; a short alias resolves to the full ID wherever a database is expected, and full IDs
and private IDs always work verbatim. Aliases exist for make-on-demand spaces only.
deepmedchem databasesabbreviation molecules prices orders
------------ --------- ------ ------------------------
enamine ~93.4B yes info@enamine.net
freedom 296.4B yes sales@chem-space.com
explore 9.5T yes sales@emolecules.com
synple 7.6T yes sales@emolecules.com
vast 6.8B yes VAST@XtalPi.com
cheminfinita 794.2B - sales@otavachemicals.com
spacem1 1.5B - hello@molecule.one
7 databases. Lead times vary by database; see --detailed.
Order or request quotes by email, or run `dmc order results.csv`.rows = [
(l["database_id"], l["release_id"], l["pricing"]["available"], l["pricing"].get("currency"), l["pricing"].get("ship_to"), l["pricing"].get("default_amount_mg"))
for l in dmc.catalog()["libraries"]
]
pd.DataFrame(rows, columns=["database_id", "release", "prices", "currency", "ship_to", "default_mg"]) database_id release prices currency ship_to default_mg
0 cheminfinita-2026-02 2026-02.3 False NaN NaN NaN
1 d2b-spacem1 2025-09-24.4 False NaN NaN NaN
2 enamine-real-v5a 2026-09-06.2 True USD US 1.0
3 freedom-space-5 2026-03-296b.4 True USD US 1.0
4 synple-explore-2025-10 2025-10.4 True USD US 1.0
5 synple-synple-2025-10 2025-10.4 True USD US 1.0
6 vast-2026-h2 2026-h2.3 True USD US 1.0hit.price and the aligned result.prices list are whole US dollars for US delivery, defaulting to 1 mg
where the vendor uses pack sizes, taken from the original response without another request. A missing or
unsupported price is None, never zero. Prices are estimates; request a binding quote from the vendor
before ordering. See chemical spaces and capabilities for database
support.
9. Command line
The package installs deepmedchem and the short alias dmc. Commands exit 0 on success and 1 on an
error, which is printed to standard error.
| Command | Purpose |
|---|---|
login, status, logout | store, check, or remove credentials |
usage | plan and remaining daily credits |
databases (alias catalog) | list searchable databases; --detailed adds IDs and provider details |
search SMILES -d DB [-m morgan|shape|esp] [-n N] | similarity search |
substructure QUERY -d DB [-f smiles|smarts] [-n N] [--timeout-seconds S] | exact substructure |
sample -d DB [-n N] [--seed S] | random sample |
order RESULTS.csv | prepare vendor request drafts (section 10) |
Common options: --profile NAME, --json (print the raw response), and, on the three search commands,
-o FILE and --format csv|sdf|smi|json.
deepmedchem --version
deepmedchem search CCO -d enamine -n 2 -o cli.csv0.3.0b4
rank score price smiles
---- ------ ----- ------
1 0.4167 $245 CCCCO
2 0.3846 $245 CCCCCO
Searched ~93.4B source combinations (Enamine REAL v5a) in 639 ms.
Similarity range: 0.38-0.42 ECFP4 Tanimoto.
Saved 2 molecules to cli.csv (csv).pd.read_csv("cli.csv")[["rank", "smiles", "score", "price"]] rank smiles score price
0 1 CCCCO 0.416667 245
1 2 CCCCCO 0.384615 245A failing command prints the error and exits with 1:
deepmedchem search CCO -d no-such-space; echo "exit code: $?"error: library not loaded: no-such-space [unavailable_library]
exit code: 110. Ordering helpers
prepare_order(results_csv, ...) turns a results CSV (as written by to_csv or -o) into one reviewable
request per vendor. It never sends anything and never includes prices: it writes files, and
deepmedchem order can additionally open your mail client with each draft. Pass get_quote=True to ask
for a quote instead of an order.
from deepmedchem import prepare_order
bundle = prepare_order(out / "hits.csv", get_quote=True, output_dir=out / "quote", amount_mg=5, name="A. Chemist")
bundle.mode, bundle.molecule_count, [(d.vendor, d.email, len(d.molecules)) for d in bundle.drafts]('quote', 3, [('Enamine', 'info@enamine.net', 3)])sorted(str(p.relative_to(bundle.directory)) for p in bundle.directory.rglob("*") if p.is_file())['enamine/email.txt', 'enamine/molecules.csv', 'manifest.json', 'summary.txt']| Object | Fields |
|---|---|
OrderBundle | directory, mode (order or quote), drafts, molecule_count |
OrderDraft | vendor, email, molecules, directory, csv_path, email_path, subject, body, mailto_url |
OrderMolecule | database_id, deepmedchem_id, smiles |
Parameters: database (when the CSV has no database_id column), output_dir, to (override the
recipient, combining all rows), amount_mg, name. The directory must not already exist. Databases
without a known vendor contact need to=.
11. Compatibility
Older names still work during the migration window.
| Name | Is |
|---|---|
DMCClient, AsyncDMCClient, DMCError | aliases of Client, AsyncClient, DeepMedChemError |
Client.search_cheese(..., scorer=), Client.search_substructure(..., query_format=) | the underlying methods behind search(method=...) and substructure(...) |
DMC_API_KEY, CHEESE_API_KEY, DMC_API_URL | accepted alongside the DEEPMEDCHEM_* variables |
keychain entries from dmc-navigator | read and copied to the new location on first use |
from deepmedchem import DMCClient, AsyncDMCClient, DMCError
DMCClient is Client, AsyncDMCClient is AsyncClient, DMCError is DeepMedChemError(True, True, True)