# BioCypher adapters

Checked against BioCypher 0.17.0. Part of the BioCypher LLM guides; index: https://biocypher.org/BioCypher/agents/llms.txt

An adapter is user code that reads one data source and yields node and edge tuples. BioCypher has no adapter base class: any object whose methods return iterables of tuples works. By convention an adapter exposes `get_nodes()` and `get_edges()`, each returning a generator.

## Node tuple

`(node_id, input_label, properties)`

- `node_id` (str): unique across the whole graph, not only within one type. Prefer CURIEs (`uniprot:P04637`, `hgnc:11998`) and normalize them (strip whitespace, consistent case and prefix) before yielding.
- `input_label` (str): must equal an `input_label` of a node class in `schema_config.yaml`.
- `properties` (dict): keys must match the class's `properties` in the schema. Convert values to the declared type yourself (see "Types" below).

## Edge tuple

`(edge_id, source_id, target_id, input_label, properties)`

- `edge_id` (str or None): `None` is fine for edges represented as edges, unless there can be several edges of the same type between the same two nodes (see deduplication below). For edges represented as nodes (`represented_as: node` in the schema), BioCypher builds an ID from source, target and property values when `edge_id` is `None`.
- `source_id`, `target_id` (str): node IDs exactly as yielded in node tuples. BioCypher does not check that these nodes exist; dangling edges reach the output and fail or get skipped at database import.
- `input_label` (str): the 4th element. Must equal an `input_label` of an edge class in the schema.
- `properties` (dict): as for nodes.

4-tuples `(source_id, target_id, input_label, properties)` are still accepted but deprecated. Always yield 5-tuples.

## How BioCypher consumes tuples

BioCypher decides per call whether it got nodes or edges by looking at the length of the first element: fewer than 4 elements means nodes, otherwise edges. Do not mix nodes and edges in one iterable.

For every tuple, BioCypher:

1. Looks up the label in the schema. Unknown label: the tuple is dropped and an error is logged (`No ontology type defined for ...`); the run continues. `bc.log_missing_input_labels()` lists all dropped labels.
2. Filters properties: keys not declared in the schema are dropped silently; declared keys missing from the tuple are added with value `None`. If the class declares no properties, all properties pass through unfiltered.
3. In strict mode (`strict_mode: true`), raises `ValueError` if `source`, `licence` or `version` is missing from the properties (`license` is renamed to `licence`).
4. Deduplicates, keeping the first occurrence and dropping later ones even when their properties differ:
   - nodes by node ID, across all types;
   - edges by edge type plus edge ID, or, when `edge_id` is `None`, by edge type plus source and target. Two edges of the same type between the same pair of nodes (for example from two experiments) therefore collapse into one unless each gets its own `edge_id`.
   `bc.log_duplicates()` reports the duplicate types and IDs.

Values are not cast to the schema type. A Python `int` under a `bool` property is written as `1`, not `true`.

## Calling the adapter

Offline mode (files plus an import script) or online Neo4j:

```python
bc.write_nodes(adapter.get_nodes())
bc.write_edges(adapter.get_edges())
bc.write_import_call()  # offline only
```

In-memory backends (`dbms: networkx`, `pandas`, `csv`, `tabular` with `offline: false`):

```python
bc.add(adapter.get_nodes())
bc.add(adapter.get_edges())
kg = bc.get_kg()  # networkx.DiGraph, or dict of pandas DataFrames keyed by schema class
```

Write all nodes before edges. Generators are consumed once: call `adapter.get_nodes()` again for a second pass, do not reuse the same generator object.

## Writing an adapter

1. Read the schema first. List every class with its `input_label`, `represented_as`, `source`/`target` (edges) and `properties` with types.
2. Inspect the real data: column names, ID formats, value types, missing values, duplicates, case differences.
3. For each schema class, decide which rows produce it and how the ID is built. The same entity must get the same ID everywhere it appears, including as an edge endpoint.
4. Convert every value to the declared type (`int(...)`, `float(...)`, parse booleans from strings explicitly, split array values into lists).
5. Yield tuples from generators; do not build large lists in memory.
6. Decide what to do with rows that have missing IDs or endpoints that are not nodes, and log them.

## Types

Schema property types and the Python values to yield:

- `str` / `string`: `str`
- `int` / `integer` / `long`: `int`
- `float` / `double` / `dbl`: `float`
- `bool` / `boolean`: `bool` (parse `"true"`, `"yes"`, `"1"` yourself; `bool("false")` is `True`)
- `str[]`, `int[]`, ...: `list` of the element type

## Downloading and caching source files

Use BioCypher's resource classes instead of hand-written download code:

```python
from biocypher import APIRequest, FileDownload

resource = FileDownload(
    name="uniprot_human",            # cache subdirectory name
    url_s="https://example.org/file.tsv.gz",  # str or list of str
    lifetime=30,                     # days; 0 = never expires
    is_dir=False,                    # True: download all files listed in a directory URL
)
paths = bc.download(resource)        # list of local file paths; uses cache_directory from config
```

`APIRequest(name, url_s, lifetime)` works the same way for API endpoints. `FileDownload` has no `get()` method; downloading goes through `bc.download(...)` or `biocypher._get.Downloader(cache_dir).download(...)`. Both return a list of paths.

## Testing an adapter

Counting nodes and edges in the built graph is not enough: deduplication and property filtering hide adapter errors. Test the tuples the adapter yields:

- every label is an `input_label` in the schema;
- node IDs are unique, or duplicates have identical properties;
- every edge endpoint is a yielded node ID;
- every property key is declared in the schema, and every value has the declared Python type;
- IDs and symbols are normalized (no `TP53` and `tp53` for the same entity).

Then run the pipeline once and check the log for `No ontology type defined`, duplicate warnings and strict-mode errors.

## Related files

- Schema rules: https://biocypher.org/BioCypher/agents/llms-schema-config.txt
- Runnable example: https://biocypher.org/BioCypher/agents/llms-example-adapter.txt
- Known problems: https://biocypher.org/BioCypher/agents/llms-pitfalls.txt
