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

# Term-list builder

> Build a proposed glossary with an agent, then approve what you trust.

A small translator gets domain terms wrong: acronyms such as "KPI", unit names such as "Hội Đồng Rủi Ro", and words that mean something special in your documents. A term list fixes that, but writing hundreds of entries by hand is slow.

The `authoring` module builds a *proposed* term list for you and makes sure nothing in it is trusted until a person says so. It is a side tool. It writes config for a deployment, and nothing imports it when the index runs.

In these examples the documents are Vietnamese, the source language, and the translator turns them into English, the target language. The candidates and the glossary keys are Vietnamese terms found in the source text. The `en:` field holds the English each one must become.

## How a term list is built

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant P as Passages
    participant C as Candidate finder
    participant A as Agent (Claude Code)
    participant W as Web search
    participant R as Repair and cap
    participant G as glossary.proposed.yaml
    actor H as A person
    participant T as Translator gate

    P->>C: passage text
    C->>A: candidate terms
    loop each candidate
        A->>W: look the term up (a term only, never document text)
        W-->>A: what the term means
        A->>A: decide this term
    end
    A->>R: the agent's answer (may be messy)
    R->>R: repair it and cap the list
    R->>G: write entries, every one marked "proposed"
    Note over G,T: a proposed term is only a hint to the model
    H->>G: approve command
    G->>T: approved terms
    Note over T: an approved term is enforced by the gate
```

**1. Find candidates**

The builder does not ask a model about every word. It first finds candidates with patterns: acronyms and runs of capitalized words. A candidate must appear in at least `min_count` passages (default 2), so one-off words are skipped. The list is capped at `max_terms` (default 90).

The patterns find source-language terms only. The default patterns also accept `Đ`, but cover only plain capital letters otherwise, so a term that starts with an accented capital such as `Ủy Ban` is missed. A lowercase domain word is never proposed unless you add a pattern.

**2. Let the agent decide each term**

The agent is headless Claude Code (`claude --bare`) with only the `Read` and `Edit` tools, plus the guarded search tool when search is on. Its model is served by a gateway you run. It reads `candidates.txt` and `document_chunks.txt`, decides each term, and appends entries to `lexicon_out.yaml`.

**3. Make the answer safe**

Code repairs the agent's YAML (for example an unquoted colon), drops terms nobody asked about, and caps confidence. A `high` confidence stays only if a search for the term was logged, or the documents spell the term out, as in "Kế hoạch kinh doanh (KHKD)". Otherwise it becomes `medium`. A term with no English is marked `low` and left for a person.

**4. Approve**

Every entry is written with `status: proposed`. A person reads the file and approves what they trust. The translator's gate then enforces the approved terms.

### Proposed and approved terms

| Status | What the translator does with it |
| - | - |
| `proposed` | Shows the term to the model as a hint. The gate ignores it. |
| `approved` | The gate enforces it. A translation that drops an approved term is flagged. |

## The web search is guarded

The agent may look up public terms on the web, but a query may only be a term: at most 4 words and 40 characters, on one line. Code enforces the rule, not the prompt. A model that tries to paste a passage into a search gets `REFUSED`, and the query never reaches the search provider.

An accepted query is sent to Tavily (`api.tavily.com`) with the key from the variable named in the config, which defaults to `TAVILY_SEARCH_API`. That is a network call. Every query is logged, and the log is how `high` confidence is earned. Search is off by default in the tutorial config.

## Run it

The builder needs the `claude` CLI on your path, a model endpoint, and a `glossary_builder:` section in your `ladygraph.yaml`.

**1. Check the setup**

```bash theme={null}
python -m ladygraph.authoring doctor --config ladygraph.yaml
```

`doctor` checks the `claude` CLI, that the endpoint answers with your key, that it serves the engine you configured, and that the search key is set. It sends no model request.

**2. Preview the candidates**

```bash theme={null}
python -m ladygraph.authoring build --config ladygraph.yaml --source policies --dry-run
```

A dry run lists the candidates and the command it would run, and runs nothing. Use `--texts FILE...` instead of `--source` to read plain text or markdown files.

**3. Build**

```bash theme={null}
python -m ladygraph.authoring build --config ladygraph.yaml --source policies --out glossary.proposed.yaml
```

This runs the agent. It calls your gateway and spends tokens, and it can take a few minutes. If you leave out `--out`, the file goes to the `output:` path in the config, which is relative to the folder you run the command from.

**4. Approve**

```bash theme={null}
python -m ladygraph.authoring approve --in glossary.proposed.yaml --confidence high
```

You can also approve by term: `--terms KPI KHKD`.

### Watch the agent work

While the agent runs, `build` prints what it does on stderr, one line per step, with the seconds since the start. Before the agent starts, it prints the work folder and what each file in it is for.

```text theme={null}
[    0s] the agent works in this folder: /…/work
[    0s]   candidates.txt        the terms to decide, found in your passages
[    0s]   document_chunks.txt   your passages, for context
[    0s]   lexicon_out.yaml      the agent's answer: it adds one entry per term here
[    2s] -> read candidates.txt
[    2s] -> search the web for 'KPI'
[    2s] -> edit lexicon_out.yaml (+2 entries)
[    2s]    says: Wrote 2 entries.
[    2s] agent finished: 4 turns, 3 s
```

A path inside the work folder is shown relative to it. A file anywhere else is shown with its full path.

| Flag | What it adds |
| - | - |
| `--trace` | The agent's thinking (`thinks:`) and each tool result (`result:`). Thinking appears only if the model returns it. |
| `--quiet` | Nothing while the agent runs, only the final summary. |

The raw events are always kept in `harness.jsonl` in the work folder.

## Configure it

The builder reads a `glossary_builder:` section of your `ladygraph.yaml`.

```yaml theme={null}
glossary_builder:
  runner: claude_code
  engine: my-fast-model            # the model name your endpoint serves
  gateway:
    base_url: http://127.0.0.1:4000
    api_key_env: LADYGRAPH_GATEWAY_KEY    # the NAME of an environment variable
  source_language: Vietnamese
  target_language: English
  search:
    provider: none                 # none or tavily
    api_key_env: TAVILY_SEARCH_API
  candidates:
    ignore: ['^(STT|HUNG)$']       # stamps and form words that are not terms
    min_count: 2
    max_terms: 90
  limits: {max_turns: 160, timeout_s: 3600, max_document_chars: 120000}
  output: glossary.proposed.yaml
```

> [!NOTE]
>
> A key never goes in the config. `api_key_env` names the environment variable that holds it. Leave the setting out if your endpoint does not check keys.

A thinking-off model alias is much faster for this job.

### The gateway

The model endpoint is yours to run, outside ladyGraph. ladyGraph ships no gateway, starts none, and depends on no gateway library. The endpoint must provide:

* The Anthropic Messages API at `<base_url>/v1/messages`, including tool use. Claude Code sends its requests in this format. A gateway that translates to another provider, such as LiteLLM, is fine if the model behind it can call tools.
* A model list at `<base_url>/v1/models` in OpenAI style. Only `doctor` uses it, to check that `engine` is served.

> [!WARNING]
>
> Bind the endpoint to localhost. It can spend money and reach your models.

> [accordion] The agent fails on its second turn with a 500 error
>
> Claude Code resends the model's earlier thinking on every turn after a tool call. With LiteLLM in front of the `nvidia_nim` models, a request whose history holds a thinking block returned `500 'NoneType' object has no attribute 'choices'`. The same request without the block worked.
>
> The fix was a small LiteLLM callback that removes `thinking` blocks from the request history. The tutorial ships it as `strip_thinking.py` in `ladygraph/tutorial/07_translation/liteLLMExample/`. Restart the proxy after changing its config. Other gateways and models may behave differently.

## Use the term list in translation

Two hooks connect a glossary to the translate-then-tag extractor (`translate_ner`). The code does not connect them for you.

* **`hints`** passes the glossary terms found in each passage into the translation prompt. `term_hint(text, glossary)` builds the note, and it includes both proposed and approved terms.
* **`check`** adds the gate. `make_check(glossary)` flags a translation that drops an approved term, and the line is then escalated to the stronger model.

```python theme={null}
from ladygraph.extractors.build import build_extractor
from ladygraph.project import load_glossary
from ladygraph.translation import make_check, term_hint

glossary = load_glossary("ladygraph.yaml")
extractor = build_extractor("ladygraph.yaml", llm=..., tagger=...,
                            hints=lambda text: term_hint(text, glossary),
                            check=make_check(glossary))
```

The tagger never reads the glossary. Terms reach it only through the translation. The gate was written for one language pair, so check it against yours.


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