@boldare/askdare 0.5.1 → 0.5.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @boldare/askdare
2
2
 
3
+ ## 0.5.3
4
+
5
+ ### Patch Changes
6
+
7
+ - fe4de07: The token budget reserved before each model call now counts a conversation's history once. Before, after a message in which the bot called tools, the next message reserved the input of all its model calls, about three times the history after one with three calls, so long conversations with tool-using bots ran out of `dailyTokensPerIp` a few turns early. Real usage still replaces the reservation when the message ends, and `onUsage` still reports the summed counts. Nothing to change.
8
+
9
+ ## 0.5.2
10
+
11
+ ### Patch Changes
12
+
13
+ - 1cbfce3: Token budgets now count input read from the prompt cache as a tenth of a token, close to what it costs. Before, `dailyTokens`, `dailyTokensPerIp` and `globalDailyTokens` charged it at full weight, so a long conversation ran out of the default per-IP budget after about 13 turns while costing cents. Everything else (other input, cache writes, output) still counts as whole tokens, and the estimate reserved before each model call is unchanged. `onUsage` still reports the raw token counts from OpenAI.
14
+
15
+ Budgets now last longer for conversations with a warm cache; the money ceiling in the cost guide still holds when you take 10 × the cached-input price into account. Nothing to change unless you sized your budgets for full-weight cached input.
16
+ - 5dbcb19: Answers no longer show the same citation marker twice in a row: `[1] [1]` and `[1][1]` become `[1]`, while streaming and in reloaded history. A Responses-compatible server that leaves out the optional usage details (`input_tokens_details`, `output_tokens_details`) no longer fails the turn; the missing counts are reported as 0.
17
+
3
18
  ## 0.5.1
4
19
 
5
20
  ### Patch Changes
package/dist/events.d.ts CHANGED
@@ -354,9 +354,15 @@ interface BotLimits {
354
354
  readonly maxSteps?: number;
355
355
  /** Server-side deadline for a whole turn. Keep it below your route's `maxDuration`. Default 120 s. */
356
356
  readonly turnTimeoutMs?: number;
357
- /** Input plus output tokens per UTC day across all visitors; then `budget_exceeded`. Default 2 000 000. */
357
+ /**
358
+ * Input plus output tokens per UTC day across all visitors; then `budget_exceeded`. Input read
359
+ * from the prompt cache counts as a tenth of a token. Default 2 000 000.
360
+ */
358
361
  readonly dailyTokens?: number;
359
- /** Input plus output tokens per client IP per UTC day. Default 200 000. */
362
+ /**
363
+ * Input plus output tokens per client IP per UTC day, with input read from the prompt cache
364
+ * counted as a tenth of a token. Default 200 000.
365
+ */
360
366
  readonly dailyTokensPerIp?: number;
361
367
  /** New sessions per client IP per hour (renewals by returning visitors count separately). Default 30. */
362
368
  readonly sessionsPerIpPerHour?: number;
package/dist/next.d.ts CHANGED
@@ -214,7 +214,10 @@ interface ChatHandlerLimitsOptions {
214
214
  readonly store?: RateLimitStore;
215
215
  /** How to read the client IP behind your proxy. Default `auto` (Vercel, otherwise one proxy). */
216
216
  readonly trustProxy?: TrustProxy;
217
- /** Input plus output tokens per UTC day across all bots. Unlimited by default. */
217
+ /**
218
+ * Input plus output tokens per UTC day across all bots, with input read from the prompt cache
219
+ * counted as a tenth of a token. Unlimited by default.
220
+ */
218
221
  readonly globalDailyTokens?: number;
219
222
  /**
220
223
  * Refuse to start without a shared `store`, instead of warning in production that limits are
package/dist/next.js CHANGED
@@ -83,6 +83,21 @@ const IN_FLIGHT_WINDOW = 2 * MINUTE;
83
83
  /** Rough input cost of one file search chunk (about 800 tokens by default). */
84
84
  const SEARCH_RESULT_TOKENS = 800;
85
85
  /**
86
+ * Input read from the prompt cache costs a tenth of other input on most models (OpenAI's prompt
87
+ * caching guide, checked 2026-11-23), so budgets charge it at a tenth (ADR-0004).
88
+ */
89
+ const CACHED_INPUT_DIVISOR = 10;
90
+ /**
91
+ * What a turn's usage costs the budgets: cached input at a tenth, rounded up, and everything else
92
+ * (other input, cache writes, output) at full weight. A missing or impossible cached count counts
93
+ * as 0 cached, so the whole input is charged.
94
+ */
95
+ function budgetTokens(usage) {
96
+ const reported = usage.cachedInputTokens;
97
+ const cached = Number.isFinite(reported) ? Math.min(Math.max(reported, 0), usage.inputTokens) : 0;
98
+ return usage.inputTokens - cached + Math.ceil(cached / CACHED_INPUT_DIVISOR) + usage.outputTokens;
99
+ }
100
+ /**
86
101
  * Bounds what an anonymous visitor can cost (ADR-0004). Each turn first passes request-rate limits,
87
102
  * then reserves an estimate (expected input + `maxOutputTokens`) against the bot, per-IP and
88
103
  * global daily budgets. The reservation is atomic, so concurrent turns can't overshoot, and it
@@ -255,12 +270,12 @@ function createLimits(options) {
255
270
  reserved += perCall;
256
271
  return true;
257
272
  },
258
- async settle(usage, conversationId) {
259
- const actual = usage.inputTokens + usage.outputTokens;
273
+ async settle(usage, conversationId, historyTokens = usage.inputTokens) {
274
+ const actual = budgetTokens(usage);
260
275
  await Promise.all(list.map((budget) => store.hit(budget.key, 2 * DAY, actual - reserved)));
261
276
  const inputKey = `ask:ci:${conversationId}`;
262
277
  const previous = (await store.hit(inputKey, CONVERSATION_TTL, 0)).count;
263
- await store.hit(inputKey, CONVERSATION_TTL, usage.inputTokens - previous);
278
+ await store.hit(inputKey, CONVERSATION_TTL, historyTokens - previous);
264
279
  if (!keys.conversationId) await store.hit(`ask:c:${conversationId}`, CONVERSATION_TTL, 1);
265
280
  }
266
281
  };
@@ -745,6 +760,52 @@ function citationSource(annotation, sources) {
745
760
  };
746
761
  }
747
762
  }
763
+ /** A citation marker repeated right after itself, with only spaces or tabs between. */
764
+ const REPEATED_MARKER = /\[(\d{1,3})\](?:[ \t]*\[\1\])+/g;
765
+ /** A marker at the end of the text, then what could still become its repeat. */
766
+ const OPEN_REPEAT = /(\[\d{1,3}\])([ \t]*(?:\[\d{0,3})?)$/;
767
+ /** The start of a marker cut off at the end of the text. */
768
+ const OPEN_MARKER = /\[\d{0,3}$/;
769
+ /**
770
+ * Merges adjacent identical citation markers: `[1] [1]` and `[1][1]` become `[1]`. Only numbers
771
+ * that `isCitation` accepts are merged, so text such as `grid[1][1]` in an answer without that
772
+ * citation stays as written.
773
+ */
774
+ function mergeRepeatedMarkers(text, isCitation) {
775
+ return text.replace(REPEATED_MARKER, (repeat, index) => isCitation(Number(index)) ? `[${index}]` : repeat);
776
+ }
777
+ /**
778
+ * `mergeRepeatedMarkers` for streamed text. Holds back what follows a marker (spaces, a partial
779
+ * `[`) until the next delta shows whether it repeats the marker, so a repeat split across deltas
780
+ * is still merged. At most a few characters wait; `flush` releases them at the end of the step.
781
+ */
782
+ var MarkerMerger = class {
783
+ #isCitation;
784
+ /** The marker the text sent so far ends with, if it ends with one. */
785
+ #marker = "";
786
+ #held = "";
787
+ constructor(isCitation) {
788
+ this.#isCitation = isCitation;
789
+ }
790
+ /** Takes the next delta and returns the text that can be sent now (possibly empty). */
791
+ push(delta) {
792
+ const sent = this.#marker.length;
793
+ const text = mergeRepeatedMarkers(this.#marker + this.#held + delta, this.#isCitation);
794
+ const repeat = OPEN_REPEAT.exec(text);
795
+ const partial = repeat ? void 0 : OPEN_MARKER.exec(text);
796
+ const end = repeat ? text.length - (repeat[2] ?? "").length : partial?.index ?? text.length;
797
+ this.#marker = repeat?.[1] ?? "";
798
+ this.#held = text.slice(end);
799
+ return text.slice(sent, end);
800
+ }
801
+ /** Returns the held text, for the end of the stream. */
802
+ flush() {
803
+ const held = this.#held;
804
+ this.#marker = "";
805
+ this.#held = "";
806
+ return held;
807
+ }
808
+ };
748
809
  // src/openai/page-context.ts
749
810
  /** Starts the part of a visitor's turn that carries the page's description; history hides it. */
750
811
  const PAGE_CONTEXT_MARKER = "[askdare:page-context]";
@@ -1015,11 +1076,12 @@ function toHistoryMessage(item, sources = /* @__PURE__ */ new Map()) {
1015
1076
  case "input_file": attachments += 1;
1016
1077
  }
1017
1078
  if (text === "" && attachments === 0) return void 0;
1079
+ const citations = citationsOf(annotations, sources);
1018
1080
  return {
1019
1081
  id: item.id,
1020
1082
  role: item.role,
1021
- text,
1022
- citations: citationsOf(annotations, sources),
1083
+ text: mergeRepeatedMarkers(text, (index) => index >= 1 && index <= citations.length),
1084
+ citations,
1023
1085
  attachments
1024
1086
  };
1025
1087
  }
@@ -1207,6 +1269,10 @@ var CitationRegistry = class {
1207
1269
  isNew: true
1208
1270
  };
1209
1271
  }
1272
+ /** Whether `[index]` is the marker of a source registered in this turn. */
1273
+ has(index) {
1274
+ return Number.isInteger(index) && index >= 1 && index <= this.#indices.size;
1275
+ }
1210
1276
  };
1211
1277
  /**
1212
1278
  * Translates one Responses API stream into protocol events. Only text, refusals, citations and
@@ -1218,6 +1284,7 @@ var ResponseStreamMapper = class {
1218
1284
  #emit;
1219
1285
  #citations;
1220
1286
  #functionCalls = [];
1287
+ #markers;
1221
1288
  #answerItemId;
1222
1289
  #textItemId;
1223
1290
  #outcome;
@@ -1225,16 +1292,13 @@ var ResponseStreamMapper = class {
1225
1292
  this.#messageId = messageId;
1226
1293
  this.#emit = emit;
1227
1294
  this.#citations = citations;
1295
+ this.#markers = new MarkerMerger((index) => citations.has(index));
1228
1296
  }
1229
1297
  handle(event) {
1230
1298
  switch (event.type) {
1231
1299
  case "response.output_text.delta":
1232
1300
  case "response.refusal.delta":
1233
- if (event.delta !== "") this.#emit({
1234
- type: "text.delta",
1235
- messageId: this.#messageId,
1236
- delta: event.delta
1237
- });
1301
+ this.#emitText(this.#markers.push(event.delta));
1238
1302
  return;
1239
1303
  case "response.output_text.annotation.added":
1240
1304
  this.#handleAnnotation(event.annotation);
@@ -1274,23 +1338,26 @@ var ResponseStreamMapper = class {
1274
1338
  });
1275
1339
  return;
1276
1340
  case "response.completed":
1277
- case "response.incomplete":
1341
+ case "response.incomplete": {
1342
+ this.#emitText(this.#markers.flush());
1343
+ const usage = event.response.usage;
1278
1344
  this.#outcome = {
1279
1345
  status: event.type === "response.completed" ? "completed" : "incomplete",
1280
1346
  incompleteReason: event.response.incomplete_details?.reason,
1281
1347
  model: event.response.model || void 0,
1282
1348
  answerItemId: this.#answerItemId,
1283
1349
  textItemId: this.#textItemId,
1284
- usage: event.response.usage ? {
1285
- inputTokens: event.response.usage.input_tokens,
1286
- cachedInputTokens: event.response.usage.input_tokens_details.cached_tokens,
1287
- cacheWriteTokens: event.response.usage.input_tokens_details.cache_write_tokens ?? 0,
1288
- outputTokens: event.response.usage.output_tokens,
1289
- reasoningTokens: event.response.usage.output_tokens_details?.reasoning_tokens ?? 0
1350
+ usage: usage ? {
1351
+ inputTokens: usage.input_tokens,
1352
+ cachedInputTokens: usage.input_tokens_details?.cached_tokens ?? 0,
1353
+ cacheWriteTokens: usage.input_tokens_details?.cache_write_tokens ?? 0,
1354
+ outputTokens: usage.output_tokens,
1355
+ reasoningTokens: usage.output_tokens_details?.reasoning_tokens ?? 0
1290
1356
  } : ZERO_USAGE,
1291
1357
  functionCalls: this.#functionCalls
1292
1358
  };
1293
1359
  return;
1360
+ }
1294
1361
  case "response.failed": throw new AskdareError("upstream_error", { cause: event.response.error });
1295
1362
  case "error": throw new AskdareError("upstream_error", { cause: {
1296
1363
  code: event.code,
@@ -1304,6 +1371,13 @@ var ResponseStreamMapper = class {
1304
1371
  if (!this.#outcome) throw new AskdareError("upstream_error", { cause: "Stream ended without a terminal event." });
1305
1372
  return this.#outcome;
1306
1373
  }
1374
+ #emitText(delta) {
1375
+ if (delta !== "") this.#emit({
1376
+ type: "text.delta",
1377
+ messageId: this.#messageId,
1378
+ delta
1379
+ });
1380
+ }
1307
1381
  #handleAnnotation(annotation) {
1308
1382
  const source = citationSource(annotation, this.#citations.sources);
1309
1383
  if (!source) return;
@@ -2698,6 +2772,7 @@ function streamTurn(options) {
2698
2772
  let steps = 0;
2699
2773
  let model;
2700
2774
  let usage = ZERO_USAGE;
2775
+ let lastInput;
2701
2776
  const tools = [];
2702
2777
  let finishReason;
2703
2778
  let outcome = "completed";
@@ -2759,11 +2834,12 @@ function streamTurn(options) {
2759
2834
  steps += 1;
2760
2835
  model = step.model ?? model;
2761
2836
  usage = addUsage(usage, step.usage);
2837
+ lastInput = step.usage.inputTokens;
2762
2838
  },
2763
2839
  onToolCall: (call) => tools.push(call)
2764
2840
  });
2765
2841
  finishReason = result.reason;
2766
- options.settle?.(result.usage, conversationId);
2842
+ options.settle?.(result.usage, conversationId, lastInput ?? result.usage.inputTokens);
2767
2843
  const proposed = result.replies && normalizeReplies(result.replies);
2768
2844
  const released = holding ? await releaseAnswer(conversationId, proposed ?? []) : "allowed";
2769
2845
  const replies = released === "allowed" ? proposed : void 0;
@@ -3385,8 +3461,8 @@ function createRequestHandler(config) {
3385
3461
  conversationId: id,
3386
3462
  identityKey: key
3387
3463
  })).token,
3388
- settle: (usage, id) => {
3389
- reservation.settle(usage, id).catch((error) => report(toAskdareError(error)));
3464
+ settle: (usage, id, history) => {
3465
+ reservation.settle(usage, id, history).catch((error) => report(toAskdareError(error)));
3390
3466
  },
3391
3467
  report: config.onUsage,
3392
3468
  issueFeedback: feedbackOn(bot) ? (id, itemId) => feedbackHandle(tokens, bot, {
@@ -1,4 +1,4 @@
1
- /* Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change. */
1
+ /* Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change. */
2
2
  /*
3
3
  * Default skin of the chat (ADR-0008, ADR-0011), in the iframe and inside a page. Everything is
4
4
  * built on the public styling API: the --ask-* tokens (set per bot by the theme stylesheet), the
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import type { ReactElement } from 'react';
3
3
  import { useSkin } from './context';
4
4
  import { SparkIcon } from './icons';
package/dist/ui/chat.tsx CHANGED
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  'use client';
3
3
 
4
4
  // The entry of an ejected copy (`npx @boldare/askdare add ui`): the same DefaultChat as in
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import { useChat } from '@boldare/askdare/react';
3
3
  import { type KeyboardEvent, type ReactElement, useEffect, useId, useRef } from 'react';
4
4
  import { RestartIcon } from './icons';
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import type { ChatBot, Translate } from '@boldare/askdare/react';
3
3
  import { type Context, createContext, type RefObject, useContext } from 'react';
4
4
 
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import { FeedbackButton, useChat, useChatState, useMessage } from '@boldare/askdare/react';
3
3
  import { type FormEvent, type ReactElement, useEffect, useId, useRef, useState } from 'react';
4
4
  import { useSkin } from './context';
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import {
3
3
  AttachButton,
4
4
  Composer,
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import { useChat } from '@boldare/askdare/react';
3
3
  import type { ReactElement } from 'react';
4
4
  import { Avatar } from './avatar';
package/dist/ui/icons.tsx CHANGED
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import type { ReactElement, ReactNode } from 'react';
3
3
 
4
4
  /** Line icons on a 24px grid, drawn with the current text color. */
package/dist/ui/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  'use client';
3
3
 
4
4
  // The default look of the chat (ADR-0011): what `npx @boldare/askdare add ui` copies into an app.
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import {
3
3
  Citations,
4
4
  Message,
package/dist/ui/panel.tsx CHANGED
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import {
3
3
  ErrorMessage,
4
4
  HumanCheck,
@@ -1,4 +1,4 @@
1
- // Ejected from @boldare/askdare@0.5.1 with `npx @boldare/askdare add ui`. This copy is yours to change.
1
+ // Ejected from @boldare/askdare@0.5.3 with `npx @boldare/askdare add ui`. This copy is yours to change.
2
2
  import { useChat } from '@boldare/askdare/react';
3
3
  import type { ReactElement, ReactNode } from 'react';
4
4
  import { Avatar } from './avatar';
@@ -219,8 +219,8 @@ Limits bound what visitors can cost ([ADR-0004](https://github.com/boldare/askda
219
219
  | `messagesPerIpPerMinute` | `30` | Messages per client IP per minute, across visitors | 1–10,000 |
220
220
  | `sessionsPerIpPerHour` | `30` | New sessions per client IP per hour. Renewals by returning visitors count separately. | 1–10,000 |
221
221
  | `conversationsPerIpPerHour` | `20` | New conversations per client IP per hour | 1–10,000 |
222
- | `dailyTokens` | `2_000_000` | Input plus output tokens per UTC day, across all visitors | 1,000 or more |
223
- | `dailyTokensPerIp` | `200_000` | Input plus output tokens per client IP per UTC day | 100 or more |
222
+ | `dailyTokens` | `2_000_000` | Input plus output tokens per UTC day, across all visitors. Input read from the prompt cache counts as a tenth of a token. | 1,000 or more |
223
+ | `dailyTokensPerIp` | `200_000` | Input plus output tokens per client IP per UTC day, counted like `dailyTokens` | 100 or more |
224
224
  | `uploadsPerVisitorPerHour` | `20` | File uploads per visitor per hour | 1–1,000 |
225
225
  | `uploadsPerIpPerHour` | `60` | File uploads per client IP per hour, across visitors | 1–10,000 |
226
226
  | `uploadsPerDay` | `500` | File uploads per UTC day, across all visitors | 1–1,000,000 |
@@ -231,7 +231,7 @@ Limits bound what visitors can cost ([ADR-0004](https://github.com/boldare/askda
231
231
  What happens at a limit:
232
232
 
233
233
  - **Rates** answer `rate_limited`, with a `Retry-After` header. So does `maxTurns`, which asks the visitor to start a new conversation.
234
- - **Token budgets** answer `budget_exceeded` until midnight UTC. Before each model call, askdare reserves an estimate against `dailyTokens`, `dailyTokensPerIp` and the handler's `globalDailyTokens`. The estimate covers the conversation so far, the new message, `maxOutputTokens`, attached files and file search results. A bot with tools reserves the next call before each tool round, and answers without tools when a budget can't hold it. When the turn ends, the real usage replaces the estimate. A turn that fails or is cut off keeps the estimate charged.
234
+ - **Token budgets** answer `budget_exceeded` until midnight UTC. Before each model call, askdare reserves an estimate against `dailyTokens`, `dailyTokensPerIp` and the handler's `globalDailyTokens`. The estimate covers the conversation so far, the new message, `maxOutputTokens`, attached files and file search results. A bot with tools reserves the next call before each tool round, and answers without tools when a budget can't hold it. When the turn ends, the real usage replaces the estimate: input read from the prompt cache counts as a tenth of a token, close to its price, and everything else, cache writes included, as a whole token. The estimate counts the conversation so far as whole tokens, in case the cache has gone cold. A turn that fails or is cut off keeps the estimate charged.
235
235
  - **Speech budgets** reserve `voice.maxSeconds` per dictation, then charge the duration OpenAI reports. When one is spent, dictation answers `budget_exceeded` until midnight UTC.
236
236
  - **`maxInputChars`** rejects a longer message with `invalid_input`.
237
237
 
@@ -298,7 +298,7 @@ A wrong `basePath`, a duplicate bot ID or an empty `bots` list throws a `TypeErr
298
298
  | --- | --- | --- | --- |
299
299
  | `store` | `RateLimitStore` | in memory, per process | Counter storage for rate limits and budgets. With more than one instance, use a shared store such as `@boldare/askdare-upstash`. See [Custom rate-limit store](custom-store.md). |
300
300
  | `trustProxy` | `'auto' \| 'vercel' \| 'heroku' \| number` | `'auto'` | How to read the client IP behind your proxy. |
301
- | `globalDailyTokens` | `number` | unlimited | Input plus output tokens per UTC day, across all bots of this handler. Reaching it answers `budget_exceeded`. |
301
+ | `globalDailyTokens` | `number` | unlimited | Input plus output tokens per UTC day, across all bots of this handler, counted like `dailyTokens`. Reaching it answers `budget_exceeded`. |
302
302
  | `requireSharedStore` | `boolean` | `false` | `true` makes `createChatHandler` throw as the route loads unless `store` is shared (`shared: true`), instead of only warning in production. For example `process.env.NODE_ENV === 'production'`, so development keeps the in-memory store. Note that `next build` loads the route with `NODE_ENV=production`. |
303
303
 
304
304
  ### `trustProxy`
package/docs/costs.md CHANGED
@@ -21,8 +21,8 @@ These defaults bound spending. All of them can be changed in `limits` ([Configur
21
21
 
22
22
  | Limit | Default | Counted per |
23
23
  | --- | --- | --- |
24
- | `dailyTokens` | 2,000,000 input plus output tokens | bot, per UTC day |
25
- | `dailyTokensPerIp` | 200,000 input plus output tokens | client IP and bot, per UTC day |
24
+ | `dailyTokens` | 2,000,000 input plus output tokens (cached input counts as a tenth) | bot, per UTC day |
25
+ | `dailyTokensPerIp` | 200,000 input plus output tokens (cached input counts as a tenth) | client IP and bot, per UTC day |
26
26
  | `globalDailyTokens` (in `createChatHandler`) | none | all bots, per UTC day |
27
27
  | `maxOutputTokens` | 1,024 | model call |
28
28
  | `maxSteps` | 5 model calls | message |
@@ -46,15 +46,18 @@ one bot, 30 days 30 × 2,000,000 = 60,000,000 tokens
46
46
  three bots, one day 3 × 2,000,000 = 6,000,000 tokens (unless you set globalDailyTokens)
47
47
  ```
48
48
 
49
- The budget counts input, cached input and output tokens alike, but OpenAI prices them differently. For a ceiling in money, use the highest per-token price of your model:
49
+ The budget counts input read from the prompt cache as a tenth of a token, and input, cache writes and output as whole tokens. OpenAI prices cached input at a tenth of input on most models, so one budget token never costs more than the most expensive of them. For a ceiling in money, use the highest per-token price of your model:
50
50
 
51
51
  ```text
52
- ceiling per bot per day = 2,000,000 / 1,000,000 × highest price per 1M tokens
53
- = 2 × highest price per 1M tokens
52
+ highest price per 1M tokens = the highest of: input, cache writes, output, 10 × cached input
53
+ ceiling per bot per day = 2,000,000 / 1,000,000 × highest price per 1M tokens
54
+ = 2 × highest price per 1M tokens
54
55
  ceiling per bot per 30 days = 60 × highest price per 1M tokens
55
56
  ```
56
57
 
57
- Real spending is lower whenever some of the tokens are cheaper input or cached input. The ceiling is what an attacker with ten or more IP addresses can make you pay every day.
58
+ On current models the highest is usually output, and 10 × cached input equals input. Real spending is lower whenever some of the tokens are cheaper input or cached input. The ceiling is what an attacker with ten or more IP addresses can make you pay every day.
59
+
60
+ Long conversations are mostly cached input: every model call reads the whole conversation again, and the cache serves all of it but the newest part. We measured a 50-turn support conversation with knowledge searches at 97.9 % cached input. It used 3.8M input tokens, cost 0.31 USD, and counts as about 460,000 tokens against the budgets. One visitor can hold a conversation of about 28 turns like it on the default `dailyTokensPerIp`.
58
61
 
59
62
  ### Speech
60
63
 
@@ -85,7 +88,7 @@ The budgets are checked before each message. A few things let the real number en
85
88
  - **A message can use somewhat more than it reserved.** Before each model call, askdare reserves an estimate of that call against every budget:
86
89
 
87
90
  ```text
88
- one call = input tokens of the previous message in this conversation
91
+ one call = input tokens of the last model call of the previous message
89
92
  + characters of the instructions, message and page context / 2
90
93
  + maxOutputTokens
91
94
  + tokens of the attached files
@@ -167,7 +170,7 @@ OpenAI caches the beginning of prompts automatically on supported models, and ca
167
170
  - Start the instructions with text that is the same for every visitor. Put what varies, such as the locale or a signed-in user's name, at the end.
168
171
  - Keep the tool list stable. askdare already keeps it the same on every model call of a message.
169
172
 
170
- askdare's budgets count cached tokens in full, so they overestimate the cost when caching works. OpenAI's [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching) lists the minimum prompt length that can be cached.
173
+ askdare's budgets count input read from the prompt cache as a tenth of a token, close to its price, so they last longer when caching works ([Tokens](#tokens)). The estimate reserved before each model call still counts the conversation so far as whole tokens, in case the cache has gone cold. OpenAI's [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching) lists the minimum prompt length that can be cached.
171
174
 
172
175
  ## Reply options
173
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boldare/askdare",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Embeddable AI chatbot for Next.js, as a script-tag widget or React components, built on the official OpenAI SDK.",
5
5
  "license": "MIT",
6
6
  "author": {