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.

fix(laya-ts): a non-object answer is omitted from the projection, as the oracle omits it

Aashish508869ae3859
diff --git a/laya-ts/src/structured.ts b/laya-ts/src/structured.ts
index 8427ac74..a4a0a48c 100644
--- a/laya-ts/src/structured.ts
+++ b/laya-ts/src/structured.ts
@@ -272,11 +272,33 @@ export function questionsFromJsonSchema(schema: unknown): Record<string, Questio
return Object.fromEntries(planFromJsonSchema(schema).map((f) => [f.name, f.question]));
}
-function project(answers: Record<string, Record<string, any> | undefined>, fields: PlannedField[]): Record<string, unknown> {
+/**
+ * Is this entry an answer object? Python's `_project` and `_details` ask the same question with
+ * `isinstance(answer, dict)` and skip the field when it is not true (structured.py:281, :323).
+ * Answers reach this port as parsed remote JSON, so the value under a field name can be a string,
+ * a number, a boolean or an array -- and `answer.low_confidence` on any of those is `undefined`
+ * rather than an error, so the unguarded read below did not crash: it invented a value. Measured
+ * with the other three answers well-formed and one replaced, against `laya/structured.py`:
+ *
+ * answer py (all fields) ts (before)
+ * "oops" omitted "undefined" (choice) / 0 (score) / false (noul)
+ * ["x"] omitted same
+ * 7 omitted same
+ * true omitted same
+ * null omitted omitted
+ *
+ * `Array.isArray` is load-bearing: `typeof` reports an array as "object", and `common.ts:408` --
+ * the port of the same skip -- has the primitive half of the check but not that one.
+ */
+function isAnswerObject(answer: unknown): answer is Record<string, any> {
+ return answer !== null && typeof answer === "object" && !Array.isArray(answer);
+}
+
+function project(answers: Record<string, unknown>, fields: PlannedField[]): Record<string, unknown> {
const values: Record<string, unknown> = {};
for (const f of fields) {
const answer = answers[f.name];
- if (answer == null) continue;
+ if (!isAnswerObject(answer)) continue;
if (answer.low_confidence) {
values[f.name] = null;
continue;
@@ -312,7 +334,7 @@ function project(answers: Record<string, Record<string, any> | undefined>, field
/** Project Laya answers onto the schema values (choice value, integer level, boolean). */
export function answersToJson(
- answers: Record<string, Record<string, any> | undefined>,
+ answers: Record<string, unknown>,
schema: unknown,
): Record<string, unknown> {
return project(answers, planFromJsonSchema(schema));
@@ -329,14 +351,16 @@ function answerConfidenceValue(answer: Record<string, any>): number | null {
function detailsOf(
values: Record<string, unknown>,
- answers: Record<string, Record<string, any> | undefined>,
+ answers: Record<string, unknown>,
result: { usage?: unknown; routing?: unknown },
): DecisionResult {
const confidence: Record<string, number> = {};
const answerConfidence: Record<string, number | null> = {};
const probabilities: Record<string, Record<string, unknown>> = {};
for (const [name, answer] of Object.entries(answers)) {
- if (answer == null) continue;
+ // Same rule as `project`: a non-object answer reports no confidence, no max(p) and no
+ // probability map, rather than a 0.0/null/{} entry for a question that was never answered.
+ if (!isAnswerObject(answer)) continue;
confidence[name] = Number(answer.confidence ?? 0.0);
answerConfidence[name] = answerConfidenceValue(answer);
if (answer.type === "noul") {
diff --git a/laya-ts/tests/structured.test.ts b/laya-ts/tests/structured.test.ts
index 9ab6e15d..8765688e 100644
--- a/laya-ts/tests/structured.test.ts
+++ b/laya-ts/tests/structured.test.ts
@@ -109,6 +109,61 @@ describe("structured/projection", () => {
{ type: "object", properties: { x: { enum: ["a", null] } } });
expect(v.x).toBe(null);
});
+
+ // Mirrors the non-dict-answer block in tests/test_structured.py. The answers this port projects
+ // come from parsed remote JSON, so a field's entry can be a string, number, boolean, array or
+ // null instead of an answer object. Python skips those (`isinstance(answer, dict)`) and omits the
+ // field, as it omits an absent answer; `answer == null` let a primitive through and each field
+ // read invented a value for it -- "undefined" for a choice, `minimum + 0` for a score, false for
+ // a noul, measured across 4 fields x 6 shapes against `laya/structured.py`.
+ const EXPECTED_VALUES: Record<string, unknown> = {
+ department: "billing", urgency: 2, needs_human: true, priority: 2,
+ };
+ const FIELDS = Object.keys(EXPECTED_VALUES);
+ const NON_OBJECT: Array<[string, unknown]> = [
+ ["string", "oops"],
+ ["list", ["not", "an", "answer"]],
+ ["int", 7],
+ ["float", 0.5],
+ ["bool", true],
+ ["null", null],
+ ];
+ for (const [label, body] of NON_OBJECT) {
+ it(`omits a non-object answer (${label}) and still projects the fields beside it`, () => {
+ for (const field of FIELDS) {
+ const values = answersToJson({ ...ANSWERS, [field]: body } as any, SCHEMA);
+ expect(Object.prototype.hasOwnProperty.call(values, field)).toBe(false);
+ for (const other of FIELDS.filter((f) => f !== field)) {
+ expect(values[other]).toEqual(EXPECTED_VALUES[other]);
+ }
+ }
+ });
+ }
+ it("all answers non-object yields no values", () => {
+ expect(answersToJson({ department: 5, urgency: "x" } as any, SCHEMA)).toEqual({});
+ });
+
+ // The same entry reaches `decide` through a runner, not only through answersToJson, and
+ // `returnDetails` walks it a second time to build the per-field maps. Python omits it from all
+ // four (`values`, `confidence`, `answer_confidence`, `probabilities`); the unguarded loop added a
+ // confidence of 0.0 for a question that was never answered.
+ const fakeRunner = (answers: Record<string, any>) => ({
+ async predict() {
+ return { model: "fake", answers: JSON.parse(JSON.stringify(answers)) };
+ },
+ });
+ for (const [label, body] of NON_OBJECT) {
+ it(`decide omits a non-object answer (${label}) from the details too`, async () => {
+ const det = await decide(fakeRunner({ ...ANSWERS, department: body }), "s", SCHEMA, {
+ returnDetails: true,
+ }) as any;
+ for (const map of ["values", "confidence", "answerConfidence", "probabilities"]) {
+ expect(Object.prototype.hasOwnProperty.call(det[map], "department")).toBe(false);
+ }
+ expect(det.values.urgency).toBe(2);
+ expect(det.confidence.needs_human).toBe(0.8);
+ });
+ }
});
describe("structured/rejections", () => {