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): derive the bucket guard from Python's `or {}`, not JS truthiness

Bruce-Yii934273ab62c0
diff --git a/laya-ts/src/agent.ts b/laya-ts/src/agent.ts
index a6c95ff7..03a98d9e 100644
--- a/laya-ts/src/agent.ts
+++ b/laya-ts/src/agent.ts
@@ -271,6 +271,20 @@ function isPlainDict(o: unknown): o is Record<string, unknown> {
return proto === null || proto === Object.prototype;
}
+/** Whether a `temperature_by_options` value means "no override" in Python.
+ *
+ * `cfg.get("temperature_by_options") or {}` turns every Python-falsy value into `{}`, and the
+ * two languages disagree about which values those are: an empty array is truthy in JavaScript,
+ * and NaN is falsy here while truthy in Python. So the set is named rather than inferred from
+ * JavaScript truthiness. Python's own falsy values are `[]`, `{}`, `0`, `0.0`, `False`, `None`
+ * and `""`; `{}` needs no case here because a dict is accepted either way.
+ */
+function isEmptyOverride(v: unknown): boolean {
+ if (v === null || v === undefined || v === false || v === "") return true;
+ if (v === 0) return true; // `===`, not Object.is: that distinguishes -0 from 0
+ return Array.isArray(v) && v.length === 0; // [] -- truthy in JavaScript
+}
+
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"];
@@ -399,23 +413,23 @@ export class Agent extends HookRegistry {
`Language override ${JSON.stringify(l)} temperature must be a list of 3 floats`,
);
}
- const tboRaw = (lc?.temperature_by_options ?? {}) as Record<string, unknown>;
- // Python requires a mapping here and names the language otherwise. `?? {}` covers only
- // null/undefined, so a string reached `Object.entries` and became character keys --
- // "nope" gave {"0":"n","1":"o","2":"p","3":"e"} -- and every bucket a question can ask for
- // then missed, silently, at the base temperature; a number gave {} and so did nothing at
- // all. A falsy value is an empty override on both sides (Python's `or {}` is what makes it
- // so), so only a truthy non-mapping is an error here too.
- if (tboRaw && (typeof tboRaw !== "object" || Array.isArray(tboRaw))) {
+ const tboRaw: unknown = lc?.temperature_by_options;
+ // Python: `cfg.get("temperature_by_options") or {}`, then `isinstance(..., dict)`. So a
+ // Python-falsy value is an empty override, a dict is kept, and anything else is rejected
+ // naming the language. isPlainDict is the module's own mapping test, so a Map, Set or Date
+ // is refused instead of being read as {} by Object.entries -- a configured override that
+ // silently does nothing is the same failure as no override at all.
+ if (!isEmptyOverride(tboRaw) && !isPlainDict(tboRaw)) {
throw new Error(
`Language override ${JSON.stringify(l)} temperature_by_options must be a mapping of ` +
`bucket -> float, got ${Array.isArray(tboRaw) ? "list" : typeof tboRaw}`,
);
}
+ const tboDict: Record<string, unknown> = isPlainDict(tboRaw) ? tboRaw : {};
this.langTemperatures[normL] = {
temperature: [0, 1, 2].map((i) => clampTemperature(tRaw[i])),
temperatureByOptions: Object.fromEntries(
- Object.entries(tboRaw).map(([k, v]) => [k, clampTemperature(v)]),
+ Object.entries(tboDict).map(([k, v]) => [k, clampTemperature(v)]),
),
};
}
diff --git a/laya-ts/tests/lang-temperature.test.ts b/laya-ts/tests/lang-temperature.test.ts
index d2204f55..ed0c3721 100644
--- a/laya-ts/tests/lang-temperature.test.ts
+++ b/laya-ts/tests/lang-temperature.test.ts
@@ -84,26 +84,63 @@ describe("lang_temperatures", () => {
});
it("rejects bucket overrides that are not a mapping, as Python does", () => {
- // Python (common.py resolve_lang_temperatures) requires a mapping and names the language
- // otherwise. `?? {}` only covers null/undefined, so a string reached Object.entries and
- // became character keys: Object.entries("nope") is [["0","n"],["1","o"],["2","p"],["3","e"]],
- // none of which is a bucket any question asks for.
- for (const buckets of ["nope", 42, true, ["choice:2"]]) {
+ // Python (common.py resolve_lang_temperatures) is two lines: `cfg.get(...) or {}`, then
+ // `isinstance(..., dict)`. So a Python-falsy value collapses to {} and is accepted, a dict
+ // is accepted, and anything else truthy is rejected naming the language.
+ //
+ // JavaScript truthiness is not that test, in two places: an empty array is truthy here and
+ // falsy in Python, and NaN is falsy here and truthy in Python. A string also reached
+ // Object.entries and became character keys -- Object.entries("nope") is
+ // [["0","n"],["1","o"],["2","p"],["3","e"]] -- none of which is a bucket any question asks for.
+ const truthyNonMappings: Array<[string, unknown]> = [
+ ["a non-empty string", "nope"],
+ ["a non-zero number", 42],
+ ["a boolean", true],
+ ["a non-empty list", ["choice:2"]],
+ ["NaN", NaN],
+ ["Infinity", Infinity],
+ // Not dicts in Python, and Object.entries reads none of their contents, so accepting
+ // them turns a configured override into an empty one without a word.
+ ["a Map", new Map([["choice:2", 2.0]])],
+ ["a Set", new Set(["choice:2"])],
+ ["a Date", new Date(0)],
+ ["a class instance", new (class { "choice:2" = 2.0 })()],
+ ];
+ for (const [label, buckets] of truthyNonMappings) {
expect(
() => new Agent({ provider: fakeProvider(), lang_temperatures: { de: { temperature_by_options: buckets } } } as any),
+ label,
).toThrow('Language override "de" temperature_by_options must be a mapping of bucket -> float');
}
- // A falsy value is an empty override in both languages, and Python's `or {}` is what makes
- // that so; these must keep passing rather than start failing on a shape that means "none".
- for (const buckets of [undefined, null, {}, 0, false, ""]) {
+ });
+
+ it("treats a Python-falsy bucket override as no override, as Python does", () => {
+ // `x or {}` is what makes these "no override" in Python, and the empty array is the case
+ // that has to be named rather than inferred. All must keep passing rather than start
+ // failing on a shape that already means "none".
+ for (const buckets of [undefined, null, {}, [], 0, -0, false, ""]) {
const a = new Agent({
provider: fakeProvider(),
lang_temperatures: { de: { temperature_by_options: buckets } },
} as any);
- expect(a.langTemperatures.de.temperatureByOptions).toEqual({});
+ expect(a.langTemperatures.de.temperatureByOptions, JSON.stringify(buckets) ?? "undefined").toEqual({});
}
});
+ it("keeps a real mapping, and a null-prototype one, as Python's dict", () => {
+ const mapped = new Agent({
+ provider: fakeProvider(),
+ lang_temperatures: { de: { temperature_by_options: { "choice:2": 2.0 } } },
+ } as any);
+ expect(mapped.langTemperatures.de.temperatureByOptions).toEqual({ "choice:2": 2.0 });
+ // JSON.parse and Object.create(null) are both dicts in Python; both must survive.
+ const bare = new Agent({
+ provider: fakeProvider(),
+ lang_temperatures: { de: { temperature_by_options: Object.assign(Object.create(null), { "choice:2": 2.0 }) } },
+ } as any);
+ expect(bare.langTemperatures.de.temperatureByOptions).toEqual({ "choice:2": 2.0 });
+ });
+
it("rejects a base temperature that is not a list of 3 floats, as Python does (#502)", () => {
for (const temperature of [[1, 1], [1, 1, 1, 1], 2, "1"]) {
expect(() => new Agent({ provider: fakeProvider(), temperature } as any)).toThrow(