Skip to content

Instantly share code, notes, and snippets.

@Dhravya
Created April 28, 2026 22:07
Show Gist options
  • Select an option

  • Save Dhravya/1aa176ff25c41a1bd1cf445ac7c953e3 to your computer and use it in GitHub Desktop.

Select an option

Save Dhravya/1aa176ff25c41a1bd1cf445ac7c953e3 to your computer and use it in GitHub Desktop.
formatting supermemory's results in token efficient way
// formatMemories.js — render a Supermemory search response as a token-efficient string.
export function formatMemories(response, opts = {}) {
const {
minSimilarity = 0,
maxRelations = 4,
maxDocuments = 3,
maxChunkLength = Infinity,
includeScores = true,
includeLegend = true,
} = opts;
const day = (s) => s?.slice(0, 10) ?? "";
const mime = (m) =>
!m ? "" :
m === "application/pdf" ? "pdf" :
m.includes("spreadsheet") ? "xlsx" :
m.includes("presentation") ? "pptx" :
m.includes("document") ? "doc" :
m.split("/").pop() ?? "";
const temporal = (tc) => {
if (!tc) return [];
const ev = (tc.eventDate ?? []).map(day).filter(Boolean);
return [
tc.documentDate && `doc ${day(tc.documentDate)}`,
ev.length === 1 && `event ${ev[0]}`,
ev.length > 1 && `event ${ev[0]}${ev.at(-1)}`,
].filter(Boolean);
};
const describeMeta = (m) => {
if (!m) return "";
const tags = [mime(m.mimeType), m.source, ...temporal(m.temporalContext)].filter(Boolean);
return [m.title && `"${m.title}"`, tags.length && `(${tags.join(", ")})`].filter(Boolean).join(" ");
};
const renderRelations = (rels, arrow, root) => {
if (!rels?.length) return [];
const seen = new Set();
const items = rels.filter((r) => {
const k = r.memory.trim();
if (k === root.trim() || seen.has(k)) return false;
seen.add(k);
return true;
});
const shown = items.slice(0, maxRelations);
const lines = shown.map((r) => {
const t = temporal(r.metadata?.temporalContext);
const when = t.length ? t.join(", ") : day(r.updatedAt);
return ` ${arrow} ${r.relation}${when ? `, ${when}` : ""}: ${r.memory}`;
});
if (items.length > shown.length) lines.push(` ${arrow} … +${items.length - shown.length} more`);
return lines;
};
const renderDocs = (ds) => (ds ?? []).slice(0, maxDocuments).map((d) => {
const title = d.title ? `"${d.title}"` : "(untitled)";
const type = d.type ? ` (${d.type})` : "";
const summary = d.summary ? ` — ${d.summary}` : "";
return ` Document: ${title}${type}${summary}`;
});
const results = (response.results ?? []).filter((m) => (m.similarity ?? 0) >= minSimilarity);
if (!results.length) return "No relevant memories found.";
const total = response.total ?? results.length;
const header = [
`${results.length} memor${results.length === 1 ? "y" : "ies"}` +
(total !== results.length ? ` of ${total}` : "") + ", ranked by relevance.",
includeLegend && "Markers: 'agg' = aggregated synthesis, 'chunk' = raw excerpt; ← parent, → child, ~ related.",
].filter(Boolean).join(" ");
const arrows = [["parents", "←"], ["children", "→"], ["related", "~"]];
const blocks = results.map((m) => {
const score = m.similarity?.toFixed(2) ?? "—";
const prefix = includeScores ? `${score} ` : "";
const memory = m.memory ?? "";
if (m.isAggregated) return `${prefix}agg ${memory}`;
if (m.chunk != null && m.memory == null) {
const body = m.chunk.replace(/\s+$/, "");
const text = body.length > maxChunkLength
? `${body.slice(0, maxChunkLength)} … [truncated, ${body.length - maxChunkLength} more chars]`
: body;
return [
`${prefix}chunk ${describeMeta(m.metadata)}`.trimEnd(),
...renderDocs(m.documents),
...text.split("\n").map((l) => ` ${l}`),
].join("\n");
}
const meta = describeMeta(m.metadata);
return [
`${prefix}${memory}`,
meta ? ` Source: ${meta}` : day(m.updatedAt) ? ` Source: updated ${day(m.updatedAt)}` : null,
...renderDocs(m.documents),
...arrows.flatMap(([k, a]) => renderRelations(m.context?.[k], a, memory)),
].filter(Boolean).join("\n");
});
return [header, "", blocks.join("\n\n")].join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment