SPB Git forge

spb/doc-api

Public
2commits 1branches 0releases
15.7 MBsize
maindefault branch
14 days agolast push
Python 88.3% TypeScript 7.6% Shell 4.1%
2.4 KB · 37 lines typescript
Raw Blame History
1/**2 * On-demand compaction (beta compact-2026-09-04) with the Node SDK on claude-sonnet-5: send the conversation with3 * top-level compaction {type:"summarize"} → a single signed `compaction` block, stop_reason "compaction",4 * usage.iterations [{type:"compaction"}]. Then continue by sending the block FIRST in messages.5 * STATUS: LIVE_VERIFIED 2026-09-18: summary block + signature returned; continuation answered "Ada … teal" (~$0.002).6 * Run: node --env-file=.env --experimental-strip-types examples/anthropic/context-management/compaction_on_demand.ts7 */8import Anthropic from "@anthropic-ai/sdk";9import { appendFileSync } from "node:fs";1011const MODEL = process.env.ANTHROPIC_MODEL ?? "claude-sonnet-5";12const client = new Anthropic({ maxRetries: 1 });13const log = (status: number, note: string, cost: number) =>14  appendFileSync("reports/live-requests.jsonl", JSON.stringify({ ts: new Date().toISOString(), provider: "anthropic", method: "POST", path: "/v1/messages", status, est_cost_usd: cost, note }) + "\n");1516const history = [17  { role: "user", content: "My name is Ada and I like teal." },18  { role: "assistant", content: "Nice to meet you, Ada." },19];20// 1) Summarize (no reply is generated; max_tokens caps the summary incl. thinking)21const summary = await client.beta.messages.create({22  model: MODEL, max_tokens: 400, betas: ["compact-2026-09-04"],23  compaction: { type: "summarize" }, messages: history,24} as any);25const block = summary.content[0] as any;26console.log("stop_reason:", summary.stop_reason, "| block:", block.type, "| signature:", String(block.signature).slice(0, 24) + "…");27console.log("summary:", block.content, "| iterations:", (summary.usage as any).iterations);28log(200, `example context-management/compaction_on_demand.ts summarize ${MODEL} beta=compact-2026-09-04`, 0.0015);2930// 2) Continue: the block goes FIRST, in place of the summarized messages (leaving them in front → 400 compaction_block_misplaced)31const next = await client.beta.messages.create({32  model: MODEL, max_tokens: 30, betas: ["compact-2026-09-04"],33  messages: [{ role: "assistant", content: [block] }, { role: "user", content: "What is my name and favourite color? Five words." }],34} as any);35console.log("continuation:", next.content[0].type === "text" ? next.content[0].text : next.content[0].type);36log(200, `example context-management/compaction_on_demand.ts continue ${MODEL}`, 0.0005);37