laya-php: Laravel-ready PHP SDK for classifying text with self-hosted Laya, advertised…
Classify text in PHP without an LLM bill: typed decisions in 100+ languages, self-hosted. Laravel-ready SDK for Laya, a Jev AI alternative.
**Classify text in PHP without paying for an LLM API.** Route support tickets, spot churn risk and score urgency, in 100+ languages, on your own server, and get the answers back as typed enums, ints and bools.
```php
$triage = $laya->decide('Hi, we were billed twice for March. Refund it today or we cancel.', Triage::class);
$triage->department; // Department::Billing
$triage->churn; // true
```
- **Self-hosted:** the text never leaves your infrastructure, and you pay no per-token fees.
- **Typed:** describe a decision as a readonly class with enums and get an instance back.
- **Calibrated:** every answer has a confidence you can threshold on to send unsure cases to a human.
- **Testable:** a built-in fake lets you unit-test without a running server.
Under the hood this is an SDK for [Laya](https://github.com/NandhaKishorM/laya), a multilingual decision engine that answers typed questions (`choice`, `score`, yes/no) about any text in a single forward pass. Laya runs in Python, so the SDK talks to [`laya-serve`](https://github.com/NandhaKishorM/laya/blob/main/docs/docker.md), Laya's HTTP server, over any PSR-18 client.
**Looking for Jev?** `laya-serve` speaks the same `POST /v1/systemone` protocol as TypeSafe's hosted [Jev](https://github.com/NandhaKishorM/laya#self-hosting-http-server-jev-compatible) API, with the same `choice`/`score`/`noul` answers, so this package is also a self-hosted Jev AI alternative for PHP. It targets `laya-serve`, and CI checks its requests and responses against TypeSafe's [OpenAPI spec](https://api.typesafe.ai/openapi.json) on every change and weekly, so other `/v1/systemone` servers such as [sys1](https://github.com/alvarobartt/sys1) work too. It hasn't been tested against the hosted Jev API itself.
## Installation
```bash
composer require marcreichel/laya-php
```
PHP 8.4+. You also need a PSR-18 HTTP client (Guzzle, Symfony HttpClient, …). The SDK finds the installed one automatically.
To run `laya-serve` locally, use the `compose.yaml` in this repository (it pins upstream Laya to v0.4.0, commit [`3cf26cb`](https://github.com/NandhaKishorM/laya/commit/3cf26cbcb18725dbc2d127bb8bb2c4c43243ae63)) or follow [Laya's Docker guide](https://github.com/NandhaKishorM/laya/blob/main/docs/docker.md):
```bash
docker compose up -d --wait # http://localhost:8000
```
Runnable scripts are in [`examples/`](examples). Set `LAYA_URL` (and `LAYA_API_KEY`) if your server isn't on `localhost:8000`. `05-testing-with-fake.php` runs without a server.
### Laravel
For Laravel 13+, the service provider is auto-discovered. It registers `Laya` as a singleton, configured from your `.env`:
```dotenv
LAYA_URL=http://localhost:8000
LAYA_API_KEY=
LAYA_CACHE_STORE= # e.g. redis, to cache predictions (see Caching)
LAYA_CACHE_TTL= # seconds
LAYA_EVENTS=true # dispatch PredictionMade/PredictionFailed/CacheFailed (see Events)
LAYA_EVENTS_INCLUDE_STATE=false
```
`php artisan laya:health` prints the server's status and loaded checkpoints (plus the idle-unload window and idle time when laya-serve runs with `LAYA_IDLE_UNLOAD_SECONDS`, since an idle unload leaves "Loaded: none" on a healthy server), and exits with 1 when it is unreachable or unhealthy, so you can use it in deploy checks.
`php artisan laya:try` runs a [decision class](#decisions-into-objects) on a piece of text and shows each parameter's question, hydrated value (`null` below `minConfidence`), answer confidence and the probability of every option, plus the routed checkpoint and a warning when the text was cut off. Use it to iterate on `#[Ask]` and `#[Describe]` wording:
```bash
php artisan laya:try "App\Decisions\Triage" "Hi, we were billed twice for March. Refund it today or we cancel."
php artisan laya:try "Decisions\Triage" --file=ticket.txt # short names resolve under App\
echo "..." | php artisan laya:try "Decisions\Triage" --model=multilingual --json
```
It takes `--model=`, `--max-len=`, `--head-max-len=` and `--json`, and exits with 1 for an unknown or invalid class or an unreachable server.
Inject it wherever you need it:
```php
use MarcReichel\Laya\Laya;
final class ClassifyTicket implements ShouldQueue
{
use Queueable;
public function __construct(public Ticket $ticket) {}
public function handle(Laya $laya): void
{
$triage = $laya->decide($this->ticket->body, Triage::class);
$this->ticket->update(['department' => $triage->department]);
}
}
```
To change the config file, publish it with `php artisan vendor:publish --tag=laya-config`. In tests, `Laya::fake([...])` also replaces the container's instance, so injected code gets the fake (see [Testing your code](#testing-your-code)):
```php
$laya = Laya::fake(['department' => Department::Billing, 'urgency' => 2, 'churn' => true]);
ClassifyTicket::dispatchSync($ticket);
$laya->assertPredictedCount(1);
```
## Asking questions
```php
use MarcReichel\Laya\Laya;
use MarcReichel\Laya\Question;
$laya = new Laya('http://localhost:8000', apiKey: getenv('LAYA_API_KEY') ?: null);
$result = $laya->predict($ticketText, [
'department' => Question::choice('Which department should handle this?', [
'billing' => 'invoices, payments, refunds',
'technical' => 'bugs, outages, system errors',
'other' => 'everything else',
]),
'urgency' => Question::score('How urgent is this?', ['not urgent', 'soon', 'blocking']),
'churn_risk' => Question::yesNo('Does the user threaten to cancel or leave?'),
]);
$result->choice('department')->choice; // 'billing'
$result->choice('department')->probabilities; // ['billing' => 0.91, 'technical' => 0.06, 'other' => 0.03]
$result->score('urgency')->level(); // 2: the most likely level
$result->score('urgency')->label(); // 'blocking'
$result->score('urgency')->score; // 1.74: the expected level
$result->yesNo('churn_risk')->yes(); // true
$result->yesNo('churn_risk')->probability; // 0.83
$result['department']; // ArrayAccess works too (returns the base Answer type)
$result->routedModel; // 'english': the checkpoint laya picked
```
The three question types:
| Factory | Options | Answer |
|---|---|---|
| `Question::choice($instructions, $options)` | a list of labels, or `label => description` | `ChoiceAnswer`: `choice`, `probabilities`, `is($label)` |
| `Question::score($instructions, $levels)` | level descriptions, lowest first | `ScoreAnswer`: `score`, `level()`, `label()`, `probabilities`, `legend` |
| `Question::yesNo($instructions, yes: …, no: …)` | optional descriptions of yes and no | `YesNoAnswer`: `probability`, `yes($threshold = 0.5)`, `no()` |
Every answer also has `confidence` and `answerConfidence`. `answerConfidence` is the calibrated one and is comparable across question types, so use it to decide when to trust an answer:
```php
if ($result->choice('department')->answerConfidence sendToHumanTriage();
}
```
Servers that only follow TypeSafe's [OpenAPI spec](https://api.typesafe.ai/openapi.json), such as [sys1](https://github.com/alvarobartt/sys1), don't send an `answer_confidence`. Then `answerConfidence` falls back to `confidence`, and a yes/no answer without a `confidence` gets laya's own `max(P(yes), P(no))`. Thresholds and `minConfidence` keep working, though `confidence` is stricter than the calibrated value for choice and score answers. The same applies to laya-serve 0.3.24 or later started with `LAYA_JEV_STRICT=1`, which strips `answer_confidence`, `routing` and the truncation report from its responses, so `routedModel` is `null` and `truncated` is always `false` there.
### Abstention on the server
laya-serve can gate answers itself. Pass `minConfidence`, and every answer reports how the gate decided it, measured on `answerConfidence`:
```php
use MarcReichel\Laya\Abstention;
$result = $laya->predict($ticket, $questions, minConfidence: 0.7);
$result->choice('department')->abstention; // Abstention::Abstained
$result->choice('department')->abstentionThreshold; // 0.7
$result->choice('department')->lowConfidence; // true: below the threshold
$result->choice('department')->choice; // 'billing': laya keeps the answer either way
```
`abstention` is `Passed`, `Abstained`, or `Unevaluated` when the answer carried no usable confidence. Without `minConfidence`, it and `abstentionThreshold` are `null` and `lowConfidence` is `false`.
One threshold doesn't transfer across option counts, so laya-serve 0.3.25 and later also take a threshold per type and option count (`2`, `3-5`, `6-10` or `11+`), with `default` for the rest. Fit one with `laya.calibrate.fit_abstention_thresholds`:
```php
$laya->predict($ticket, $questions, minConfidence: ['choice:3-5' => 0.6, 'noul:2' => 0.8, 'default' => 0.7]);
```
`predictMany()`, `decide()` and `decideMany()` take `minConfidence` too. A threshold outside 0 to 1, an empty map or a bucket laya doesn't know throws an `InvalidOptionException` before anything is sent. `#[Ask(minConfidence: ...)]` on a [decision class](#decisions-into-objects) is a separate gate, on the client: it turns the parameter into `null`.
### State
`state` can be a string, an array (a JSON document, or a list of conversation turns), or any `JsonSerializable`, such as your own models:
```php
$laya->predict(['subject' => $mail->subject, 'body' => $mail->body], $questions);
```
### Picking a checkpoint
By default, laya's router picks a checkpoint by language: text identified as English goes to the `english` checkpoint, everything else to `multilingual`. Since Laya 0.4.0 that includes text whose language it can't identify, such as very short text, text without letters (`"12345 !!!"`) or a few Latin-script content words (`"Quero cancelar"`); before, those went to `english`. For mostly-English traffic, start laya-serve with `LAYA_DEFAULT_MODEL=english` to restore the old behaviour (upstream puts the break-even at about 62% English). The request carries `"model": "jev-latest"`, since TypeSafe's spec requires a model name: laya-serve routes for names it doesn't know, and sys1 reads it as the model it serves. To pin one:
```php
use MarcReichel\Laya\Model;
$laya->predict($text, $questions, model: Model::Multilingual);
```
### Long documents
Laya cuts the state off at the checkpoint's default length (512 or 1,024 tokens). With laya-serve 0.3.21 or later you can raise it per request with `maxLen`, and give questions with many or long options more room with `headMaxLen`:
```php
$laya->predict($contract, $questions, maxLen: 4096);
$laya->decide($ticket, Triage::class, headMaxLen: 384);
```
laya-serve caps both at `LAYA_MAX_TOKEN_BUDGET` (8,192 by default) and answers anything above it with a `ValidationException`.
From laya-serve 0.3.22, `$result->truncated` tells you whether the state was cut off, so you know when to raise `maxLen`:
```php
$result = $laya->predict($contract, $questions);
if ($result->truncated) {
$result = $laya->predict($contract, $questions, maxLen: 4096);
}
```
### Batches (experimental)
`predictMany()` and `decideMany()` ask the same questions about many states, which laya-serve 0.3.22 and later answers in shared forward passes. Results keep the keys you pass in:
```php
$results = $laya->predictMany($tickets->pluck('body', 'id')->all(), $questions);
$results[42]->choice('department');
$triages = $laya->decideMany($tickets->pluck('body', 'id')->all(), Triage::class, maxLen: 4096);
```
Cached states aren't sent again, identical states in one call are sent once and share the result, and the rest go out in requests of at most 64 distinct states. One state that laya-serve rejects fails the whole request, the same way `predict()` throws. `maxLen` and `headMaxLen` apply to every state in the batch and need laya-serve 0.3.23; older servers ignore them. A laya-serve older than 0.3.22 answers with a `ServerException` that names the version it needs.
Both methods are experimental and may


