Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

Merge pull request #822 from aashish254/fix-sdk-answer-confidence

Nandakishor1dffb9081ee6
diff --cc docs/typescript-sdk.md
index 60a6a4a3,fe5ca46d..7f8a2e39
--- a/docs/typescript-sdk.md
+++ b/docs/typescript-sdk.md
@@@ -39,27 -39,17 +39,32 @@@ arrays are normalized to maps with nul
Responses preserve `model`, `answers`, and token `usage`. Laya's `routing` and
answer `action` fields are optional extensions; Noul confidence is optional too.
Choice and Score confidence, distributions, and Score legends remain required.
+ Every answer carries `answer_confidence`, the `max(p)` mass on the reported answer,
+ which is the same quantity on all three question types. A call that passed
+ `min_confidence` reports `abstention` and `abstention_threshold` on each of its
+ answers and `low_confidence: true` on the ones below the threshold; with no
+ threshold set, none of those three keys are sent, and that absence is the report.
Optional extensions are validated when present.
-`/v1/systemone` does not expose Python's standalone routing method or `task` and
-`lang` overrides. The SDK rejects those legacy options instead of silently
-ignoring them. Laya's public `/health` returns `status`, `loaded`, and `device`.
-Prediction never probes health first.
+`/v1/systemone` is the only endpoint the client calls, and it has no standalone routing method:
+`laya-client` exposes `predict` and `health` and nothing else, and the live integration test asserts the
+server answers `404` for `/v1/route`. The controls the endpoint does honour are per-request, and each is
+sent only when the caller supplied the option -- an absent option leaves the deployment's own
+`Router(...)` settings in charge instead of overriding them with a client-side default:
+
+| option | request field |
+| --- | --- |
+| `model` | `model` |
+| `task` | `task` |
+| `lang` | `lang` |
+| `langGuess` | `lang_guess` |
+| `maxLen` | `max_len` |
+| `headMaxLen` | `head_max_len` |
+| `minConfidence` | `min_confidence` |
+
+An option that cannot mean anything is refused locally, before the request goes out: a blank `task`, a
+budget that is not a positive integer, a threshold outside `[0, 1]`. Nothing is silently ignored. Laya's
+public `/health` returns `status`, `loaded`, and `device`. Prediction never probes health first.
FastAPI detail strings and validation arrays are preserved as `LayaAPIError`
messages/details. Structured error envelopes from compatible backends are also
diff --cc sdk/typescript/README.md
index c28f6079,c154babc..8676e81f
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@@ -117,10 -117,11 +117,13 @@@ result.answers.urgency.score; // n
result.answers.refund.noul; // number: P(true), from 0 to 1
result.answers.department.probabilities.billing;
result.answers.department.confidence;
+ result.answers.department.answer_confidence; // number: max(p), the same quantity on every type
+ result.answers.urgency.abstention; // 'passed' | 'abstained' | 'unevaluated', with minConfidence
+ result.answers.urgency.low_confidence; // true only on an answer that fell below it
result.answers.department.action?.act_probability; // Laya-only metadata
result.usage.input_tokens;
+result.usage.truncated; // boolean: the state did not fit the room left for it
+result.usage.truncated_questions; // string[]: the questions whose own window was cut
```
Choice criteria also accept an array of unique labels, serialized as an option-to-null
diff --cc sdk/typescript/test/client.test.mjs
index cb367708,b2cec0bb..0fa1a144
--- a/sdk/typescript/test/client.test.mjs
+++ b/sdk/typescript/test/client.test.mjs
@@@ -224,90 -224,80 +224,164 @@@ test('prediction validation rejects mal
}
});
+// The key set is what a live `/v1/systemone` answer carries: both agents build these six keys for
+// any non-empty question set, and `options` joins them when the head budget leaves some question's
+// options sharing a token span (#538). The counts are chosen to exercise a cut state, which a
+// checkpoint that small cannot produce, and both reported `tokens_per_option` shapes.
+const truncationReport = { input_tokens: 43, output_tokens: 0, state_tokens: 120,
+ state_tokens_dropped: 76, truncated: true, truncated_questions: ['refund'] };
+
+test('the truncation report reaches the caller verbatim and is validated when sent', async () => {
+ const reported = structuredClone(prediction);
+ reported.usage = truncationReport;
+ const client = new Laya({ fetch: async () => json(reported) });
+ assert.deepEqual((await client.predict('Hello', questions)).usage, truncationReport);
+
+ const collapsed = structuredClone(reported);
+ collapsed.usage.options = { refund: { total: 4, distinct: 1, tokens_per_option: null },
+ team: { total: 2, distinct: 1, tokens_per_option: 4 } };
+ const collapseClient = new Laya({ fetch: async () => json(collapsed) });
+ assert.deepEqual((await collapseClient.predict('Hello', questions)).usage.options,
+ collapsed.usage.options);
+
+ // a server answering only the two keys Jev decodes is still a valid prediction
+ const legacy = structuredClone(prediction);
+ const legacyClient = new Laya({ fetch: async () => json(legacy) });
+ assert.deepEqual((await legacyClient.predict('Hello', questions)).usage,
+ { input_tokens: 10, output_tokens: 0 });
+
+ // but a half-report is refused rather than passed through as a budget fact
+ for (const mutate of [
+ u => { delete u.input_tokens; },
+ u => { u.state_tokens = '120'; },
+ u => { u.state_tokens_dropped = 76.5; },
+ u => { u.truncated = 'true'; },
+ u => { u.truncated_questions = 'refund'; },
+ u => { u.truncated_questions = [1]; },
+ u => { u.options = []; },
+ u => { u.options = { refund: { total: 4, distinct: 1 } }; },
+ u => { u.options = { refund: { total: 4, distinct: 5, tokens_per_option: 4 } }; },
+ u => { u.options = { refund: { total: 4, distinct: 1, tokens_per_option: '4' } }; },
+ ]) {
+ const bad = structuredClone(reported);
+ mutate(bad.usage);
+ await assert.rejects(new Laya({ fetch: async () => json(bad) }).predict('Hello', questions),
+ LayaResponseError, JSON.stringify(bad.usage));
+ }
+});
+
+// A live `/v1/systemone` answer's `routing.detection`, verbatim, for a state whose subject and
+// notes are English but whose customer message is German. Every branch of `laya.lang.analyse()`
+// reports the same eight keys, which is what tests/test_router.py pins on the Python side;
+// `mixed_segment` is the one that names the segment that pulled the state off English (#384).
+const mixedDetection = {
+ script: 'latin', script_profile: { latin: 1.0 }, language: 'de', is_english: false,
+ language_undecided: false, diacritic_rate: 0.0083, non_latin_fraction: 0.0,
+ mixed_segment: 'Ich möchte meine Bestellung stornieren, danke',
+};
+
+test('routing detection reports the segment that pulled a mostly-English state off English', async () => {
+ const routed = structuredClone(prediction);
+ routed.routing = { ...route, detection: mixedDetection,
+ reason: 'Latin script, mostly English, but a line or field reads as \'de\'' };
+ const client = new Laya({ fetch: async () => json(routed) });
+ const result = await client.predict('Hello', questions);
+ assert.equal(result.routing.detection.mixed_segment, 'Ich möchte meine Bestellung stornieren, danke');
+
+ // null is the ordinary answer: the route read the state as one language
+ const single = structuredClone(routed);
+ single.routing.detection.mixed_segment = null;
+ const singleClient = new Laya({ fetch: async () => json(single) });
+ assert.equal((await singleClient.predict('Hello', questions)).routing.detection.mixed_segment, null);
+
+ // a deployment predating #384 sends no such key, and one display field must not fail the call
+ const older = structuredClone(routed);
+ delete older.routing.detection.mixed_segment;
+ const olderClient = new Laya({ fetch: async () => json(older) });
+ assert.equal((await olderClient.predict('Hello', questions)).routing.detection.language, 'de');
+
+ for (const segment of [7, false, ['Ich'], {}]) {
+ const bad = structuredClone(routed);
+ bad.routing.detection.mixed_segment = segment;
+ await assert.rejects(new Laya({ fetch: async () => json(bad) }).predict('Hello', questions),
+ LayaResponseError, JSON.stringify(segment));
+ }
+});
+
+ // Captured from `tests/sdk_server_fixture.py` over HTTP with `min_confidence: 0.35`, so the three
+ // answer types each carry their real gate report. The counts are what that fixture's random weights
+ // give; `abstention: 'unevaluated'` is not reachable there -- every answer it builds carries a
+ // usable confidence -- so only the two states the gate really reported here are asserted verbatim.
+ const gateQuestions = {
+ team: { type: 'choice', instructions: 'Team?', criteria: ['billing', 'technical'] },
+ urgency: { type: 'score', instructions: 'Urgency?', criteria: ['low', 'medium', 'high'] },
+ refund: questions.refund,
+ };
+ const gateReport = {
+ model: 'laya-rl-agent', usage: { input_tokens: 10, output_tokens: 0 },
+ answers: {
+ team: { type: 'choice', choice: 'technical', probabilities: { billing: 0.4965, technical: 0.5035 },
+ confidence: 0.0, answer_confidence: 0.5035, action: { act_probability: 0.5017 },
+ abstention: 'passed', abstention_threshold: 0.35 },
+ urgency: { type: 'score', score: 1.0105, probabilities: { '0': 0.3338, '1': 0.3218, '2': 0.3444 },
+ legend: { '0': 'low', '1': 'medium', '2': 'high' }, confidence: 0.0003, answer_confidence: 0.3444,
+ action: { act_probability: 0.5238 }, low_confidence: true, abstention: 'abstained',
+ abstention_threshold: 0.35 },
+ refund: { type: 'noul', noul: 0.499, confidence: 0.501, answer_confidence: 0.501,
+ action: { act_probability: 0.3968 }, abstention: 'passed', abstention_threshold: 0.35 },
+ },
+ };
+
+ test('the confidence an answer was gated on and the gate report reach the caller', async () => {
+ const client = new Laya({ fetch: async () => json(gateReport) });
+ const result = await client.predict('hello', gateQuestions);
+ assert.deepEqual(result.answers, gateReport.answers);
+ assert.equal(result.answers.urgency.low_confidence, true);
+ assert.equal(result.answers.urgency.abstention, 'abstained');
+ assert.equal(result.answers.team.abstention, 'passed');
+ assert.equal(result.answers.team.abstention_threshold, 0.35);
+
+ // 'unevaluated' is the third state core reports (laya/confidence.py); accepted like the others.
+ const unevaluated = structuredClone(gateReport);
+ unevaluated.answers.refund.abstention = 'unevaluated';
+ assert.equal((await new Laya({ fetch: async () => json(unevaluated) })
+ .predict('hello', gateQuestions)).answers.refund.abstention, 'unevaluated');
+
+ // An ungated call answers exactly the payload it answered before the gate existed: no abstention,
+ // no threshold, no flag. Absence is the report, so it must not read as a failure.
+ const ungated = structuredClone(gateReport);
+ for (const answer of Object.values(ungated.answers)) {
+ delete answer.low_confidence;
+ delete answer.abstention;
+ delete answer.abstention_threshold;
+ }
+ const bare = await new Laya({ fetch: async () => json(ungated) }).predict('hello', gateQuestions);
+ assert.equal(bare.answers.urgency.abstention, undefined);
+ assert.equal(bare.answers.urgency.low_confidence, undefined);
+
+ // A deployment predating `answer_confidence` (#126) still answers, exactly as it did before.
+ const older = structuredClone(ungated);
+ for (const answer of Object.values(older.answers)) delete answer.answer_confidence;
+ assert.equal((await new Laya({ fetch: async () => json(older) })
+ .predict('hello', gateQuestions)).answers.team.choice, 'technical');
+
+ for (const mutate of [
+ answer => { answer.abstention = 'skipped'; },
+ answer => { delete answer.abstention_threshold; },
+ answer => { answer.abstention_threshold = 1.5; },
+ answer => { answer.abstention_threshold = '0.35'; },
+ answer => { answer.low_confidence = false; },
+ answer => { delete answer.abstention; },
+ answer => { answer.answer_confidence = 'high'; },
+ answer => { answer.answer_confidence = 2; },
+ ]) {
+ const payload = structuredClone(gateReport);
+ mutate(payload.answers.urgency);
+ await assert.rejects(new Laya({ fetch: async () => json(payload) })
+ .predict('hello', gateQuestions), LayaResponseError);
+ }
+ });
+
test('network errors preserve the cause', async () => {
const cause = new TypeError('fetch failed');
await assert.rejects(new Laya({ fetch: async () => { throw cause; } }).health(), error =>
diff --cc sdk/typescript/test/types.ts
index 6569dd6d,b25ae5b1..5dc34bd3
--- a/sdk/typescript/test/types.ts
+++ b/sdk/typescript/test/types.ts
@@@ -1,5 -1,5 +1,5 @@@
-import { Laya, defineQuestions, emailQuestions, triageQuestions,
- type Questions, type Answer, type ChoiceAnswer } from 'laya-client';
+import { Laya, defineQuestions, emailQuestions, triageQuestions, type Questions, type Answer,
- type Usage, type LanguageDetection } from 'laya-client';
++ type Usage, type LanguageDetection, type ChoiceAnswer } from 'laya-client';
const client = new Laya();
const questions = defineQuestions({
@@@ -17,12 -17,26 +17,32 @@@ const noul: number = result.answers.ref
const routingModel: string | undefined = result.routing?.model;
const actionProbability: number | undefined = result.answers.team.action?.act_probability;
const noulConfidence: number | undefined = result.answers.refund.confidence;
+const stateTokens: number = result.usage.state_tokens;
+const stateTokensDropped: number = result.usage.state_tokens_dropped;
+const truncated: boolean = result.usage.truncated;
+const truncatedQuestions: string[] = result.usage.truncated_questions;
+const collapsedSpans: number | null | undefined = result.usage.options?.refund?.tokens_per_option;
+const mixedSegment: string | null | undefined = result.routing?.detection?.mixed_segment;
+ const answerConfidence: number = result.answers.team.answer_confidence;
+ const noulAnswerConfidence: number = result.answers.refund.answer_confidence;
+ const gateState: 'passed' | 'abstained' | 'unevaluated' | undefined = result.answers.priority.abstention;
+ const gateThreshold: number | undefined = result.answers.priority.abstention_threshold;
+ const flagged: true | undefined = result.answers.refund.low_confidence;
+ // @ts-expect-error `flag_low_confidence` writes `True` or writes nothing, so no answer reads false.
+ const flagAsFalse: false | undefined = result.answers.refund.low_confidence;
+ // @ts-expect-error A gate state is one of the three core reports, not any string.
+ const inventedGate: Answer['abstention'] = 'skipped';
+ const gatedAnswer: ChoiceAnswer = { type: 'choice', confidence: 0.5, answer_confidence: 0.42,
+ choice: 'a', probabilities: { a: 0.42 }, low_confidence: true, abstention: 'abstained',
+ abstention_threshold: 0.8 };
+ // @ts-expect-error The gate writes `true` or writes nothing, so a cleared answer has no flag at all.
+ const clearedAnswer: ChoiceAnswer = { ...gatedAnswer, low_confidence: false };
+ // An ungated call is the ordinary answer shape: no flag, no gate state, no threshold echo.
+ const ungatedReport: ChoiceAnswer = { type: 'choice', confidence: 0.5, answer_confidence: 0.42,
+ choice: 'a', probabilities: { a: 0.42 } };
+ // @ts-expect-error An answer must carry the calibrated confidence it was gated on.
+ const uncalibratedAnswer: ChoiceAnswer = { type: 'choice', confidence: 0.5, choice: 'a',
+ probabilities: { a: 0.5 } };
// @ts-expect-error Routing metadata is optional.
result.routing.model;
// @ts-expect-error Action metadata is optional.
@@@ -77,5 -80,5 +97,6 @@@ if (answer?.type === 'choice')
void [dynamicLabel, dynamicProbability];
}
void [label, arrayLabel, probability, score, noul, inlineLabel, intent, category, routingModel,
- actionProbability, noulConfidence, answerConfidence, noulAnswerConfidence, gateState,
- gateThreshold, flagged, gatedAnswer];
+ actionProbability, noulConfidence, stateTokens, stateTokensDropped, truncated, truncatedQuestions,
- collapsedSpans, answeredUsage, mixedSegment, undetermined];
++ collapsedSpans, answeredUsage, mixedSegment, undetermined, answerConfidence,
++ noulAnswerConfidence, gateState, gateThreshold, flagged, gatedAnswer];