Cut the Cost per Question

The quota from Set Budgets and Per-Hiker Quotas stops a script, but an ordinary question still costs what it did. In Observing AI Features, most of that cost came from beds questions that called the hut-availability tool for hut after hut, with each round resending the conversation.

In this lesson, you’ll check whether that remains true now that every round also resends the reports block, then cut the cost one change at a time and show that the answers still hold.

Find Today’s Biggest Cost

The download’s traces/recorded-day.jsonl holds 100 questions recorded on the app as it stands. Save scripts/cost-by-kind.js. It prices every model span with callCost() and sorts it into beds or conditions by its asked.topics. The overall total includes every question, so a cached answer counts as costing nothing:

Language: JavaScript Filename: scripts/cost-by-kind.js
import { readFileSync } from "node:fs";
import { callCost } from "../model/prices.js";

const kinds = {};
const asked = new Set();
const seen = new Set();
for (const line of readFileSync(process.argv[2], "utf8")
  .split("\n")) {
  if (!line.startsWith("{")) continue;
  const s = JSON.parse(line);
  asked.add(s.traceId);
  if (s.name !== "model" || !s.tokens) continue;
  const kind = s.asked?.topics?.includes("beds")
    ? "beds" : "conditions";
  const k = (kinds[kind] ??= { questions: 0, calls: 0, cost: 0 });
  if (!seen.has(s.traceId)) k.questions++;
  seen.add(s.traceId);
  k.calls++;
  k.cost += callCost(s);
}

Below the loop, print the cost per thousand questions for each kind and for the day overall:

Language: JavaScript Filename: scripts/cost-by-kind.js
const perThousand = (k) =>
  `$${((k.cost / k.questions) * 1000).toFixed(2)} per 1,000`;
const all = { questions: asked.size, cost: 0 };
for (const [kind, k] of Object.entries(kinds)) {
  console.log(`${kind}: ${k.questions} questions, ` +
    `${k.calls} calls, ${perThousand(k)}`);
  all.cost += k.cost;
}
console.log(`all ${all.questions} questions: ${perThousand(all)}`);

Run it on the recorded day:

Language: Text
$ node scripts/cost-by-kind.js traces/recorded-day.jsonl
beds: 30 questions, 107 calls, $3.09 per 1,000
conditions: 70 questions, 140 calls, $1.48 per 1,000
all 100 questions: $1.96 per 1,000

Beds questions still cost twice as much as conditions questions. A round is one model reply, which can ask about several huts. Five beds questions made seven to twelve tool calls in up to five rounds.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.