@rudra-js/core 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +175 -46
- package/dist/claim-screening.d.ts.map +1 -1
- package/dist/claim-screening.js +3 -9
- package/dist/claim-screening.js.map +1 -1
- package/dist/component-generator.d.ts +4 -1
- package/dist/component-generator.d.ts.map +1 -1
- package/dist/component-generator.js +95 -63
- package/dist/component-generator.js.map +1 -1
- package/dist/component-spec.d.ts +102 -12
- package/dist/component-spec.d.ts.map +1 -1
- package/dist/component-spec.js +4 -6
- package/dist/component-spec.js.map +1 -1
- package/dist/fallback-component.d.ts.map +1 -1
- package/dist/fallback-component.js +3 -3
- package/dist/fallback-component.js.map +1 -1
- package/dist/fit-to-shopper.d.ts +4 -1
- package/dist/fit-to-shopper.d.ts.map +1 -1
- package/dist/fit-to-shopper.js +8 -0
- package/dist/fit-to-shopper.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/model-prompt.d.ts.map +1 -1
- package/dist/model-prompt.js +16 -3
- package/dist/model-prompt.js.map +1 -1
- package/dist/product-display.d.ts +6 -0
- package/dist/product-display.d.ts.map +1 -0
- package/dist/product-display.js +32 -0
- package/dist/product-display.js.map +1 -0
- package/dist/reconciliation.d.ts +2 -4
- package/dist/reconciliation.d.ts.map +1 -1
- package/dist/reconciliation.js +15 -21
- package/dist/reconciliation.js.map +1 -1
- package/dist/schemas.d.ts +1 -0
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +1 -0
- package/dist/schemas.js.map +1 -1
- package/dist/signal-digest.d.ts.map +1 -1
- package/dist/signal-digest.js +2 -10
- package/dist/signal-digest.js.map +1 -1
- package/dist/spec-cache.d.ts +87 -7
- package/dist/spec-cache.d.ts.map +1 -1
- package/dist/spec-cache.js +20 -32
- package/dist/spec-cache.js.map +1 -1
- package/dist/tracking-input.d.ts.map +1 -1
- package/dist/tracking-input.js +8 -2
- package/dist/tracking-input.js.map +1 -1
- package/package.json +5 -4
- package/schemas/package.json +4 -0
- package/src/claim-screening.ts +3 -9
- package/src/component-generator.ts +126 -84
- package/src/component-spec.ts +6 -18
- package/src/fallback-component.ts +4 -3
- package/src/fit-to-shopper.ts +16 -1
- package/src/index.ts +1 -2
- package/src/model-prompt.ts +24 -3
- package/src/product-display.ts +43 -0
- package/src/reconciliation.ts +16 -23
- package/src/schemas.ts +6 -0
- package/src/signal-digest.ts +2 -8
- package/src/spec-cache.ts +24 -40
- package/src/tracking-input.ts +11 -2
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
1
|
import {
|
|
3
2
|
SPEC_VERSION,
|
|
4
3
|
generatedSpecSchema,
|
|
@@ -8,14 +7,16 @@ import {
|
|
|
8
7
|
type SpecSource,
|
|
9
8
|
} from './component-spec.js';
|
|
10
9
|
import { buildFallbackSpec } from './fallback-component.js';
|
|
11
|
-
import { buildPrompt } from './model-prompt.js';
|
|
10
|
+
import { buildPrompt, type PromptPair } from './model-prompt.js';
|
|
12
11
|
import type { ComponentProvider, TokenUsage } from './provider.js';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
12
|
+
import { reconcileSpec } from './reconciliation.js';
|
|
13
|
+
import type { RankOrder } from './product-selection.js';
|
|
14
|
+
import { fitCohortSpec } from './fit-to-shopper.js';
|
|
16
15
|
import { buildDigest, toCohortDigest, type SignalDigest } from './signal-digest.js';
|
|
17
16
|
import {
|
|
17
|
+
cachedSpecSchema,
|
|
18
18
|
createMemorySpecCache,
|
|
19
|
+
isNullSpecCache,
|
|
19
20
|
specCacheKey,
|
|
20
21
|
type CachedSpec,
|
|
21
22
|
type SpecCache,
|
|
@@ -36,6 +37,7 @@ export interface GenerationEvent {
|
|
|
36
37
|
degradedReason?: DegradedReason;
|
|
37
38
|
error?: unknown;
|
|
38
39
|
cache?: 'hit' | 'miss' | 'error' | 'timeout';
|
|
40
|
+
background?: true;
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
export interface ComponentGeneratorOptions {
|
|
@@ -45,6 +47,8 @@ export interface ComponentGeneratorOptions {
|
|
|
45
47
|
cacheTimeoutMs?: number;
|
|
46
48
|
generation?: 'cohort' | 'per-shopper';
|
|
47
49
|
rank?: RankOrder;
|
|
50
|
+
waitForModel?: boolean;
|
|
51
|
+
waitUntil?: (work: Promise<unknown>) => void;
|
|
48
52
|
onEvent?: (event: GenerationEvent) => void;
|
|
49
53
|
}
|
|
50
54
|
|
|
@@ -86,11 +90,6 @@ async function withinBudget<T>(
|
|
|
86
90
|
}
|
|
87
91
|
}
|
|
88
92
|
|
|
89
|
-
const cachedSpecSchema = z.object({
|
|
90
|
-
spec: generatedSpecSchema,
|
|
91
|
-
generatedAt: z.number(),
|
|
92
|
-
});
|
|
93
|
-
|
|
94
93
|
interface CacheRead {
|
|
95
94
|
outcome: NonNullable<GenerationEvent['cache']>;
|
|
96
95
|
entry?: CachedSpec;
|
|
@@ -99,16 +98,19 @@ interface CacheRead {
|
|
|
99
98
|
interface ModelCall {
|
|
100
99
|
spec: GeneratedSpec | null;
|
|
101
100
|
usage?: TokenUsage;
|
|
101
|
+
failedWrite?: { error: unknown };
|
|
102
102
|
}
|
|
103
103
|
|
|
104
104
|
interface Settings {
|
|
105
|
-
options: ComponentGeneratorOptions;
|
|
106
105
|
provider: ComponentProvider | null;
|
|
107
106
|
cache: SpecCache;
|
|
108
|
-
generation: '
|
|
107
|
+
generation: NonNullable<ComponentGeneratorOptions['generation']>;
|
|
109
108
|
rank: RankOrder;
|
|
110
109
|
modelTimeoutMs: number;
|
|
111
110
|
cacheTimeoutMs: number;
|
|
111
|
+
waitForModel: boolean;
|
|
112
|
+
waitUntil: ComponentGeneratorOptions['waitUntil'];
|
|
113
|
+
onEvent: ComponentGeneratorOptions['onEvent'];
|
|
112
114
|
inFlight: Map<string, Promise<ModelCall>>;
|
|
113
115
|
}
|
|
114
116
|
|
|
@@ -119,59 +121,32 @@ interface Run {
|
|
|
119
121
|
startedAt: number;
|
|
120
122
|
}
|
|
121
123
|
|
|
122
|
-
interface Trace {
|
|
123
|
-
calledModel: boolean;
|
|
124
|
-
cache: CacheRead['outcome'];
|
|
125
|
-
usage: TokenUsage | undefined;
|
|
126
|
-
error?: unknown;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
124
|
type Found =
|
|
130
|
-
| { spec: GeneratedSpec; generatedAt: number; source: 'cache' | 'llm';
|
|
131
|
-
| { failed: DegradedReason;
|
|
125
|
+
| { spec: GeneratedSpec; generatedAt: number; source: 'cache' | 'llm'; details: EventDetails }
|
|
126
|
+
| { failed: DegradedReason; details: EventDetails };
|
|
132
127
|
|
|
133
128
|
type EventDetails = Pick<
|
|
134
129
|
GenerationEvent,
|
|
135
130
|
'calledModel' | 'usage' | 'violations' | 'cache' | 'error'
|
|
136
131
|
>;
|
|
137
132
|
|
|
138
|
-
function fitCohortSpec(
|
|
139
|
-
spec: GeneratedSpec,
|
|
140
|
-
input: TrackingInput,
|
|
141
|
-
digest: SignalDigest,
|
|
142
|
-
rank: RankOrder,
|
|
143
|
-
): FittedSpec {
|
|
144
|
-
const picks = selectProducts(input, digest, { rank });
|
|
145
|
-
const blocks = capBlocks(spec.blocks);
|
|
146
|
-
|
|
147
|
-
const bundleAt = blocks.findIndex((block) => block.kind === 'bundle');
|
|
148
|
-
if (bundleAt === -1) return fitToShopper(spec, picks, digest.maxItems);
|
|
149
|
-
|
|
150
|
-
const heroesAbove = placeableHeroSkus(blocks.slice(0, bundleAt), input);
|
|
151
|
-
const bundle = bundleForShopper(input, digest, heroesAbove);
|
|
152
|
-
if (!bundle) return fitToShopper(spec, picks, digest.maxItems);
|
|
153
|
-
|
|
154
|
-
const spokenFor = new Set<string>(bundle.skus);
|
|
155
|
-
for (const sku of placeableHeroSkus(blocks, input)) spokenFor.add(sku);
|
|
156
|
-
|
|
157
|
-
const roomLeft = digest.maxItems - spokenFor.size;
|
|
158
|
-
if (roomLeft <= 0) return fitToShopper(spec, picks, digest.maxItems);
|
|
159
|
-
|
|
160
|
-
const forGrid = picks.filter((pick) => !spokenFor.has(pick.product.sku));
|
|
161
|
-
return fitToShopper(spec, forGrid, roomLeft);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
133
|
export function createComponentGenerator(
|
|
165
134
|
options: ComponentGeneratorOptions = {},
|
|
166
135
|
): ComponentGenerator {
|
|
136
|
+
const generation = options.generation ?? 'cohort';
|
|
137
|
+
const waitForModel = options.waitForModel ?? true;
|
|
138
|
+
if (!waitForModel) assertPagesCanBeServed(generation, options.cache);
|
|
139
|
+
|
|
167
140
|
const settings: Settings = {
|
|
168
|
-
options,
|
|
169
141
|
provider: options.provider ?? null,
|
|
170
142
|
cache: options.cache ?? createMemorySpecCache(),
|
|
171
|
-
generation
|
|
143
|
+
generation,
|
|
172
144
|
rank: options.rank ?? 'signals',
|
|
173
|
-
modelTimeoutMs: options.modelTimeoutMs ?? 1_500,
|
|
145
|
+
modelTimeoutMs: options.modelTimeoutMs ?? (waitForModel ? 1_500 : 30_000),
|
|
174
146
|
cacheTimeoutMs: options.cacheTimeoutMs ?? 50,
|
|
147
|
+
waitForModel,
|
|
148
|
+
waitUntil: options.waitUntil,
|
|
149
|
+
onEvent: options.onEvent,
|
|
175
150
|
inFlight: new Map(),
|
|
176
151
|
};
|
|
177
152
|
|
|
@@ -181,18 +156,37 @@ export function createComponentGenerator(
|
|
|
181
156
|
};
|
|
182
157
|
}
|
|
183
158
|
|
|
159
|
+
function assertPagesCanBeServed(
|
|
160
|
+
generation: Settings['generation'],
|
|
161
|
+
cache: SpecCache | undefined,
|
|
162
|
+
): void {
|
|
163
|
+
if (generation === 'per-shopper') {
|
|
164
|
+
throw new RangeError(
|
|
165
|
+
"waitForModel: false needs generation: 'cohort'. A per-shopper prompt changes with " +
|
|
166
|
+
'almost every view, so the call it starts would almost never reach a page.',
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
if (cache && isNullSpecCache(cache)) {
|
|
170
|
+
throw new RangeError(
|
|
171
|
+
'waitForModel: false needs a cache that keeps entries. Pages only get the answer ' +
|
|
172
|
+
'from the cache, so with createNullSpecCache() no call would ever reach one.',
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
184
177
|
async function generate(settings: Settings, draft: TrackingInputDraft): Promise<ComponentSpec> {
|
|
185
178
|
const run = startRun(settings, draft);
|
|
186
179
|
const provider = settings.provider;
|
|
187
180
|
if (!provider) return fallback(settings, run, null, 'no-provider');
|
|
188
181
|
|
|
189
|
-
const
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
182
|
+
const prompt = buildPrompt(run.input, run.promptDigest);
|
|
183
|
+
const key = specCacheKey(prompt, provider);
|
|
184
|
+
const found = await findSpec(settings, provider, prompt, key);
|
|
185
|
+
if ('failed' in found) return fallback(settings, run, key, found.failed, found.details);
|
|
193
186
|
|
|
194
187
|
const reconciled = shapeForShopper(settings, run, found.spec);
|
|
195
|
-
const
|
|
188
|
+
const { usage, ...seen } = found.details;
|
|
189
|
+
const details = { ...seen, violations: reconciled.violations, ...(usage ? { usage } : {}) };
|
|
196
190
|
if (!reconciled.isUsable) return fallback(settings, run, key, 'unusable-on-serve', details);
|
|
197
191
|
|
|
198
192
|
const finishedAt = Date.now();
|
|
@@ -227,39 +221,39 @@ function startRun(settings: Settings, draft: TrackingInputDraft): Run {
|
|
|
227
221
|
return { input, digest, promptDigest, startedAt };
|
|
228
222
|
}
|
|
229
223
|
|
|
230
|
-
function cacheKeyFor(provider: ComponentProvider, run: Run): string {
|
|
231
|
-
const identity = { name: provider.name, model: provider.model };
|
|
232
|
-
const skus = run.input.candidates.map((product) => product.sku);
|
|
233
|
-
return specCacheKey(run.promptDigest, skus, identity);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
224
|
async function findSpec(
|
|
237
225
|
settings: Settings,
|
|
238
226
|
provider: ComponentProvider,
|
|
239
|
-
|
|
227
|
+
prompt: PromptPair,
|
|
240
228
|
key: string,
|
|
241
229
|
): Promise<Found> {
|
|
242
230
|
const read = await readCache(settings, key);
|
|
243
231
|
if (read.entry) {
|
|
244
|
-
const
|
|
245
|
-
return { spec: read.entry.spec, generatedAt: read.entry.generatedAt, source: 'cache',
|
|
232
|
+
const details = { calledModel: false, cache: read.outcome };
|
|
233
|
+
return { spec: read.entry.spec, generatedAt: read.entry.generatedAt, source: 'cache', details };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (!settings.waitForModel) {
|
|
237
|
+
if (read.outcome === 'miss') fillInBackground(settings, provider, prompt, key);
|
|
238
|
+
return { failed: 'not-cached', details: { calledModel: false, cache: read.outcome } };
|
|
246
239
|
}
|
|
247
240
|
|
|
248
241
|
const calledModel = !settings.inFlight.has(key);
|
|
249
242
|
let call: ModelCall;
|
|
250
243
|
try {
|
|
251
|
-
call = await sharedCall(settings, key, () => askModel(settings, provider,
|
|
244
|
+
call = await sharedCall(settings, key, () => askModel(settings, provider, prompt));
|
|
252
245
|
} catch (error) {
|
|
253
246
|
const failed = error instanceof TimeoutError ? 'timeout' : 'provider-error';
|
|
254
|
-
return { failed,
|
|
247
|
+
return { failed, details: { calledModel, cache: read.outcome, error } };
|
|
255
248
|
}
|
|
256
249
|
|
|
257
|
-
const
|
|
258
|
-
if (
|
|
250
|
+
const details: EventDetails = { calledModel, cache: read.outcome };
|
|
251
|
+
if (call.usage) details.usage = call.usage;
|
|
252
|
+
if (!call.spec) return { failed: 'invalid-generation', details };
|
|
259
253
|
|
|
260
254
|
const generatedAt = Date.now();
|
|
261
255
|
if (calledModel) storeInBackground(settings, key, { spec: call.spec, generatedAt });
|
|
262
|
-
return { spec: call.spec, generatedAt, source: 'llm',
|
|
256
|
+
return { spec: call.spec, generatedAt, source: 'llm', details };
|
|
263
257
|
}
|
|
264
258
|
|
|
265
259
|
async function readCache(settings: Settings, key: string): Promise<CacheRead> {
|
|
@@ -277,11 +271,15 @@ async function readCache(settings: Settings, key: string): Promise<CacheRead> {
|
|
|
277
271
|
async function askModel(
|
|
278
272
|
settings: Settings,
|
|
279
273
|
provider: ComponentProvider,
|
|
280
|
-
|
|
274
|
+
prompt: PromptPair,
|
|
281
275
|
): Promise<ModelCall> {
|
|
282
|
-
const { system, user } = buildPrompt(run.input, run.promptDigest);
|
|
283
276
|
const result = await withinBudget('generation', settings.modelTimeoutMs, (signal) =>
|
|
284
|
-
provider.generate({
|
|
277
|
+
provider.generate({
|
|
278
|
+
system: prompt.system,
|
|
279
|
+
user: prompt.user,
|
|
280
|
+
schema: generatedSpecSchema,
|
|
281
|
+
signal,
|
|
282
|
+
}),
|
|
285
283
|
);
|
|
286
284
|
const parsed = generatedSpecSchema.safeParse(result.spec);
|
|
287
285
|
return {
|
|
@@ -302,6 +300,61 @@ function sharedCall(
|
|
|
302
300
|
return started;
|
|
303
301
|
}
|
|
304
302
|
|
|
303
|
+
function fillInBackground(
|
|
304
|
+
settings: Settings,
|
|
305
|
+
provider: ComponentProvider,
|
|
306
|
+
prompt: PromptPair,
|
|
307
|
+
key: string,
|
|
308
|
+
): void {
|
|
309
|
+
if (settings.inFlight.has(key)) return;
|
|
310
|
+
|
|
311
|
+
const startedAt = Date.now();
|
|
312
|
+
const finished = (
|
|
313
|
+
source: SpecSource,
|
|
314
|
+
details: Pick<GenerationEvent, 'cache' | 'error' | 'usage' | 'degradedReason'>,
|
|
315
|
+
) =>
|
|
316
|
+
report(settings, {
|
|
317
|
+
key,
|
|
318
|
+
source,
|
|
319
|
+
elapsedMs: Date.now() - startedAt,
|
|
320
|
+
calledModel: true,
|
|
321
|
+
...details,
|
|
322
|
+
background: true,
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const askAndStore = async (): Promise<ModelCall> => {
|
|
326
|
+
const call = await askModel(settings, provider, prompt);
|
|
327
|
+
if (!call.spec) return call;
|
|
328
|
+
try {
|
|
329
|
+
await settings.cache.set(key, { spec: call.spec, generatedAt: Date.now() });
|
|
330
|
+
return call;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
return { ...call, failedWrite: { error } };
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const work = sharedCall(settings, key, askAndStore).then(
|
|
337
|
+
(call) => {
|
|
338
|
+
const usage = call.usage ? { usage: call.usage } : {};
|
|
339
|
+
if (!call.spec) {
|
|
340
|
+
finished('fallback', { ...usage, degradedReason: 'invalid-generation' });
|
|
341
|
+
} else if (call.failedWrite) {
|
|
342
|
+
finished('fallback', { cache: 'error', error: call.failedWrite.error, ...usage });
|
|
343
|
+
} else {
|
|
344
|
+
finished('llm', usage);
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
(error: unknown) => {
|
|
348
|
+
const degradedReason = error instanceof TimeoutError ? 'timeout' : 'provider-error';
|
|
349
|
+
finished('fallback', { error, degradedReason });
|
|
350
|
+
},
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
try {
|
|
354
|
+
settings.waitUntil?.(work);
|
|
355
|
+
} catch {}
|
|
356
|
+
}
|
|
357
|
+
|
|
305
358
|
function storeInBackground(settings: Settings, key: string, cached: CachedSpec): void {
|
|
306
359
|
void Promise.resolve()
|
|
307
360
|
.then(() => settings.cache.set(key, cached))
|
|
@@ -345,19 +398,8 @@ function fallback(
|
|
|
345
398
|
};
|
|
346
399
|
}
|
|
347
400
|
|
|
348
|
-
function eventDetails(trace: Trace, violations?: string[]): EventDetails {
|
|
349
|
-
return {
|
|
350
|
-
calledModel: trace.calledModel,
|
|
351
|
-
cache: trace.cache,
|
|
352
|
-
...(violations ? { violations } : {}),
|
|
353
|
-
...(trace.usage ? { usage: trace.usage } : {}),
|
|
354
|
-
...('error' in trace ? { error: trace.error } : {}),
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
|
|
358
401
|
function report(settings: Settings, event: GenerationEvent): void {
|
|
359
|
-
if (!settings.options.onEvent) return;
|
|
360
402
|
try {
|
|
361
|
-
settings.
|
|
403
|
+
settings.onEvent?.(event);
|
|
362
404
|
} catch {}
|
|
363
405
|
}
|
package/src/component-spec.ts
CHANGED
|
@@ -40,6 +40,8 @@ const gridBlockSchema = z.object({
|
|
|
40
40
|
items: z.array(productReferenceSchema),
|
|
41
41
|
});
|
|
42
42
|
|
|
43
|
+
export const GRID_COLUMNS = gridBlockSchema.shape.columns.options.map((option) => option.value);
|
|
44
|
+
|
|
43
45
|
export function columnsFor(count: number, widest: 2 | 3 | 4): 2 | 3 | 4 {
|
|
44
46
|
return Math.min(widest, Math.max(2, count)) as 2 | 3 | 4;
|
|
45
47
|
}
|
|
@@ -109,22 +111,12 @@ const DEGRADED_REASONS = [
|
|
|
109
111
|
'invalid-generation',
|
|
110
112
|
'unusable-on-serve',
|
|
111
113
|
'requested',
|
|
114
|
+
'not-cached',
|
|
112
115
|
] as const;
|
|
113
116
|
export type DegradedReason = (typeof DEGRADED_REASONS)[number];
|
|
114
117
|
|
|
115
118
|
export const SPEC_VERSION = '1' as const;
|
|
116
119
|
|
|
117
|
-
export interface ComponentSpec extends GeneratedSpec {
|
|
118
|
-
specVersion: typeof SPEC_VERSION;
|
|
119
|
-
slot: string;
|
|
120
|
-
source: SpecSource;
|
|
121
|
-
generatedAt: number;
|
|
122
|
-
latencyMs: number;
|
|
123
|
-
provider: string | null;
|
|
124
|
-
model: string | null;
|
|
125
|
-
degradedReason?: DegradedReason;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
120
|
const componentSpecSchema = generatedSpecSchema.extend({
|
|
129
121
|
specVersion: z.literal(SPEC_VERSION),
|
|
130
122
|
slot: z.string(),
|
|
@@ -133,16 +125,12 @@ const componentSpecSchema = generatedSpecSchema.extend({
|
|
|
133
125
|
latencyMs: z.number(),
|
|
134
126
|
provider: z.string().nullable(),
|
|
135
127
|
model: z.string().nullable(),
|
|
136
|
-
degradedReason: z.enum(DEGRADED_REASONS).
|
|
128
|
+
degradedReason: z.enum(DEGRADED_REASONS).exactOptional(),
|
|
137
129
|
});
|
|
130
|
+
export type ComponentSpec = z.infer<typeof componentSpecSchema>;
|
|
138
131
|
|
|
139
132
|
export function parseComponentSpec(value: unknown): ComponentSpec {
|
|
140
|
-
|
|
141
|
-
return degradedReason === undefined ? spec : { ...spec, degradedReason };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export function parseGeneratedSpec(value: unknown): GeneratedSpec {
|
|
145
|
-
return generatedSpecSchema.parse(value);
|
|
133
|
+
return componentSpecSchema.parse(value);
|
|
146
134
|
}
|
|
147
135
|
|
|
148
136
|
export function safeParseGeneratedSpec(value: unknown): GeneratedSpecResult {
|
|
@@ -43,8 +43,9 @@ export function buildFallbackSpec(
|
|
|
43
43
|
items.length === 0
|
|
44
44
|
? []
|
|
45
45
|
: [{ kind: 'grid', title: null, columns: columnsFor(items.length, 4), items }],
|
|
46
|
-
rationale:
|
|
47
|
-
|
|
48
|
-
|
|
46
|
+
rationale:
|
|
47
|
+
options.rank === 'given'
|
|
48
|
+
? 'Deterministic: kept in the order the candidates were sent.'
|
|
49
|
+
: 'Deterministic: ranked by category interest (the browsed category counts too), views, rating and shared tags.',
|
|
49
50
|
};
|
|
50
51
|
}
|
package/src/fit-to-shopper.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { Block, GeneratedSpec, ProductReference } from './component-spec.js';
|
|
2
|
-
import type
|
|
2
|
+
import { selectProducts, type ProductPick, type RankOrder } from './product-selection.js';
|
|
3
|
+
import { heroAndSetSkus } from './reconciliation.js';
|
|
4
|
+
import type { SignalDigest } from './signal-digest.js';
|
|
5
|
+
import type { TrackingInput } from './tracking-input.js';
|
|
3
6
|
|
|
4
7
|
export interface FittedSpec {
|
|
5
8
|
spec: GeneratedSpec;
|
|
@@ -41,3 +44,15 @@ export function fitToShopper(
|
|
|
41
44
|
|
|
42
45
|
return { spec: { ...spec, blocks }, ourReasons };
|
|
43
46
|
}
|
|
47
|
+
|
|
48
|
+
export function fitCohortSpec(
|
|
49
|
+
spec: GeneratedSpec,
|
|
50
|
+
input: TrackingInput,
|
|
51
|
+
digest: SignalDigest,
|
|
52
|
+
rank: RankOrder,
|
|
53
|
+
): FittedSpec {
|
|
54
|
+
const spokenFor = heroAndSetSkus(spec.blocks, input, digest);
|
|
55
|
+
const picks = selectProducts(input, digest, { rank });
|
|
56
|
+
const forGrid = picks.filter((pick) => !spokenFor.has(pick.product.sku));
|
|
57
|
+
return fitToShopper(spec, forGrid, digest.maxItems - spokenFor.size);
|
|
58
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -43,7 +43,6 @@ export {
|
|
|
43
43
|
blockSchema,
|
|
44
44
|
generatedSpecSchema,
|
|
45
45
|
parseComponentSpec,
|
|
46
|
-
parseGeneratedSpec,
|
|
47
46
|
productReferenceSchema,
|
|
48
47
|
safeParseGeneratedSpec,
|
|
49
48
|
type BannerBlock,
|
|
@@ -64,7 +63,7 @@ export {
|
|
|
64
63
|
} from './component-spec.js';
|
|
65
64
|
|
|
66
65
|
export { reconcileSpec, type ReconcileResult } from './reconciliation.js';
|
|
67
|
-
export { selectProducts, type ProductPick } from './product-selection.js';
|
|
66
|
+
export { selectProducts, type ProductPick, type RankOrder } from './product-selection.js';
|
|
68
67
|
|
|
69
68
|
export {
|
|
70
69
|
createFixedSpecProvider,
|
package/src/model-prompt.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
BANNER_TONES,
|
|
3
|
+
EMPHASIS,
|
|
4
|
+
GRID_COLUMNS,
|
|
5
|
+
RECOMMENDATION_BASES,
|
|
6
|
+
TONES,
|
|
7
|
+
} from './component-spec.js';
|
|
2
8
|
import type { SignalDigest } from './signal-digest.js';
|
|
3
9
|
import { FIELD_LIMITS, type Product, type TrackingInput } from './tracking-input.js';
|
|
4
10
|
|
|
@@ -12,6 +18,21 @@ export interface PromptPair {
|
|
|
12
18
|
|
|
13
19
|
const quotedList = (values: readonly string[]) => values.map((value) => `"${value}"`).join(', ');
|
|
14
20
|
|
|
21
|
+
const NUMBER_WORDS = [
|
|
22
|
+
'zero',
|
|
23
|
+
'one',
|
|
24
|
+
'two',
|
|
25
|
+
'three',
|
|
26
|
+
'four',
|
|
27
|
+
'five',
|
|
28
|
+
'six',
|
|
29
|
+
'seven',
|
|
30
|
+
'eight',
|
|
31
|
+
'nine',
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const inWords = (count: number) => NUMBER_WORDS[count] ?? String(count);
|
|
35
|
+
|
|
15
36
|
export const SYSTEM_PROMPT = `You design one recommendation component for one shopper on an
|
|
16
37
|
e-commerce page. You return JSON matching the schema you were given, and nothing else.
|
|
17
38
|
|
|
@@ -46,7 +67,7 @@ Blocks never nest.
|
|
|
46
67
|
|
|
47
68
|
- "hero" — one large statement, optionally anchored to a single product. Use
|
|
48
69
|
when one product clearly dominates what the shopper seems to want.
|
|
49
|
-
- "grid" — a titled grid of
|
|
70
|
+
- "grid" — a titled grid of ${GRID_COLUMNS.slice(0, -1).join(', ')} or ${GRID_COLUMNS.at(-1)} columns. The general choice when several
|
|
50
71
|
products are comparably relevant.
|
|
51
72
|
- "carousel" — a row read left to right. Use when the order means something.
|
|
52
73
|
- "banner" — a single line of merchandising copy, with a tone of ${quotedList(BANNER_TONES)}.
|
|
@@ -59,7 +80,7 @@ Blocks never nest.
|
|
|
59
80
|
products: you are never shown which set the shop will pick, so words about
|
|
60
81
|
the things in it end up beside a different set. Never say a set saves money,
|
|
61
82
|
and never say by how much — you are not told any of the prices. Every product
|
|
62
|
-
in a set spends one of your product slots, and a set holds two to
|
|
83
|
+
in a set spends one of your product slots, and a set holds two to ${inWords(FIELD_LIMITS.productsPerBundle)} of
|
|
63
84
|
them.
|
|
64
85
|
|
|
65
86
|
Each product you place carries an "emphasis" of ${quotedList(EMPHASIS)}.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Bundle, Product } from './tracking-input.js';
|
|
2
|
+
|
|
3
|
+
export function defaultHrefForSku(sku: string): string {
|
|
4
|
+
return `/product/${encodeURIComponent(sku)}`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function findSellableProduct(
|
|
8
|
+
products: ReadonlyMap<string, Product>,
|
|
9
|
+
sku: string,
|
|
10
|
+
): Product | undefined {
|
|
11
|
+
const product = products.get(sku);
|
|
12
|
+
return product?.isInStock === false ? undefined : product;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function formatMoney(price: number, currency: string, locale?: string): string {
|
|
16
|
+
let formatter: Intl.NumberFormat;
|
|
17
|
+
try {
|
|
18
|
+
formatter = new Intl.NumberFormat(locale, { style: 'currency', currency });
|
|
19
|
+
} catch {
|
|
20
|
+
return `${currency} ${price}`;
|
|
21
|
+
}
|
|
22
|
+
return formatter.format(price);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function defaultFormatPrice(product: Product, locale?: string): string {
|
|
26
|
+
if (!Number.isFinite(product.price)) {
|
|
27
|
+
throw new TypeError(
|
|
28
|
+
`price for SKU ${product.sku} is ${String(product.price)}, not a finite number. ` +
|
|
29
|
+
'Catalog objects must satisfy productSchema from @rudra-js/core',
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return formatMoney(product.price, product.currency, locale);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function defaultFormatBundlePrice(bundle: Bundle, locale?: string): string {
|
|
36
|
+
if (!Number.isFinite(bundle.price)) {
|
|
37
|
+
throw new TypeError(
|
|
38
|
+
`price for bundle ${bundle.id} is ${String(bundle.price)}, not a finite number. ` +
|
|
39
|
+
'Bundle objects must satisfy bundleSchema from @rudra-js/core',
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return formatMoney(bundle.price, bundle.currency, locale);
|
|
43
|
+
}
|
package/src/reconciliation.ts
CHANGED
|
@@ -24,10 +24,6 @@ const CLAMP = {
|
|
|
24
24
|
|
|
25
25
|
export const MAX_BLOCKS = 4;
|
|
26
26
|
|
|
27
|
-
export function capBlocks(blocks: Block[]): Block[] {
|
|
28
|
-
return blocks.slice(0, MAX_BLOCKS);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
27
|
export interface ReconcileResult {
|
|
32
28
|
spec: GeneratedSpec;
|
|
33
29
|
isUsable: boolean;
|
|
@@ -253,27 +249,24 @@ function chooseBundle(run: Run): Bundle | undefined {
|
|
|
253
249
|
return best;
|
|
254
250
|
}
|
|
255
251
|
|
|
256
|
-
export function
|
|
252
|
+
export function heroAndSetSkus(
|
|
253
|
+
blocks: Block[],
|
|
257
254
|
input: TrackingInput,
|
|
258
255
|
digest: SignalDigest,
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const blocked = blockedForPicks(input);
|
|
270
|
-
const skus: string[] = [];
|
|
271
|
-
for (const block of blocks) {
|
|
272
|
-
if (block.kind !== 'hero' || block.sku === null) continue;
|
|
273
|
-
if (!allowed.has(block.sku) || blocked.has(block.sku)) continue;
|
|
274
|
-
if (!skus.includes(block.sku)) skus.push(block.sku);
|
|
256
|
+
): ReadonlySet<string> {
|
|
257
|
+
const heroes = startRun(input, digest, new Map());
|
|
258
|
+
let setSkus: readonly string[] | undefined;
|
|
259
|
+
let listAbove = false;
|
|
260
|
+
|
|
261
|
+
for (const block of blocks.slice(0, MAX_BLOCKS)) {
|
|
262
|
+
if (block.kind === 'hero' && block.sku !== null) takeSlot(block.sku, heroes);
|
|
263
|
+
if (setSkus !== undefined) continue;
|
|
264
|
+
if (block.kind === 'bundle') setSkus = chooseBundle(heroes)?.skus ?? [];
|
|
265
|
+
if (block.kind === 'grid' || block.kind === 'carousel') listAbove ||= block.items.length > 0;
|
|
275
266
|
}
|
|
276
|
-
|
|
267
|
+
|
|
268
|
+
const withSet = new Set([...heroes.placed, ...(setSkus ?? [])]);
|
|
269
|
+
return listAbove && withSet.size >= digest.maxItems ? heroes.placed : withSet;
|
|
277
270
|
}
|
|
278
271
|
|
|
279
272
|
function reconcileBlock(block: Block, run: Run): Block | null {
|
|
@@ -390,7 +383,7 @@ export function reconcileSpec(
|
|
|
390
383
|
}
|
|
391
384
|
|
|
392
385
|
const blocks: Block[] = [];
|
|
393
|
-
for (const block of
|
|
386
|
+
for (const block of generated.blocks.slice(0, MAX_BLOCKS)) {
|
|
394
387
|
const reconciled = reconcileBlock(block, run);
|
|
395
388
|
if (reconciled !== null) blocks.push(reconciled);
|
|
396
389
|
}
|
package/src/schemas.ts
CHANGED
package/src/signal-digest.ts
CHANGED
|
@@ -150,14 +150,8 @@ function mergeViewsBySku(views: ViewSignal[]): MergedView[] {
|
|
|
150
150
|
const totals = new Map<string, MergedView>();
|
|
151
151
|
|
|
152
152
|
for (const view of views) {
|
|
153
|
-
const total = totals.get(view.sku);
|
|
154
|
-
|
|
155
|
-
const first: MergedView = { sku: view.sku, views: view.views, weight: weightOf(view) };
|
|
156
|
-
if (view.dwellMs !== undefined) first.dwellMs = view.dwellMs;
|
|
157
|
-
if (view.category !== undefined) first.category = view.category;
|
|
158
|
-
totals.set(view.sku, first);
|
|
159
|
-
continue;
|
|
160
|
-
}
|
|
153
|
+
const total = totals.get(view.sku) ?? { sku: view.sku, views: 0, weight: -Infinity };
|
|
154
|
+
totals.set(view.sku, total);
|
|
161
155
|
|
|
162
156
|
total.views += view.views;
|
|
163
157
|
if (view.dwellMs !== undefined) total.dwellMs = (total.dwellMs ?? 0) + view.dwellMs;
|