Metadata-Version: 2.5
Name: laya-weights
Version: 0.1.2
Summary: Run laya without Hugging Face access: pip install laya-weights and laya.load() works offline
Project-URL: Model (Hugging Face), https://huggingface.co/convaiinnovations/laya
Project-URL: laya on PyPI, https://pypi.org/project/laya/
Project-URL: laya-weights guide, https://pypi.org/project/laya-weights/
Author: Aleeza Noor
Maintainer: Aleeza Noor
License-Expression: Apache-2.0
Keywords: agent-routing,huggingface,laya,offline,weights
Requires-Python: >=3.8
Requires-Dist: laya
Requires-Dist: laya-weights-part-00==0.1.0
Requires-Dist: laya-weights-part-01==0.1.0
Requires-Dist: laya-weights-part-02==0.1.0
Requires-Dist: laya-weights-part-03==0.1.0
Requires-Dist: laya-weights-part-04==0.1.0
Requires-Dist: laya-weights-part-05==0.1.0
Requires-Dist: laya-weights-part-06==0.1.0
Requires-Dist: laya-weights-part-07==0.1.0
Requires-Dist: laya-weights-part-08==0.1.0
Description-Content-Type: text/markdown

# laya-weights

Run [laya](https://pypi.org/project/laya/) without access to the Hugging Face Hub, with a
fine-tune for routing user queries to the right tool or agent.

laya normally downloads its model from Hugging Face the first time you use it. Many organisations
allow `pip install` (directly or through an internal mirror such as Artifactory or Nexus) but block
Hugging Face, so laya fails there. This package ships laya's English checkpoint through pip instead:

```bash
pip install laya-weights
```

That's all. Your existing laya code works unchanged and never contacts Hugging Face for this model.

**Maintainer:** Aleeza Noor

## Quick start

**1. Install** (about 855 MB download, plus `laya` and its dependencies such as torch):

```bash
pip install laya-weights
```

**2. Run the built-in example**, which routes eight queries across eight tools:

```bash
python -m laya_weights.example
```

```
docs_search     95%        <- how do I rotate the API keys for the payments service?
pipeline_db     98%        <- check pipeline orders_daily_etl
infra_metrics  100%        <- get infra metrics for prod-cluster-2
sql_analytics   95%        <- how many orders did we get last week
log_search      99%        <- show errors from auth-service in the last 15 minutes
ticketing       18% (low)  <- create an incident, checkout is down
deploy          96%        <- roll back the checkout service
web_search      33% (low)  <- what's new in postgres 17
```

Each line is the chosen tool, the model's confidence in it, and the query. Try your own:

```bash
python -m laya_weights.example "is the nightly export done yet"
```

The first run takes a little longer while the weights are unpacked (see [How it works](#how-it-works)).

## Route queries to tools and agents

Describe each tool in a sentence, then ask which one a query belongs to. One model call, no LLM,
no network:

```python
from laya.integrations.tools import LayaToolSelector
import laya_weights

TOOLS = {
    "docs_search": "Search internal documentation, runbooks and how-to guides. For 'how do I...' questions.",
    "pipeline_db": "Look up a data pipeline or job in the NoSQL store: status, last run, failures, owner.",
    "infra_metrics": "Fetch live infrastructure metrics: CPU, memory, disk, latency, node health.",
}

selector = LayaToolSelector(
    tools=[{"name": name, "description": text} for name, text in TOOLS.items()],
    agent=laya_weights.load_routing_agent(),   # load once and reuse; takes several seconds
)

decision = selector.select("check pipeline orders_daily_etl")
print(decision.tool_name, round(decision.confidence, 2))   # pipeline_db 1.0
```

`laya_weights.load_routing_agent()` returns laya's English checkpoint with this package's
tool-routing fine-tune applied. Plain `laya.load()` also works here but routes much less
accurately (see the table below).

**Python functions as tools.** Pass the functions themselves; the name and the first docstring
line are used, and `decision.tool` is the function to call:

```python
def get_pipeline_status(name: str) -> dict:
    """Look up a data pipeline or job in the NoSQL store: status, last run, failures, owner."""

def get_infra_metrics(target: str) -> dict:
    """Fetch live infrastructure metrics: CPU, memory, disk, latency, node health."""

selector = LayaToolSelector(tools=[get_pipeline_status, get_infra_metrics],
                            agent=laya_weights.load_routing_agent(),
                            allow_direct_answer=True)       # adds a "no tool needed" option
decision = selector.select("is the nightly_snapshot job done")
if decision.is_direct_answer:        # greetings, thanks, small talk
    ...
else:
    result = decision.tool("nightly_snapshot")
```

`LayaToolSelector` is part of laya and also accepts LangChain, CrewAI and LlamaIndex tool objects
and OpenAI-style function specs; this package's tests cover the dict and function forms above.

**Tips**

- Describe the questions a tool answers, not the technology behind it. Users type
  "check pipeline X", never "query the NoSQL store".
- Keep descriptions distinct. If two tools could both claim a query, say in each which cases it owns.
- Use the confidence, with care. When it is low (under about 0.5), ask the user to clarify or
  hand the query to an LLM rather than calling the tool. A high value is not a guarantee: several
  of the misses in the test below were confident ones.
- The fine-tune was trained on 2 to 12 tools per call and measured on 7 and 8.

### Measured accuracy

`tests/routing_eval.py` routes 121 hand-written queries that are not in the training data:

| Test set | Stock `laya.load()` | `load_routing_agent()` |
|---|---|---|
| 86 queries over 8 ops tools (docs, pipelines, metrics, SQL, logs, tickets, deploys, web) | 30 correct (35%) | 76 correct (88%) |
| 35 queries over 7 assistant tools (calendar, email, calculator, weather, flights, notes, music) | 26 correct (74%) | 32 correct (91%) |

The assistant tools appear nowhere in the training data, so that row measures routing over tools
the model has never seen. Tools of the same kinds as the ops set were in the training data under
different names, descriptions and queries. Both sets are small, so read the numbers as "roughly
nine in ten", and measure on your own queries before relying on it.

## Using laya for anything else

Scores, yes/no questions and other typed decisions use the stock checkpoint, exactly as laya
documents, with no Hugging Face access:

```python
import laya
agent = laya.load()
```

The routing fine-tune was trained only on "pick one option" questions, so keep `laya.load()` for
everything else.

## Installing on a machine with no internet

On a machine that can reach PyPI, download every wheel:

```bash
pip download laya-weights -d laya-wheels
```

Copy the `laya-wheels` folder across, then install from it:

```bash
pip install --no-index --find-links laya-wheels laya-weights
```

Download on the same OS and Python version as the target machine, because laya's dependencies
(such as torch) have platform-specific wheels.

## Docker

```dockerfile
FROM python:3.11-slim
RUN pip install --no-cache-dir laya-weights \
 && python -m laya_weights          # unpack the weights at build time, not at first request
```

## How it works

- PyPI rejects files over 100 MB, so the 843 MB `model.safetensors` ships as 9 small
  `laya-weights-part-NN` packages that `laya-weights` depends on.
- On first load, the parts are joined back into one file in `~/.cache/laya-weights`, checked
  against a SHA-256 and reused afterwards. Run `python -m laya_weights` to do this ahead of time
  (it prints the folder).
- A small startup hook catches laya's Hugging Face download request for this checkpoint and serves
  it from that folder. Requests for other models still go to Hugging Face as normal.
- The routing fine-tune is an 85 MB file inside `laya-weights` itself: a new decision head plus a
  low-rank update to the rest of the model. `load_routing_agent()` loads the stock checkpoint and
  applies that update in memory, so the stock weights on disk are never changed.

## Configuration

| Setting | Default | Purpose |
|---|---|---|
| `LAYA_WEIGHTS_HOME` | `~/.cache/laya-weights` | Where the joined weights are stored. Point it at a writable folder if your home directory is read-only. |

Disk space: about 1.8 GB in total (the installed packages plus the joined copy).

## Troubleshooting

- **laya still tries to reach Hugging Face.** Check that `laya-weights` is installed in the same
  environment as your code (`pip show laya-weights`), and that you're using the default English
  checkpoint (`laya.load()` with no model name).
- **`rebuilt model.safetensors fails its SHA-256 check`.** A part is corrupt or from a different version.
  Run `pip install --force-reinstall laya-weights`.
- **Permission error on first load.** Set `LAYA_WEIGHTS_HOME` to a writable folder.
- **`the routing weights do not fit this laya version`.** A newer laya changed the model layout.
  Pin the laya version this release was tested with (below) or upgrade `laya-weights`.

## Limitations

- English only. The multilingual and typed-decisions checkpoints are not included, and `Router()`
  sends non-English text to the multilingual checkpoint, which still needs Hugging Face.
- The routing fine-tune was trained on generated examples (86 tools across 19 domains) and
  measured on the 121 queries above. Expect lower accuracy on tool sets or phrasing far from those.
- The shipped routing update is a compressed form of the fine-tune. The uncompressed model scored
  79 of 86 on the ops set; the shipped one scores 76.
- Routing confidence was calibrated before that compression, so treat it as a ranking signal and
  pick your threshold on your own data.
- Tested with laya 0.4.37 (the offline loading of the stock checkpoint also with 0.4.34).

## Building and releasing (maintainers)

```bash
pip install build hatchling twine huggingface_hub
python -c "from huggingface_hub import snapshot_download as s; s('convaiinnovations/laya', revision='55cf4c4ebb4ebe31b2550e8bdf3bd21b99753851', local_dir='hf_snapshot', allow_patterns=['rl_agent_config.json','model.safetensors','tokenizer/*','encoder/*'])"
python build_weights.py --version 0.1.2 --parts-version 0.1.0
pip install dist/*.whl && python -m pytest tests
twine upload dist/laya_weights-0.1.2-py3-none-any.whl
```

For a docs or code change, keep `--parts-version` on the published parts and upload only the
`laya_weights` wheel. Bump the parts only when the stock weights change.

**Re-training the routing fine-tune** needs a GPU with about 16 GB of memory:

1. `python make_colab_notebook.py`, then run `finetune_routing_colab.ipynb` on a Colab T4
   (about 40 minutes). It trains, scores the result and downloads `routing_finetune.zip`.
2. Unzip it and run `python finetune_routing.py --pack-only --rank 32 --out <unzipped>/routing_ckpt`,
   which writes `src/laya_weights/routing/`.
3. `python tests/routing_eval.py` to check accuracy, then build and release as above.

The training data is generated by `finetune_routing.py` from its `CATALOG` of tools and queries;
add your own tools there to specialise the fine-tune.
