Skip to content

Commit f8dd0ac

Browse files
committed
fix(service-knowledge): the saved Base URL applies only to custom and Azure; number keys read from text; boot line names the endpoint host
Claude-Session: https://claude.ai/code/session_01QSeKYofJfCPWsxaVYkmaVF Co-authored-by: Claude <noreply@anthropic.com>
1 parent f329965 commit f8dd0ac

2 files changed

Lines changed: 157 additions & 11 deletions

File tree

‎packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts‎

Lines changed: 102 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -307,19 +307,27 @@ class HostEmbedderPlugin implements Plugin {
307307
}
308308
}
309309

310-
interface ProviderRequest { url: string; authorization: string | null; model: unknown; inputs: string[] }
310+
interface ProviderRequest { url: string; authorization: string | null; model: unknown; dimensions: unknown; inputs: string[] }
311311

312-
/** Stubs the provider's `POST /embeddings` on the global `fetch`. */
313-
function stubProvider(): ProviderRequest[] {
312+
/** Stubs the provider's `POST /embeddings` on the global `fetch`; `status` other than 200 answers an error. */
313+
function stubProvider(status = 200): ProviderRequest[] {
314314
const requests: ProviderRequest[] = [];
315315
vi.stubGlobal('fetch', vi.fn(async (url: string | URL, init?: RequestInit) => {
316-
const body = JSON.parse(String(init?.body)) as { model?: unknown; input: string[] };
316+
const body = JSON.parse(String(init?.body)) as { model?: unknown; dimensions?: unknown; input: string[] };
317317
requests.push({
318318
url: String(url),
319319
authorization: new Headers(init?.headers).get('authorization'),
320320
model: body.model,
321+
dimensions: body.dimensions,
321322
inputs: body.input,
322323
});
324+
if (status !== 200) {
325+
return new Response(JSON.stringify({ error: { message: 'Incorrect API key provided.' } }), {
326+
status,
327+
statusText: 'Unauthorized',
328+
headers: { 'content-type': 'application/json' },
329+
});
330+
}
323331
return new Response(JSON.stringify({ data: body.input.map(() => ({ embedding: [0.6, 0.8] })) }), {
324332
status: 200,
325333
headers: { 'content-type': 'application/json' },
@@ -331,6 +339,7 @@ function stubProvider(): ProviderRequest[] {
331339
async function bootEmbedder(opts: {
332340
saved?: Record<string, unknown>;
333341
host?: { embedder: IEmbedder; phase: 'init' | 'kernel:ready' };
342+
env?: Record<string, string>;
334343
} = {}) {
335344
const lines: LoggedLine[] = [];
336345
const kernel = new LiteKernel();
@@ -340,7 +349,7 @@ async function bootEmbedder(opts: {
340349
enableEventSync: false,
341350
sources: [{ id: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'http', urls: ['https://docs.example.com/'] } }],
342351
}));
343-
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
352+
kernel.use(new SettingsServicePlugin({ env: opts.env ?? {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
344353
kernel.use(new EmbeddingAdapterPlugin());
345354
if (opts.saved) kernel.use(new SavedAiSettings(opts.saved));
346355
await kernel.bootstrap();
@@ -369,6 +378,7 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
369378
url: 'https://api.openai.com/v1/embeddings',
370379
authorization: `Bearer ${API_KEY}`,
371380
model: 'text-embedding-3-small',
381+
dimensions: undefined,
372382
inputs: ['hello embedder'],
373383
}]);
374384
// The key reaches the provider and nothing else.
@@ -483,6 +493,93 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
483493
expect(requests.map((r) => r.inputs.length)).toEqual([50, 10]);
484494
});
485495

496+
it('a Base URL left saved from a custom endpoint is not applied under a preset provider', async () => {
497+
const requests = stubProvider();
498+
// The operator once saved `custom` with a gateway, then switched to OpenAI
499+
// with a new key: the Base URL row stays saved, but the form no longer
500+
// offers the field, and the new key must not go to the old gateway.
501+
const { embedder, lines } = await bootEmbedder({
502+
saved: {
503+
embedder_provider: 'openai',
504+
embedder_api_key: API_KEY,
505+
embedder_model: 'text-embedding-3-small',
506+
embedder_base_url: 'https://old-gateway.example.com/v1',
507+
},
508+
});
509+
await embedder.embed(['x']);
510+
expect(requests.map((r) => r.url)).toEqual(['https://api.openai.com/v1/embeddings']);
511+
const boot = lines.filter((l) => l.line.includes(`registered '${EMBEDDER_SERVICE}' from the ai.embedder_* settings`));
512+
expect(boot).toHaveLength(1);
513+
expect(boot[0].line).toContain('endpoint=api.openai.com');
514+
expect(boot[0].line).not.toContain(API_KEY);
515+
});
516+
517+
it('an OS_AI_EMBEDDER_* override of a number key arrives as text and is applied, not dropped', async () => {
518+
const requests = stubProvider();
519+
const { embedder } = await bootEmbedder({
520+
env: { OS_AI_EMBEDDER_DIMENSIONS: '256' },
521+
saved: { embedder_provider: 'openai', embedder_api_key: API_KEY, embedder_model: 'text-embedding-3-small' },
522+
});
523+
expect(embedder.dimensions).toBe(256);
524+
await embedder.embed(['x']);
525+
expect(requests.map((r) => r.dimensions)).toEqual([256]);
526+
});
527+
528+
it('a number key saved as text that is not a positive integer is refused at warn, not dropped', async () => {
529+
const requests = stubProvider();
530+
const { embedder, lines } = await bootEmbedder({
531+
env: { OS_AI_EMBEDDER_DIMENSIONS: 'large' },
532+
saved: { embedder_provider: 'openai', embedder_api_key: API_KEY },
533+
});
534+
await expect(embedder.embed(['x'])).rejects.toThrow(/ai\.embedder_dimensions is saved as 'large', which is not a positive integer/);
535+
expect(lines.some((l) => l.level === 'warn' && l.line.includes('ai.embedder_dimensions'))).toBe(true);
536+
expect(requests).toHaveLength(0);
537+
});
538+
539+
it('an unsaved batch size on a model with no documented cap is the embedder fallback, not the default 64', async () => {
540+
const requests = stubProvider();
541+
const { embedder } = await bootEmbedder({
542+
saved: {
543+
embedder_provider: 'custom',
544+
embedder_api_key: API_KEY,
545+
embedder_model: 'my-gateway-model',
546+
embedder_base_url: 'https://gateway.example.com/v1',
547+
},
548+
});
549+
await embedder.embed(texts(70));
550+
// The default 64 counted as saved would send 64, 6.
551+
expect(requests.map((r) => r.inputs.length)).toEqual([10, 10, 10, 10, 10, 10, 10]);
552+
});
553+
554+
it('the API key is in no log line and no error: incomplete settings, and a provider that refuses the key', async () => {
555+
stubProvider();
556+
// Saved with its key, but `custom` without the Base URL it needs.
557+
const incomplete = await bootEmbedder({ saved: { embedder_provider: 'custom', embedder_api_key: API_KEY } });
558+
const refusal = await incomplete.embedder.embed(['x']).then(
559+
() => { throw new Error('expected a refusal'); },
560+
(err: unknown) => err as Error,
561+
);
562+
expect(refusal.message).toMatch(/custom embedder requires a Base URL/);
563+
expect(refusal.message).not.toContain(API_KEY);
564+
expect(incomplete.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]);
565+
566+
vi.unstubAllGlobals();
567+
const requests = stubProvider(401);
568+
const rejected = await bootEmbedder({
569+
saved: { embedder_provider: 'openai', embedder_api_key: API_KEY, embedder_model: 'text-embedding-3-small' },
570+
});
571+
await expect(rejected.knowledge.indexDocument('docs', { id: 'd1', sourceId: 'docs', content: 'hello' }))
572+
.rejects.toThrow(/401/);
573+
const failure = await rejected.embedder.embed(['x']).then(
574+
() => { throw new Error('expected a provider error'); },
575+
(err: unknown) => err as Error,
576+
);
577+
expect(failure.message).not.toContain(API_KEY);
578+
await rejected.knowledge.search('hello', { sourceIds: ['docs'] });
579+
expect(requests.length).toBeGreaterThan(0);
580+
expect(rejected.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]);
581+
});
582+
486583
it("'none' saved: embeddings stay disabled, and the error says so", async () => {
487584
stubProvider();
488585
const { embedder } = await bootEmbedder({ saved: { embedder_provider: 'none' } });

‎packages/services/service-knowledge/src/knowledge-service-plugin.ts‎

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ type EmbedderFromSettings =
7272
batchSize: number | undefined;
7373
/** The saved size, when the documented cap lowered it. */
7474
savedBatchSize: number | undefined;
75+
/** The host requests go to — named in the boot line; the key never is. */
76+
endpointHost: string;
7577
}
7678
| {
7779
kind: 'unconfigured';
@@ -121,6 +123,29 @@ function savedValue(values: Record<string, ResolvedEmbedderSetting | undefined>,
121123
return value;
122124
}
123125

126+
/** The providers whose form offers the Base URL field (`embedder_base_url`'s `visible` rule). */
127+
const BASE_URL_PROVIDERS: ReadonlySet<string> = new Set(['custom', 'azure']);
128+
129+
/**
130+
* A saved number key read as a positive integer: the value (a number, or its
131+
* decimal text, as an `OS_*` override hands it over), `undefined` when nothing
132+
* is saved, `null` when what is saved is not one.
133+
*/
134+
function positiveIntegerSetting(value: unknown): number | undefined | null {
135+
if (value === undefined) return undefined;
136+
const n = typeof value === 'number' ? value : typeof value === 'string' && /^\s*\d+\s*$/.test(value) ? Number(value) : NaN;
137+
return Number.isInteger(n) && n > 0 ? n : null;
138+
}
139+
140+
/** The host of an endpoint URL, or the URL itself when it does not parse. */
141+
function hostOf(url: string): string {
142+
try {
143+
return new URL(url).host;
144+
} catch {
145+
return url;
146+
}
147+
}
148+
124149
/**
125150
* Build the embedder the saved `ai.embedder_*` settings describe, or say why
126151
* there is none. Completeness is judged by the settings page's own
@@ -199,18 +224,40 @@ async function embedderFromSettings(ctx: PluginContext): Promise<EmbedderFromSet
199224
}
200225

201226
const providerId = String(provider);
202-
const baseUrl = typeof saved.embedder_base_url === 'string' ? saved.embedder_base_url.trim() : undefined;
203227
const preset = Object.prototype.hasOwnProperty.call(OPENAI_COMPATIBLE_PRESETS, providerId)
204228
? (providerId as OpenAICompatiblePreset)
205229
: undefined;
230+
// The saved Base URL applies only where the form offers the field (`custom`,
231+
// `azure`, the manifest's `visible` rule). A URL saved under one of those and
232+
// left behind when the operator switches to a preset provider must not carry
233+
// the new provider's key to the old host: every other provider uses its
234+
// preset endpoint.
235+
const baseUrl =
236+
BASE_URL_PROVIDERS.has(providerId) && typeof saved.embedder_base_url === 'string'
237+
? saved.embedder_base_url.trim()
238+
: undefined;
206239
const model = typeof saved.embedder_model === 'string' ? saved.embedder_model.trim() : undefined;
207-
const dimensions = typeof saved.embedder_dimensions === 'number' ? saved.embedder_dimensions : undefined;
240+
// The two number keys can arrive as text: an `OS_AI_EMBEDDER_*` override of a
241+
// key with no numeric default is handed over as the env string. A positive
242+
// integer, as a number or as its decimal text, is the value; anything else
243+
// is refused below rather than dropped.
244+
const dimensions = positiveIntegerSetting(saved.embedder_dimensions);
245+
const savedBatch = positiveIntegerSetting(saved.embedder_batch_size);
246+
if (dimensions === null || savedBatch === null) {
247+
const key = dimensions === null ? 'embedder_dimensions' : 'embedder_batch_size';
248+
return {
249+
kind: 'unconfigured',
250+
quiet: false,
251+
reason:
252+
`ai.${key} is saved as '${String(saved[key])}', which is not a positive integer — correct it ` +
253+
EMBEDDER_SETTINGS_REMEDY,
254+
};
255+
}
208256
// Only a SAVED batch size is a batch cap; unsaved, the embedder batches at the
209257
// model's own documented cap (some providers accept 10, not the default 64).
210258
// A saved size is held to that documented cap when the saved model has one:
211259
// an explicit `maxBatchSize` would otherwise override it. A model the table
212260
// does not know, or no saved model, keeps the saved size as saved.
213-
const savedBatch = typeof saved.embedder_batch_size === 'number' ? saved.embedder_batch_size : undefined;
214261
const documentedCap = model ? documentedMaxBatchSize(model) : undefined;
215262
const batchSize =
216263
savedBatch !== undefined && documentedCap !== undefined ? Math.min(savedBatch, documentedCap) : savedBatch;
@@ -221,7 +268,8 @@ async function embedderFromSettings(ctx: PluginContext): Promise<EmbedderFromSet
221268
: providerId === 'ollama'
222269
? 'ollama'
223270
: '';
224-
if (!preset && !baseUrl) {
271+
const endpoint = baseUrl || (preset ? OPENAI_COMPATIBLE_PRESETS[preset] : '');
272+
if (!endpoint) {
225273
return {
226274
kind: 'unconfigured',
227275
quiet: false,
@@ -231,7 +279,7 @@ async function embedderFromSettings(ctx: PluginContext): Promise<EmbedderFromSet
231279
try {
232280
const embedder = createOpenAIEmbedder({
233281
preset,
234-
baseUrl: baseUrl || undefined,
282+
baseUrl: endpoint,
235283
apiKey,
236284
model,
237285
dimensions,
@@ -245,6 +293,7 @@ async function embedderFromSettings(ctx: PluginContext): Promise<EmbedderFromSet
245293
model,
246294
batchSize,
247295
savedBatchSize: batchSize !== savedBatch ? savedBatch : undefined,
296+
endpointHost: hostOf(endpoint),
248297
};
249298
} catch (err) {
250299
// The embedder's own refusals name the option, never the key's value.
@@ -571,7 +620,7 @@ export class KnowledgeServicePlugin implements Plugin {
571620
ctx.registerService(EMBEDDER_SERVICE, outcome.embedder);
572621
ctx.logger.info?.(
573622
`KnowledgeServicePlugin: registered '${EMBEDDER_SERVICE}' from the ai.embedder_* settings ` +
574-
`(provider=${outcome.provider}, model=${outcome.model ?? '(embedder default)'}, ` +
623+
`(provider=${outcome.provider}, endpoint=${outcome.endpointHost}, model=${outcome.model ?? '(embedder default)'}, ` +
575624
`batch size=${outcome.batchSize ?? "the model's own cap"}` +
576625
`${outcome.savedBatchSize !== undefined ? ` — the saved ${outcome.savedBatchSize}, held to the model's documented cap` : ''}). ` +
577626
'A saved change takes effect on the next restart.',

0 commit comments

Comments
 (0)