> ## Documentation Index
> Fetch the complete documentation index at: https://ladygraph.io.vn/llms.txt
> Use this file to discover all available pages before exploring further.

# Sources

> Turn databases, config files and markdown into Documents.

A source turns a system into Documents. Each entry under `sources:` in `ladygraph.yaml` has a `name` (a label for logs), a `kind`, a `scheme` (how passage addresses start, such as `notes://`), and the settings of its kind.

| Kind | The input | Shape (default) | What you write |
| - | - | - | - |
| `markdown` | `.md` files with optional front matter | `decompose` | `path`, `split_level`, `target_chars`, `skip_status` |
| `json` | A `.json`, `.yaml` or `.yml` file | `map` | `path` and `rules`, or `auto: {}` |
| `pydantic` | A function that returns a model | `map` | `provider` and `rules`, or `auto: {}` |
| `sql` | A database | `assemble` or `map` | `connections`, `tables`, `queries`, `map` |

A source of a kind with no adapter is skipped with a warning, not an error. Check the log if a source seems missing.

## What you can read from

ladyGraph indexes business internal documents: skills, policies and guidelines, and business-application configurations. Each kind of system reaches the index through a source.

| The system holding your documents | How ladyGraph reads it |
| - | - |
| An ACID database: SQL, Postgres | `kind: sql`. You write the queries that list the documents and read their chunks. |
| JSON or YAML files, such as rules, glossaries and settings | `kind: json`. Rules pick the entries, or `auto: {}` finds the knowledge. |
| An application's configuration as Python objects | `kind: pydantic`. |
| Markdown files, such as skills, policies and guidelines | `kind: markdown`. Headings split a file into documents. |
| A vector database that holds chunked documents | No built-in adapter. Implement the `Source` interface (`manifest` and `read`) and return each document with its chunks as passages. |
| A document-oriented database | No built-in adapter. Implement the `Source` interface, or export the documents as JSON files for `kind: json`. |

The [Interfaces](https://ladygraph.io.vn/reference/api/overview.md) page shows the `Source` contract.

## One example of each kind

This block is tested: `tests/test_project_paths.py` loads it with `load_sources`. The list goes under `sources:`.

```yaml theme={null}
- name: notes                          # markdown: a folder, file or glob of .md files
  kind: markdown
  scheme: notes
  path: notes/*.md                     # relative to this file; {scope} is replaced by the scope being indexed
  split_level: 2                       # headings of this level start a new Document

- name: blueprint                      # json: a .json or .yaml file of rules, glossary entries, settings
  kind: json
  scheme: bp
  path: blueprints/{scope}.json
  rules:
    - {pointer: /glossary/*, kind: glossary, id: term, title: term}     # one Document per glossary entry

- name: settings                       # pydantic: a function returns a model, dumped and read like a json file
  kind: pydantic
  scheme: cfg
  provider: my_package.config:build_settings                            # package.module:function, called with the scope
  auto: {}                             # no rules written: the shape of the data decides what is knowledge

- name: documents                      # sql: documents and chunks mined from a database
  kind: sql
  scheme: db                           # passages: db://<scope>/<unit>#<anchor>
  document_scheme: dbdoc               # the document itself: dbdoc://<scope>/<unit>
  shape: assemble                      # assemble: many rows become one Document | map: one row is one Document
  connections:
    meta: {dsn: "env:META_DB_URL"}       # a URL, or env:NAME so the secret stays in the environment
  tables:
    documents: {connection: meta, key: document_id, columns: [document_id, scope_id, file_name, status]}
    chunks: {connection: meta, key: chunk_id, columns: [chunk_id, document_id, text, node_path, breadcrumbs]}
  queries:
    manifest: SELECT document_id AS unit, scope_id AS scope, file_name AS checksum, status FROM documents WHERE scope_id = :scope
    document: SELECT file_name, document_id AS unit, scope_id AS scope, file_name AS checksum, status FROM documents WHERE document_id = :unit
    passages: SELECT text, node_path, breadcrumbs FROM chunks WHERE document_id = :unit ORDER BY node_path
  map:
    title: file_name
    version: {file: [checksum], metadata: [status]}
    passage: {text: text, anchor: node_path, section: breadcrumbs}
```

## SQL sources

A `kind: sql` source declares four things: where to connect (`connections`), which tables it mines (`tables`, and optionally `relationships`), the queries that read them (`queries`), and how query columns become Document fields (`map`).

* **The manifest must be cheap.** It returns `unit`, a version column or checksum, and the same metadata and date columns as `document`. Otherwise every update sees a change.
* **Parameters are bound.** Queries use `:scope` and `:unit`, never formatted text. Table and column names come from this trusted config, never from user input.
* **Two databases cannot be joined in SQL.** The adapter runs the `document` and `passages` queries separately and joins them on `unit` in Python. A `JOIN` inside a query works only between tables on the same connection.
* **`map` supplies** the title, metadata, access labels, validity dates, the version parts, and the passage text, anchor and section. The adapter computes the rest: `scope` and `unit` from the manifest columns, `shape` from the config, and the addresses.
* **Two schemes.** `scheme` addresses passages (`db://`). `document_scheme` addresses the document (`dbdoc://`). When `document_scheme` is absent, the document uses `scheme`.
* **`passages_digest` keeps the manifest cheap.** `DocVersion.passages` must be the same from `manifest` and `read`. With the digest query, both use the database's own hash of the chunk texts, so no text is read to detect a change.
* **`relationships` is declarative.** Nothing in SQL enforces it. It documents the keys and cardinality, and tells the adapter to read the latest version only (`pick: latest`). It is not needed to run the queries.
* **`replacements`** is an optional query. It takes `:scope` and returns each unit with the effective date of a document that replaces it. The unit's validity period ends at the earlier of its expiry and that date.

> [!WARNING]
>
> `sources/sql.py` is tested against SQLite in `tests/test_sql_source.py`. The queries use Postgres functions (`md5`, `string_agg`) and have not been run against a production database. The table and column names in the examples are an illustration, not checked against any real schema.

## Config and markdown sources

Business configuration has no fixed shape: routing rules, escalation rules, a glossary, skill routing, and notes written as markdown. Three sources read it without a database. Each flattens and normalizes its input into Records, because the extractor needs the same thing from all of it: a title, metadata, and passages of plain text it can quote.

```text theme={null}
JSON or YAML file  --JsonSource-------+
pydantic model     --PydanticSource---+-->  Record  -->  FlatSource  -->  Document  -->  extractor
markdown files     --MarkdownSource---+
```

| Source | Input | Shape | One Document per |
| - | - | - | - |
| `kind: json` | A `.json`, `.yaml` or `.yml` file. `path` may contain `{scope}`. | map | Entry that a rule selects |
| `kind: pydantic` | `provider: package.module:function`, which returns a model for the scope | map | Entry that a rule selects |
| `kind: markdown` | A folder, a file or a glob | decompose | Section (heading) |

**Normalizing** removes what is not knowledge. Text is NFC and trimmed, numbers and dates become text, booleans become "yes" and "no", and empty values are dropped. Nested objects become `a.b: value` lines, and lists of scalars become `a: x; y`. The output is deterministic, because the resolver reads it again at search time and compares fingerprints.

A new kind of input needs only a `Flattener`, a function `flatten(scope, raw)` that returns Records. `FlatSource` is the only source that reads Records, so versions, validity periods and addresses are computed in one place.

### Rules

For JSON and pydantic sources, rules pick the entries with a JSON Pointer and say how to read them. Write one rule per kind of entry.

| Key | Meaning |
| - | - |
| `pointer` | A JSON Pointer. `*` picks every member, so `/rules/*` gives one Document per rule. |
| `kind` | `rule`, `glossary` and so on. It becomes metadata `kind` and the passage section, so entries of one kind meet in one context. |
| `id`, `title` | The field that names the unit, and the field used as the Document title. |
| `where` | Keep only entries whose fields equal these, for example `{enabled: true}`. |
| `fields`, `exclude` | Which fields become text. The default is all of them, in file order. |
| `passage` | `field` (the default) gives one passage per field, so a quote points at one field. `entry` makes the whole entry one passage, which reads like a paragraph. |
| `render` | `{markers: dnf}` writes marker clauses such as `a & b & !c` as a sentence: `mentions "a" and "b" but not "c"`. |
| `labels` | A readable label for a cryptic field name, for the extractor. |
| `metadata`, `access_labels`, `valid_from`, `valid_until` | Field names that fill those Document fields. |
| `words`, `declare`, `rewrite` | Declared words, declared concepts, and a model's reading of an entry (see below). |

A unit is `<path before the entry>~<slug of the id>`, so reordering a list changes nothing. Two entries with the same id both stay, with a `-2` suffix. Without `rules`, every top-level member of the input is one entry.

This is a routing rule from a blueprint, and what the extractor receives:

```yaml theme={null}
rules:
  - pointer: /query_route_rules/*       # one Document per rule
    kind: routing rule
    id: id
    title: label
    render: { markers: dnf }            # "a & b & !c" is written as a sentence
    labels: { markers: A question is routed here when it }
    metadata: { topics: topic_ids }
```

```text theme={null}
query_route_rules~entertainment   title: Entertainment expenses
  [markers]  A question is routed here when it: mentions "tiếp khách" and "chi phí" but not "hội nghị"; or mentions "quà tặng"
  [route]    route: direct_rag
  [topic_ids] topic_ids: expenses; approval
```

Run `PYTHONPATH=. python ladygraph/tutorial/04_sources/hello_flat_sources.py` from `ladyGraph/` to see all of this on sample data.

### Automatic mode

A real blueprint is mostly plumbing, such as thresholds, switches, budgets and refresh intervals, with a little knowledge in a few recognizable shapes. Writing a rule per kind of entry does not scale to files nobody controls. `auto: {}` on a JSON or pydantic source finds the knowledge from the shape of the data and says why.

```yaml theme={null}
- name: domain
  kind: json
  scheme: cfg
  path: config/{scope}.json
  auto: {}                                    # no rules. Optional: passage, protected, redact, knowledge_names, system_names
  triage: { cache: triage.json }              # optional: a Decider judges long text; its answers are saved
```

Automatic mode works in this order:

1. Every object in a list is an entry (a rule, a term, a field, a block). The rest of the file is one profile entry.
2. Each leaf is scored from the kind of value and from its field name. A number, a switch or a code word explains nothing. A phrase, a sentence or a list of phrases does. Names like `label`, `markers` and `aliases` lean to knowledge. Names like `enabled` and `max_rows` lean to configuration.
3. A leaf that points at another entry scores more, because it explains why the neighbors are related.
4. Entries marked `kind: secret` or `visibility: restricted` are skipped. A long text built from smaller texts is dropped as a copy. An entry left with only its label is dropped.
5. `a & b & !c` markers are written as words, and an id that refers to an entry is written as its title.

On a real 106-leaf export this kept 21 leaves in 8 documents.

See what is kept and dropped, with no model:

```bash theme={null}
PYTHONPATH=ladygraph python -m sources.auto --file <config.json> [--all]
PYTHONPATH=ladygraph python -m sources.auto --file <config.json> --misses
```

`--misses` lists the fields that were dropped although their value reads as language, and exits with status 1 when there are any. A name you list in `knowledge_names` always counts as knowledge.

> [!NOTE]
>
> Run these modules as `python -m sources.<module>` with the `ladygraph/` folder on `PYTHONPATH`, as above, or import `sources.<module>`. Never run them from inside the `sources/` folder, whose `json.py` and `pydantic.py` would hide the standard `json` module.

#### Declared concepts

An entry that a person already described does not need a model. A routing rule, a glossary term or a taxonomy has a name and the words people use for it, and an LLM only turns those into fragments. With `auto`, an entry that has a title and keyword lists but no prose is declared, and `DeclaredExtractor` makes exactly one concept from it, with no LLM call.

* The title is the concept.
* The keywords and aliases are its user words, stamped as human-declared.
* Its description repeats a sample of the keywords, so the vector and the decider read them too.

Search matches a question against those words. A concept whose keyword is in the question is returned with a fixed score of 0.9, whatever the decider said, and the hit's path shows the word that matched. Matching ignores case and accents, takes whole words, and understands `a & b & !c` clauses. Entries with prose still go to the LLM, so one source can hold both: `DeclaredOrLlm(DeclaredExtractor(...), LlmOkfExtractor(...))`. Set the ontology type of declared concepts with `auto: {types: {"query route rules": routing}}`.

On the sample blueprint, 6 of 8 entries cost no LLM calls.

#### Contact details

An e-mail address or phone number is context for a concept, not a concept. An extractor refuses a candidate whose name or quote is only a contact detail. The sentence that holds one becomes extra evidence of the larger concept it elaborates, with no model call. A hit shows it when more than one evidence pointer is asked for (`SearchConfig.max_evidence`). To keep contact details away from a model, mask them with `auto: {redact: [email, phone]}`. Masking is off by default.

#### Triage

Listing `exclude:` fields by hand does not scale either, so a decision model can judge them. Add `triage: {cache: triage.json}` and run this once:

```bash theme={null}
PYTHONPATH=ladygraph python -m sources.triage --config ladygraph/tutorial/04_sources/flat/ladygraph.yaml --scope finance --decider lite
```

A decider (DecisionLite, Clef or an LLM judge) answers one question per kind of field, such as "Field `notify` of an escalation rule: it holds an e-mail address. Knowledge or a setting?". The answers go into `triage.json`, one per kind of field and not per value. Every later run reads that file and calls no model.

The saved file is what keeps the index correct. Flattened text is fingerprinted and read again at search time, so a model that answered differently on a later run would make valid evidence look stale. Review the file and change `keep` to override a decision, or delete an entry to decide it again. A field is dropped only when the model is confident it is a setting (`drop_threshold`, default 0.7). An unsure answer or a model error keeps the field.

#### Reading an entry as prose

A flattened entry is `label: value` lines. A rule, or `auto:`, with `rewrite: true` makes `ReadingExtractor` ask the LLM, once per entry, to write it as cohesive prose. The extractor reads that text next to the passages. It is context and never evidence: quotes must still be copied from the passages.

Text in quotation marks is what a person wrote as a term. Each quoted term becomes a user word on the concept whose evidence is nearest. Give `ReadingExtractor` its own client with a small `max_output_tokens`.

### Markdown

A markdown file keeps its words as written. Front matter gives the title, validity, access labels and metadata. Headings split the file into Documents at `split_level`, and a code fence or table stays in one block.

| Front matter | Becomes |
| - | - |
| `title` | The Document title |
| `access_labels` (or `confidentiality`) | Access labels |
| `valid_from` (or `effective_date`), `valid_until` (or `expiry_date`) | The validity period |
| `status` | A `draft` or `deprecated` file is skipped |
| Any other key | Metadata |

The `file` version hashes the title, anchors and text, so any edit replaces the unit. The `metadata` version hashes metadata, access labels and validity, so a change there only re-opens context choices.

### pydantic

`provider: package.module:function` is called with the scope and returns a model. It is dumped with `model_dump(mode="json")`, so the same rules work on a file or on the model. Values equal to their default stay, because a default such as `route: direct` is still a setting. Set `exclude_defaults: true` to leave them out. In a host application, a provider such as `host_app.services.settings:load_settings` reads the live settings of a domain.

## Several sources in one scope

`run_update` compares a source's manifest with every unit stored in the scope. A second source run into the same scope would see the first one's units as deleted and drop them. Present them as one with `CombinedSource(*sources)` from `sources/combined.py`. Two sources must not produce the same unit.

## Long text: chunking

A long, loosely structured text, such as OCR or a converted PDF, needs cutting into passages that know their heading path. Put `chunking:` on a markdown source entry.

```yaml theme={null}
sources:
  - name: policy
    kind: markdown
    scheme: pol
    path: docs/*.md
    chunking: {ranks: ['Section\s+\d+\.', '\d+\.\s', '[a-z]\)'], body_starts_at_rank: 0, end_pattern: 'Distribution:'}
```

The chunker drops stamps, keeps short clauses, repairs table fragments, and flags chunks for review. Every language- or document-specific rule is configuration, not code. A pattern that cannot compile, or that matches the empty string, is refused when the config loads.

> [!WARNING]
>
> The chunker was tuned on one document. `docs/chunking.example.yaml` is that document's configuration. On it the chunker reproduces the experiment's output exactly (88 of 88 chunks) when `CHUNK_PARITY_DIR` points at the experiment. Re-joining a phrase that the OCR cut over several table columns is not ported.

## Entity kinds

An optional `entities:` section names things a deployment's documents contain and explains them: document codes, form codes, decision numbers and abbreviations. A kind is data, so a new kind is a new entry in the config. See [Entity kinds](https://ladygraph.io.vn/guides/entity-kinds.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.