Skip to content

Commit

Permalink
fix(serialization): handle bounded functions
Browse files Browse the repository at this point in the history
Ref: #92
Signed-off-by: Tomas Dvorak <[email protected]>
  • Loading branch information
Tomas2D committed Oct 15, 2024
1 parent e4d060f commit 58d072f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/serializer/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { BAMLLM } from "@/adapters/bam/llm.js";
import { BAMChatLLM } from "@/adapters/bam/chat.js";
import { SerializerError } from "@/serializer/error.js";
import { ValueOf } from "@/internals/types.js";
import { toBoundedFunction } from "@/serializer/utils.js";

describe("Serializer", () => {
it.each([
Expand Down Expand Up @@ -265,6 +266,31 @@ describe("Serializer", () => {
expect(() => Serializer.deserialize(json, [BaseMessage])).not.toThrowError();
});

it("Handles bounded functions", () => {
const a = 1;
const b = 2;

let fn = toBoundedFunction(
(...args: any[]) => [a, b, ...args].reduce((a, b) => a + b, 0),
[
{
name: "a",
value: a,
},
{
name: "b",
value: b,
},
],
);

for (let i = 0; i < 5; ++i) {
const serialized = Serializer.serialize(fn);
fn = Serializer.deserialize(serialized);
expect(fn(3)).toBe(6);
}
});

it("Handles nested functions", () => {
vi.stubEnv("GENAI_API_KEY", "123");
const { data } = JSON.parse(
Expand Down
4 changes: 3 additions & 1 deletion src/serializer/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
RootNode,
SerializerNode,
SerializerRefIdentifier,
toBoundedFunction,
traverseObject,
traverseWithUpdate,
} from "@/serializer/utils.js";
Expand All @@ -43,6 +44,7 @@ import { SerializerError } from "@/serializer/error.js";
import { ZodType } from "zod";
import { toJsonSchema } from "@/internals/helpers/schema.js";
import { createAbortController } from "@/internals/helpers/cancellation.js";
import { hasMinLength } from "@/internals/helpers/array.js";

export interface SerializeFactory<A = unknown, B = unknown> {
ref: ClassConstructor<A> | NamedFunction<A>;
Expand Down Expand Up @@ -530,7 +532,7 @@ Serializer.register(Function, {
value: () => value.fn,
}),
);
return fn;
return hasMinLength(binds, 1) ? toBoundedFunction(fn, binds) : fn;
},
});

Expand Down

0 comments on commit 58d072f

Please sign in to comment.