Skip to content

Commit 7c3f8b0

Browse files
committed
fix(lmstudio): resolve JIT embedding variants
1 parent f1e7e20 commit 7c3f8b0

2 files changed

Lines changed: 130 additions & 9 deletions

File tree

‎extensions/lmstudio/src/embedding-provider.test.ts‎

Lines changed: 84 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,42 @@ const ensureLmstudioModelLoadedMock = vi.hoisted(() =>
99
async (_params?: { requestedContextLength?: number }) => "text-embedding-nomic-embed-text-v1.5",
1010
),
1111
);
12+
const fetchLmstudioModelsMock = vi.hoisted(() =>
13+
vi.fn(async (_params?: unknown) => ({
14+
reachable: true,
15+
status: 200,
16+
models: [] as Array<{
17+
type?: "llm" | "embedding";
18+
key?: string;
19+
variants?: unknown;
20+
selected_variant?: unknown;
21+
loaded_instances?: unknown[];
22+
}>,
23+
})),
24+
);
1225
const resolveLmstudioProviderHeadersMock = vi.hoisted(() =>
1326
vi.fn(async (_params?: unknown) => undefined),
1427
);
1528
const resolveLmstudioRuntimeApiKeyMock = vi.hoisted(() =>
1629
vi.fn(async (_params?: unknown) => undefined),
1730
);
31+
const embeddedModels = vi.hoisted(() => [] as string[]);
1832
const createRemoteEmbeddingProviderMock = vi.hoisted(() =>
19-
vi.fn(() => ({
20-
id: "lmstudio",
21-
model: "text-embedding-nomic-embed-text-v1.5",
22-
embedQuery: vi.fn(async () => [1, 0]),
23-
embedBatch: vi.fn(async (texts: string[]) => texts.map(() => [1, 0])),
24-
})),
33+
vi.fn((params: { client: { model: string } }) => {
34+
const providerModel = params.client.model;
35+
return {
36+
id: "lmstudio",
37+
model: providerModel,
38+
embedQuery: vi.fn(async () => {
39+
embeddedModels.push(params.client.model);
40+
return [1, 0];
41+
}),
42+
embedBatch: vi.fn(async (texts: string[]) => {
43+
embeddedModels.push(params.client.model);
44+
return texts.map(() => [1, 0]);
45+
}),
46+
};
47+
}),
2548
);
2649

2750
vi.mock("openclaw/plugin-sdk/memory-core-host-engine-embeddings", async (importOriginal) => {
@@ -39,6 +62,7 @@ vi.mock("./models.fetch.js", async (importOriginal) => {
3962
...actual,
4063
ensureLmstudioModelLoaded: (params: { requestedContextLength?: number }) =>
4164
ensureLmstudioModelLoadedMock(params),
65+
fetchLmstudioModels: (params: unknown) => fetchLmstudioModelsMock(params),
4266
};
4367
});
4468

@@ -84,7 +108,10 @@ async function readRequestedContextLength(config: OpenClawConfig): Promise<unkno
84108
describe("createLmstudioEmbeddingProvider preload context length", () => {
85109
beforeEach(() => {
86110
ensureLmstudioModelLoadedMock.mockClear();
111+
fetchLmstudioModelsMock.mockClear();
112+
fetchLmstudioModelsMock.mockResolvedValue({ reachable: true, status: 200, models: [] });
87113
createRemoteEmbeddingProviderMock.mockClear();
114+
embeddedModels.length = 0;
88115
resolveLmstudioProviderHeadersMock.mockClear();
89116
resolveLmstudioRuntimeApiKeyMock.mockClear();
90117
});
@@ -159,6 +186,7 @@ describe("createLmstudioEmbeddingProvider preload context length", () => {
159186
});
160187

161188
expect(ensureLmstudioModelLoadedMock).not.toHaveBeenCalled();
189+
expect(fetchLmstudioModelsMock).not.toHaveBeenCalled();
162190
expect(acquireLocalService).not.toHaveBeenCalled();
163191

164192
await expect(provider.embedQuery("hello")).resolves.toEqual([1, 0]);
@@ -172,6 +200,56 @@ describe("createLmstudioEmbeddingProvider preload context length", () => {
172200
},
173201
);
174202

203+
it("resolves a JIT variant before freezing provider and cache identity", async () => {
204+
const requestedVariant = `${EMBEDDING_MODEL}@q4_k_m`;
205+
const release = vi.fn();
206+
const acquireLocalService = vi.fn(async () => ({ release }));
207+
fetchLmstudioModelsMock.mockResolvedValueOnce({
208+
reachable: true,
209+
status: 200,
210+
models: [
211+
{
212+
type: "embedding",
213+
key: EMBEDDING_MODEL,
214+
variants: [requestedVariant],
215+
selected_variant: requestedVariant,
216+
loaded_instances: [],
217+
},
218+
],
219+
});
220+
221+
const options = {
222+
config: buildConfig({
223+
model: { id: requestedVariant },
224+
provider: {
225+
params: { preload: false },
226+
localService: { command: "/usr/bin/lms" },
227+
},
228+
}),
229+
provider: "lmstudio",
230+
model: `lmstudio/${requestedVariant}`,
231+
fallback: "none",
232+
acquireLocalService,
233+
};
234+
const result = await lmstudioMemoryEmbeddingProviderAdapter.create(options);
235+
if (!result.provider) {
236+
throw new Error("expected LM Studio embedding provider");
237+
}
238+
239+
expect(ensureLmstudioModelLoadedMock).not.toHaveBeenCalled();
240+
expect(fetchLmstudioModelsMock).toHaveBeenCalledOnce();
241+
expect(acquireLocalService).toHaveBeenCalledOnce();
242+
expect(release).toHaveBeenCalledOnce();
243+
expect(result.provider.model).toBe(EMBEDDING_MODEL);
244+
expect(result.runtime?.cacheKeyData).toMatchObject({ model: EMBEDDING_MODEL });
245+
246+
await expect(result.provider.embedQuery("hello")).resolves.toEqual([1, 0]);
247+
248+
expect(embeddedModels).toEqual([EMBEDDING_MODEL]);
249+
expect(acquireLocalService).toHaveBeenCalledTimes(2);
250+
expect(release).toHaveBeenCalledTimes(2);
251+
});
252+
175253
it("uses the canonical preloaded model for embedding requests and memory identity", async () => {
176254
const requestedVariant = `${EMBEDDING_MODEL}@q4_k_m`;
177255
const result = await lmstudioMemoryEmbeddingProviderAdapter.create({

‎extensions/lmstudio/src/embedding-provider.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
1212
import { formatErrorMessage, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
1313
import { asPositiveSafeInteger } from "openclaw/plugin-sdk/string-coerce-runtime";
1414
import { LMSTUDIO_DEFAULT_EMBEDDING_MODEL, LMSTUDIO_PROVIDER_ID } from "./defaults.js";
15-
import { ensureLmstudioModelLoaded } from "./models.fetch.js";
15+
import { ensureLmstudioModelLoaded, fetchLmstudioModels } from "./models.fetch.js";
1616
import {
1717
normalizeLmstudioConfiguredCatalogEntries,
18+
resolveLmstudioCanonicalModelKey,
1819
resolveLmstudioInferenceBase,
1920
resolveLmstudioServerBase,
2021
} from "./models.js";
@@ -156,9 +157,31 @@ function resolveLmstudioLocalServiceBaseUrl(
156157
return /\/api\/v1$/iu.test(configuredPath) ? `${serverBaseUrl}/api/v1` : `${serverBaseUrl}/v1`;
157158
}
158159

160+
async function resolveLmstudioEmbeddingModelKey(params: {
161+
baseUrl: string;
162+
apiKey?: string;
163+
headers: Record<string, string>;
164+
ssrfPolicy?: SsrFPolicy;
165+
model: string;
166+
}): Promise<string> {
167+
const discovered = await fetchLmstudioModels({
168+
baseUrl: params.baseUrl,
169+
apiKey: params.apiKey,
170+
headers: params.headers,
171+
ssrfPolicy: params.ssrfPolicy,
172+
});
173+
if (!discovered.reachable || (discovered.status !== undefined && discovered.status >= 400)) {
174+
return params.model;
175+
}
176+
return resolveLmstudioCanonicalModelKey({
177+
modelKey: params.model,
178+
models: discovered.models,
179+
});
180+
}
181+
159182
/** Creates the LM Studio embedding provider client and preloads the target model before return. */
160183
export async function createLmstudioEmbeddingProvider(
161-
options: MemoryEmbeddingProviderCreateOptions,
184+
options: LocalServiceAwareEmbeddingOptions,
162185
): Promise<{ provider: MemoryEmbeddingProvider; client: LmstudioEmbeddingClient }> {
163186
const resolvedProvider = resolveConfiguredLmstudioProvider(options);
164187
const providerConfig = resolvedProvider?.config;
@@ -225,7 +248,7 @@ export async function createLmstudioEmbeddingProvider(
225248
headers,
226249
}
227250
: undefined;
228-
const acquireLocalService = (options as LocalServiceAwareEmbeddingOptions).acquireLocalService;
251+
const acquireLocalService = options.acquireLocalService;
229252
const withLocalServiceLease = async <T>(
230253
signal: AbortSignal | undefined,
231254
action: () => Promise<T>,
@@ -269,6 +292,26 @@ export async function createLmstudioEmbeddingProvider(
269292
});
270293
}
271294
});
295+
} else if (model.includes("@")) {
296+
// Variant aliases are not accepted by LM Studio's inference routes. Resolve
297+
// only the stable wire/cache identity here; JIT still owns the actual load.
298+
try {
299+
await withLocalServiceLease(undefined, async () => {
300+
client.model = await resolveLmstudioEmbeddingModelKey({
301+
baseUrl,
302+
apiKey,
303+
headers: headerOverrides,
304+
ssrfPolicy,
305+
model,
306+
});
307+
});
308+
} catch (error) {
309+
log.debug("lmstudio embedding variant discovery failed; using requested model", {
310+
baseUrl,
311+
model,
312+
error: formatErrorMessage(error),
313+
});
314+
}
272315
}
273316

274317
const remoteProvider = createRemoteEmbeddingProvider({

0 commit comments

Comments
 (0)