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(ts): validate questions and reject null state before serialization (#607, #608)

Swatantra Yadavdf54052d8e50
diff --git a/laya-ts/src/agent.ts b/laya-ts/src/agent.ts
index 6a8c8566..50119f28 100644
--- a/laya-ts/src/agent.ts
+++ b/laya-ts/src/agent.ts
@@ -218,6 +218,12 @@ export function checkQuestion(qid: string, qdef: unknown): void {
}
}
+function isPlainDict(o: unknown): o is Record<string, unknown> {
+ if (typeof o !== "object" || o === null || Array.isArray(o)) return false;
+ const proto = Object.getPrototypeOf(o);
+ return proto === null || proto === Object.prototype;
+}
+
export function toInternal(qdef: QuestionDef): { t: "choice" | "score" | "noul"; ins: string; crit: unknown; labels?: { false: string; true: string } } {
const t = qdef["type"] as "choice" | "score" | "noul";
let crit: unknown = qdef["criteria"];
@@ -384,6 +390,29 @@ export class Agent extends HookRegistry {
try {
await dispatchAsync(active, "onPredictStart", ctx, { raiseErrors });
if (ctx.results === null) {
+ if (!Array.isArray(ctx.states)) {
+ throw new TypeError(
+ "predictBatch expects an array of states; pass a single state to predict()/systemOne().",
+ );
+ }
+ if (!isPlainDict(ctx.questions)) {
+ const typeName =
+ ctx.questions === null
+ ? "NoneType"
+ : Array.isArray(ctx.questions)
+ ? "list"
+ : typeof ctx.questions === "object"
+ ? ((ctx.questions as object).constructor?.name ?? "object")
+ : typeof ctx.questions;
+ throw new TypeError(
+ `questions must be a dict of question id -> definition, got ${typeName}`,
+ );
+ }
+ for (const st of ctx.states) {
+ if (st === null || st === undefined) {
+ throw new TypeError("state must not be None; pass a string, dict, or list");
+ }
+ }
const out: SystemOneResult[] = [];
for (const st of ctx.states) {
out.push(
@@ -538,6 +567,17 @@ export class Agent extends HookRegistry {
return this.systemOne(state, questions, opts);
}
+ /**
+ * Evaluate typed questions across many states.
+ */
+ async predictBatch(
+ states: unknown[],
+ questions: Record<string, QuestionDef>,
+ opts: PredictOptions = {},
+ ): Promise<SystemOneResult[]> {
+ return this._predictHooked(states, questions, opts);
+ }
+
/**
* Answer `state` against a JSON schema (or explicit `opts.questions`) and return typed
* values — see `structured.ts`. Pass exactly one of `schema` or `opts.questions`; other
diff --git a/laya-ts/tests/agent.test.ts b/laya-ts/tests/agent.test.ts
index 583c0d01..5d9adc22 100644
--- a/laya-ts/tests/agent.test.ts
+++ b/laya-ts/tests/agent.test.ts
@@ -31,4 +31,50 @@ describe("agent", () => {
expect(typeof val).toBe("string");
}
});
+
+ it("non-dict questions raise a clear TypeError", async () => {
+ const a = new Agent({ provider: fakeProvider() } as any);
+ for (const method of ["predict", "systemOne"] as const) {
+ for (const bad of [null, [], "not-a-dict", 123, new Map(), new Set()]) {
+ await expect(a[method]("hello", bad as any)).rejects.toThrow(TypeError);
+ await expect(a[method]("hello", bad as any)).rejects.toThrow("questions must be a dict");
+ }
+ }
+ });
+
+ it("none state raises TypeError instead of answering the literal null", async () => {
+ const a = new Agent({ provider: fakeProvider() } as any);
+ const q = { q: { type: "noul", instructions: "Is it true?" } } as any;
+ for (const method of ["predict", "systemOne"] as const) {
+ for (const bad of [null, undefined]) {
+ await expect(a[method](bad, q)).rejects.toThrow(TypeError);
+ await expect(a[method](bad, q)).rejects.toThrow("state must not be None");
+ }
+ }
+ });
+
+ it("predictBatch validates state array and rejects non-array", async () => {
+ const a = new Agent({ provider: fakeProvider() } as any);
+ const q = { q: { type: "noul", instructions: "Is it true?" } } as any;
+ await expect(a.predictBatch("not-an-array" as any, q)).rejects.toThrow(TypeError);
+ await expect(a.predictBatch("not-an-array" as any, q)).rejects.toThrow(
+ "predictBatch expects an array of states",
+ );
+ await expect(a.predictBatch(["valid", null], q)).rejects.toThrow("state must not be None");
+ await expect(a.predictBatch(new Array(2), q)).rejects.toThrow("state must not be None");
+ const results = await a.predictBatch(["s1", "s2"], q);
+ expect(results).toHaveLength(2);
+ expect(results[0].answers.q.type).toBe("noul");
+ });
+
+ it("start hook can normalize questions or states before validation", async () => {
+ const a = new Agent({ provider: fakeProvider() } as any);
+ const result = await a.predict("hello", null as any, {
+ onPredictStart: (ctx) => {
+ ctx.questions = { q: { type: "noul", instructions: "Is it true?" } };
+ },
+ });
+ expect(result.answers.q.type).toBe("noul");
+ });
});
+
diff --git a/laya-ts/tests/structured.test.ts b/laya-ts/tests/structured.test.ts
index a20d0ba3..c38a0433 100644
--- a/laya-ts/tests/structured.test.ts
+++ b/laya-ts/tests/structured.test.ts
@@ -154,7 +154,7 @@ describe("structured/rejections", () => {
describe("structured/decide", () => {
class FakeRunner {
calls: { state: unknown; questions: unknown; opts: unknown }[] = [];
- constructor(private answers: unknown) {}
+ constructor(private answers: any) {}
async predict(state: unknown, questions: any, opts: any = {}) {
this.calls.push({ state, questions, opts });
return { answers: this.answers, usage: { input_tokens: 1, output_tokens: 0 },