Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 91 additions & 4 deletions packages/pi/src/models.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import {
type CreateModelRuntimeOptions,
ModelRuntime,
Expand Down Expand Up @@ -46,14 +47,100 @@ export interface PiModelOptions {
/** The model options that decide which models a client may use. */
type AllowlistOptions = Pick<PiModelOptions, "model" | "scopedModels">;

/** Most actors whose model runtime is kept between wakes. */
const RUNTIME_CACHE_MAX = 256;

interface CachedRuntime {
fingerprint: string;
store: GenerationCredentialStore;
runtime: ModelRuntime;
}

/** One model runtime per actor, kept across the actor's generations in this process. Least recently woken first. */
const runtimeCache = new Map<string, CachedRuntime>();

/** Forwards to the credential store of the actor's current generation. */
class GenerationCredentialStore implements PiCredentialStore {
constructor(public current: PiCredentialStore) {}
read: PiCredentialStore["read"] = (providerId, options) =>
this.current.read(providerId, options);
list: PiCredentialStore["list"] = (options) => this.current.list(options);
modify: PiCredentialStore["modify"] = (providerId, fn, options) =>
this.current.modify(providerId, fn, options);
delete: PiCredentialStore["delete"] = (providerId, options) =>
this.current.delete(providerId, options);
}

/** Everything a runtime is built from besides credentials, hashed because it includes `apiKeys`. */
function runtimeFingerprint(
options: Omit<PiModelOptions, "credentials">,
): string {
const sorted = (_key: string, value: unknown) =>
value && typeof value === "object" && !Array.isArray(value)
? Object.fromEntries(
Object.entries(value).sort(([a], [b]) =>
a < b ? -1 : a > b ? 1 : 0,
),
)
: value;
return createHash("sha256")
.update(
JSON.stringify(
{
providers: options.providers,
apiKeys: options.apiKeys,
scopedModels: options.scopedModels,
model: options.model,
offline: process.env.PI_OFFLINE,
},
sorted,
),
)
.digest("hex");
}

/**
* Creates the model runtime for one actor generation. It never reads Pi's
* `~/.pi/agent/auth.json` or `models.json`; credentials come from `apiKeys`,
* then `credentials`, then the server environment.
* Creates the model runtime for one actor generation. With `actorId`, the
* runtime built for the actor's previous generation in this process is reused
* while the options are unchanged, and reads `credentials` from now on.
* Building one rebuilds every built-in provider's model list several times.
*/
export async function createActorModelRuntime(
options: Omit<PiModelOptions, "credentials">,
credentials: PiCredentialStore,
actorId?: string,
): Promise<ModelRuntime> {
if (actorId === undefined) {
return traceModelRequests(await buildModelRuntime(options, credentials));
}
const fingerprint = runtimeFingerprint(options);
const cached = runtimeCache.get(actorId);
runtimeCache.delete(actorId);
if (cached?.fingerprint === fingerprint) {
cached.store.current = credentials;
runtimeCache.set(actorId, cached);
// Which providers these credentials configure, as a new runtime's refresh computes it.
await cached.runtime.getAvailable().catch(() => {});
return traceModelRequests(cached.runtime);
}
const store = new GenerationCredentialStore(credentials);
const runtime = await buildModelRuntime(options, store);
runtimeCache.set(actorId, { fingerprint, store, runtime });
for (const oldest of runtimeCache.keys()) {
if (runtimeCache.size <= RUNTIME_CACHE_MAX) break;
runtimeCache.delete(oldest);
}
return traceModelRequests(runtime);
}

/**
* Builds a model runtime. It never reads Pi's `~/.pi/agent/auth.json` or
* `models.json`; credentials come from `apiKeys`, then `credentials`, then the
* server environment.
*/
async function buildModelRuntime(
options: Omit<PiModelOptions, "credentials">,
credentials: PiCredentialStore,
): Promise<ModelRuntime> {
const runtime = await ModelRuntime.create({ credentials, modelsPath: null });
for (const [providerId, config] of Object.entries(options.providers ?? {})) {
Expand All @@ -63,7 +150,7 @@ export async function createActorModelRuntime(
await runtime.setRuntimeApiKey(providerId, apiKey);
}
await runtime.refresh({ allowNetwork: false });
return traceModelRequests(runtime);
return runtime;
}

/** A credential store that holds nothing and refuses writes. */
Expand Down
8 changes: 7 additions & 1 deletion packages/pi/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,8 +514,14 @@ async function createModels(
? new SourceCredentialStore(options.credentials(c))
: emptyCredentialStore;
return createActorModelRuntime(
{ providers: options.providers, apiKeys: options.apiKeys },
{
providers: options.providers,
apiKeys: options.apiKeys,
scopedModels: options.scopedModels,
model: options.model,
},
credentials,
c.actorId,
);
}

Expand Down
130 changes: 130 additions & 0 deletions packages/pi/tests/model-runtime-cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { ModelRuntime } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, test, vi } from "vitest";
import type { PiCredentialStore } from "../src/models.js";
import { createActorModelRuntime } from "../src/models.js";
import { createMockModel } from "./helpers/mock-model.js";

const providers = { mock: createMockModel().providerConfig };

/** A credential store that serves one API key for provider `mock` and counts reads. */
function store(key: string | undefined) {
const reads: string[] = [];
const credentials: PiCredentialStore = {
read: async (providerId) => {
reads.push(providerId);
return key === undefined ? undefined : { type: "api_key", key };
},
list: async () => [],
modify: async () => undefined,
delete: async () => {},
};
return { credentials, reads };
}

async function keyOf(runtime: ModelRuntime, credentials: string) {
const model = runtime.getModel("mock", "mock-model");
if (!model) throw new Error(`no mock model for ${credentials}`);
const auth = await runtime.getAuth(model);
return auth?.auth.apiKey;
}

afterEach(() => {
vi.restoreAllMocks();
});

describe("model runtime per actor", () => {
test("is built once across the wakes of one actor", async () => {
const create = vi.spyOn(ModelRuntime, "create");
const options = { providers };
for (let wake = 0; wake < 5; wake++) {
await createActorModelRuntime(
options,
store("k").credentials,
"cache-once",
);
}
expect(create).toHaveBeenCalledTimes(1);
});

test("a reused runtime reads the credentials of the current wake", async () => {
const first = store("key-1");
const second = store("key-2");
const options = { providers };
const a = await createActorModelRuntime(
options,
first.credentials,
"cache-creds",
);
expect(await keyOf(a, "first")).toBe("key-1");
const b = await createActorModelRuntime(
options,
second.credentials,
"cache-creds",
);
const readsBefore = first.reads.length;
expect(await keyOf(b, "second")).toBe("key-2");
expect(first.reads.length).toBe(readsBefore);
expect(second.reads.length).toBeGreaterThan(0);
});

test("actors never share a runtime or its credentials", async () => {
const create = vi.spyOn(ModelRuntime, "create");
const options = { providers };
const one = await createActorModelRuntime(
options,
store("key-one").credentials,
"cache-actor-1",
);
const two = await createActorModelRuntime(
options,
store("key-two").credentials,
"cache-actor-2",
);
expect(create).toHaveBeenCalledTimes(2);
expect(await keyOf(one, "one")).toBe("key-one");
expect(await keyOf(two, "two")).toBe("key-two");
});

test("changed options build a new runtime, key order does not", async () => {
const create = vi.spyOn(ModelRuntime, "create");
const run = (options: Parameters<typeof createActorModelRuntime>[0]) =>
createActorModelRuntime(
options,
store(undefined).credentials,
"cache-opts",
);
await run({ providers, apiKeys: { mock: "a", other: "b" } });
await run({ providers, apiKeys: { other: "b", mock: "a" } });
expect(create).toHaveBeenCalledTimes(1);
const changed = await run({ providers, apiKeys: { mock: "changed" } });
expect(create).toHaveBeenCalledTimes(2);
expect(await keyOf(changed, "changed")).toBe("changed");
await run({
providers,
apiKeys: { mock: "changed" },
model: "mock/mock-model",
});
expect(create).toHaveBeenCalledTimes(3);
});

test("the oldest actor is evicted past the limit and built again", async () => {
const create = vi.spyOn(ModelRuntime, "create");
const wake = (actorId: string) =>
createActorModelRuntime({ providers }, store("k").credentials, actorId);
await wake("evict-oldest");
for (let i = 0; i < 256; i++) await wake(`evict-${i}`);
const built = create.mock.calls.length;
await wake("evict-255");
expect(create).toHaveBeenCalledTimes(built);
await wake("evict-oldest");
expect(create).toHaveBeenCalledTimes(built + 1);
});

test("without an actor id nothing is cached", async () => {
const create = vi.spyOn(ModelRuntime, "create");
for (let wake = 0; wake < 3; wake++) {
await createActorModelRuntime({ providers }, store("k").credentials);
}
expect(create).toHaveBeenCalledTimes(3);
});
});