Return type of the callback
The session context
Synchronous callback that uses logits - must not return a Promise
The result from the callback
// Compute entropy synchronously
const entropy = withLogits(ctx, (logits) => {
let maxLogit = logits[0];
for (let i = 1; i < logits.length; i++) {
if (logits[i] > maxLogit) maxLogit = logits[i];
}
let sumExp = 0;
for (let i = 0; i < logits.length; i++) {
sumExp += Math.exp(logits[i] - maxLogit);
}
let entropy = 0;
for (let i = 0; i < logits.length; i++) {
const p = Math.exp(logits[i] - maxLogit) / sumExp;
if (p > 0) entropy -= p * Math.log(p);
}
return entropy;
});
// Now safe to decode (previous logits buffer is revoked)
await ctx.decode([nextToken], position++);
Safe logits access with automatic lifetime management
Ensures logits are only accessed synchronously within the callback. The callback MUST NOT:
This prevents common bugs where logits become invalid due to async operations between access and usage.
How it works: