Python

Python reference

Lightweight operations, result models, clients, profiles, and compatibility.

Suggest an edit

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.

FunctionReturnsWhat it does
search(smiles, ...)SearchResultranked similarity: method="morgan" (default), "shape", or "esp"
substructure(query, ...)SubstructureResultexact containment, SMARTS (default) or SMILES; no ranking
sample(...)SampleResultrandom molecules from one chemical space, optionally seeded
catalog()dictthe live catalog: libraries, releases, capabilities, limits, registries
usage()Usageaccount plan and daily credits

Operation-specific parameters and their defaults (a blank cell means the function does not take it):

Parametersearchsubstructuresample
smilesrequired
queryrequired
databaserequiredrequiredrequired
method'morgan'
format'smarts'
limit20100
timeout_seconds30
count100
seedNone
include_synthonsFalseFalseFalse

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:

ArgumentRange
search limit1–200
substructure limit1–200
substructure timeout_seconds1–120
sample count1–1000
SMILES length1–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)
hits
SearchResult(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
AttributeTypeMeaning
smiles, scores, ids, ranks, priceslistaligned columns. scores is None for substructure and sample; ids are product IDs; prices are whole US dollars or None
hitstuple[Hit, ...]immutable typed rows (below)
metaSearchMetacompact provenance (below)
warningstupletyped code / message pairs
rawdictthe complete, forward-compatible JSON response
request_id, database_id, database_release, scorer, metric, counts, timing_msresponse fields
resultslist[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)

FieldTypeDefault
smilesstrrequired
rankintrequired
scorefloat | NoneNone
product_idstr | NoneNone
reaction_idstr | NoneNone
metricstr | NoneNone
priceint | NoneNone
propertiesdict[str, float] | NoneNone
predicted_propertiesdict[str, float] | NoneNone
acquisitionPredictedPropertyAcquisitionHit | NoneNone

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.meta
SearchMeta(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 fieldTypeDefault
request_idstr | NoneNone
databasestr | NoneNone
releasestr | NoneNone
methodstr | NoneNone
metricstr | NoneNone
returnedint0
elapsed_msfloat | NoneNone
Usage fieldTypeDefault
planstr | NoneNone
limitint | NoneNone
usedint0
remainingint | NoneNone
unlimitedboolFalse
windowstr | None'day'
reset_atstr | NoneNone
seconds_to_resetint | NoneNone
promoUsagePromotion | NoneNone
user_idstr | NoneNone

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).

ParameterDefaultMeaning
api_keyNoneexplicit key; highest precedence (section 7)
api_urlNoneoverride the API host
profileNonewhich profile to use (section 6)
account_urlNoneoverride the account-service host
timeout45.0per-request timeout in seconds
max_retries2retries for 429, 503, 504, and network errors
retry_backoff0.25the delay doubles from this value up to 5 s and honours Retry-After (up to 30 s)
credential_providerNonea callable or object with get_api_key() (section 7)
transportNonean httpx transport, mainly for tests
application'deepmedchem-python'identifies your tool in request headers
application_versionNoneversion 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.

AttributeMeaning
codestable machine-readable code
status_codeHTTP status, or None for errors raised locally
retryablewhether retrying the same call can succeed
request_idquote 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      None

Codes you will meet:

CodeStatusRetryableMeaning
missing_api_keynonenono credential found for the profile
unauthorized401nomissing or invalid key
invalid_schema422noan argument failed validation (range, length, pattern)
invalid_request400noa semantic problem, such as an unknown property or contradictory constraints
unavailable_library400nothe chemical space is not loaded
worker_error400nothe engine rejected the input, for example an invalid SMILES
durable_required413nothe selection is over the synchronous budget; use a run
run_not_found404nounknown run ID
idempotency_conflict409nothe idempotency key was already used with different content
transport_errornoneyesthe request could not be completed (network)
client_timeoutnonenoruns.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.

Profileapi_urlweb_urlaccount_url
defaulthttps://api.deepmedchem.comhttps://cheese.deepmedchem.comhttps://api.cheese.deepmedchem.com
devhttps://api-dev.deepmedchem.comhttps://cheese-new-dev.deepmedchem.comhttps://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 status
profile: 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 variableEffect
DEEPMEDCHEM_API_KEYAPI key (also DMC_API_KEY, CHEESE_API_KEY)
DEEPMEDCHEM_PROFILEselect a profile
DEEPMEDCHEM_API_URL (also DMC_API_URL), DEEPMEDCHEM_WEB_URL, DEEPMEDCHEM_ACCOUNT_URLoverride the default profile's hosts
DEEPMEDCHEM_CREDENTIAL_STOREfile or keyring to force one credential store (default auto)
DEEPMEDCHEM_NO_BROWSERmake login print the approval URL instead of opening a browser

7. Authentication

Credential precedence, first match wins:

  1. the api_key= argument,
  2. DEEPMEDCHEM_API_KEY, then DMC_API_KEY, then CHEESE_API_KEY,
  3. a credential_provider (a callable returning a key or None, or an object with get_api_key()),
  4. the selected profile's stored key: the OS keychain, or a 0600 credentials 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 dev

login --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()
account
Usage(plan='premium', credits=unlimited)
deepmedchem status --verify
profile: 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: 1000000

8. 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 databases
abbreviation  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.0

hit.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.

CommandPurpose
login, status, logoutstore, check, or remove credentials
usageplan 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.csvprepare 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.csv
0.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    245

A 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: 1

10. 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']
ObjectFields
OrderBundledirectory, mode (order or quote), drafts, molecule_count
OrderDraftvendor, email, molecules, directory, csv_path, email_path, subject, body, mailto_url
OrderMoleculedatabase_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.

NameIs
DMCClient, AsyncDMCClient, DMCErroraliases 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_URLaccepted alongside the DEEPMEDCHEM_* variables
keychain entries from dmc-navigatorread 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)

On this page