ai-lcr 0.3.0 → 0.4.0

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
@@ -4,6 +4,23 @@ All notable changes to `ai-lcr` are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/), and the project adheres to
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.4.0] — 2026-06-02
8
+
9
+ All additions are optional and backward compatible.
10
+
11
+ ### Added
12
+
13
+ - **`CallRecord.ttftMs` — time to first token.** Streaming calls now report TTFT,
14
+ the industry-standard responsiveness metric: ms from the winning provider's
15
+ stream attempt start to its first content token (`text-delta` /
16
+ `reasoning-delta`). Measured against the *winner's* attempt, so failover
17
+ overhead (already in `latencyMs`) doesn't distort it. `undefined` for
18
+ `doGenerate` (no streaming → no "first token") and for calls that failed before
19
+ producing content. `formatCallRecord` shows it inline next to total latency when
20
+ present (`412ms (ttft 88ms)`). With `latencyMs` and `outputTokens` on the same
21
+ record, output throughput is derivable: `outputTokens / ((latencyMs − ttftMs) /
22
+ 1000)` tokens/sec.
23
+
7
24
  ## [0.3.0] — 2026-06-02
8
25
 
9
26
  Integration-feedback pass from wiring ai-lcr into a real agentic product
package/README.md CHANGED
@@ -184,6 +184,7 @@ interface CallRecord {
184
184
  ok: boolean;
185
185
  failedOver: boolean; // more than one provider was tried
186
186
  latencyMs: number;
187
+ ttftMs?: number; // streaming only: time to first token (winner's first content delta) — industry-standard responsiveness metric
187
188
  inputTokens: number;
188
189
  outputTokens: number;
189
190
  cachedInputTokens?: number; // prompt-cache hits the winner read (when reported)
@@ -196,6 +197,8 @@ interface CallRecord {
196
197
 
197
198
  **Savings, not just spend.** Whenever at least one provider in a chain carries a `cost`, `baselineUsd` is what the same call would have cost on the most expensive priced leg (typically your safety-net fallback). `baselineUsd − costUsd` is the money routing saved on that call — the number a cost dashboard exists to show.
198
199
 
200
+ **Responsiveness, not just total time.** On streaming calls (`streamText`, `streamObject`, streaming agents), `ttftMs` is the **time to first token** — measured from the winning provider's attempt start to its first content delta. It's the metric most LLM dashboards lead with, because it's what a user feels as "how fast did it start replying". Total `latencyMs` covers the whole stream including any failover; `ttftMs` isolates the serving model's responsiveness. It's `undefined` for `generateText`/`generateObject` (no streaming → no "first" token) and for calls that failed before any content. Output throughput (tokens/sec) is then `outputTokens / ((latencyMs − ttftMs) / 1000)`.
201
+
199
202
  **Cache-aware cost.** Add `cacheRead` (USD per 1M cached input tokens) to a provider's `cost` and ai-lcr bills prompt-cache hits at that rate when the call reports `usage.inputTokens.cacheRead`. Omit it and cached tokens fall back to the full `input` rate (unchanged from before). For cache-heavy traffic (e.g. Anthropic, where a cache read is ~0.1×) this keeps `costUsd` honest — and `cachedInputTokens` lets a dashboard audit it:
200
203
 
201
204
  ```ts
@@ -312,11 +315,11 @@ API_KEY=$KUNAVO_API_KEY BASE=https://api.kunavo.com \
312
315
  REF_API_KEY=$OPENROUTER_API_KEY REF_BASE=https://openrouter.ai/api \
313
316
  bash scripts/check-provider.sh
314
317
 
315
- # TokenMart uses vendor-prefixed model IDs
316
- API_KEY=$TOKENMART_API_KEY BASE=https://api.tokenmart.ai \
317
- MODEL_1=google/gemini-3-flash REF_1=google/gemini-3-flash-preview \
318
- MODEL_2=anthropic/claude-sonnet-4-6 REF_2=anthropic/claude-sonnet-4.6 \
319
- CACHE_MODEL=anthropic/claude-sonnet-4-6 \
318
+ # TokenMart (Inference AI) uses bare, un-prefixed model IDs
319
+ API_KEY=$INFERENCE_API_KEY BASE=https://model.service-inference.ai \
320
+ MODEL_1=gemini-3-flash-preview REF_1=google/gemini-3-flash-preview \
321
+ MODEL_2=claude-sonnet-4-6 REF_2=anthropic/claude-sonnet-4.6 \
322
+ CACHE_MODEL=claude-sonnet-4-6 \
320
323
  REF_API_KEY=$OPENROUTER_API_KEY REF_BASE=https://openrouter.ai/api \
321
324
  bash scripts/check-provider.sh
322
325
  ```
package/README.zh-CN.md CHANGED
@@ -232,11 +232,11 @@ API_KEY=$KUNAVO_API_KEY BASE=https://api.kunavo.com \
232
232
  REF_API_KEY=$OPENROUTER_API_KEY REF_BASE=https://openrouter.ai/api \
233
233
  bash scripts/check-provider.sh
234
234
 
235
- # TokenMart 使用 vendor 前缀的模型 ID
236
- API_KEY=$TOKENMART_API_KEY BASE=https://api.tokenmart.ai \
237
- MODEL_1=google/gemini-3-flash REF_1=google/gemini-3-flash-preview \
238
- MODEL_2=anthropic/claude-sonnet-4-6 REF_2=anthropic/claude-sonnet-4.6 \
239
- CACHE_MODEL=anthropic/claude-sonnet-4-6 \
235
+ # TokenMart(Inference AI)使用不带 vendor 前缀的裸模型 ID
236
+ API_KEY=$INFERENCE_API_KEY BASE=https://model.service-inference.ai \
237
+ MODEL_1=gemini-3-flash-preview REF_1=google/gemini-3-flash-preview \
238
+ MODEL_2=claude-sonnet-4-6 REF_2=anthropic/claude-sonnet-4.6 \
239
+ CACHE_MODEL=claude-sonnet-4-6 \
240
240
  REF_API_KEY=$OPENROUTER_API_KEY REF_BASE=https://openrouter.ai/api \
241
241
  bash scripts/check-provider.sh
242
242
  ```
package/dist/index.cjs CHANGED
@@ -312,7 +312,7 @@ var LcrFallbackModel = class {
312
312
  return max;
313
313
  }
314
314
  /** Winner settled: record the attempt, fire `onCost` (compat) + `onCall`. */
315
- finalizeOk(ctx, provider, attemptStart, usage) {
315
+ finalizeOk(ctx, provider, attemptStart, usage, ttftMs) {
316
316
  ctx.attempts.push({ provider: provider.label, ok: true, latencyMs: Date.now() - attemptStart });
317
317
  const inputTokens = usage?.inputTokens?.total ?? 0;
318
318
  const outputTokens = usage?.outputTokens?.total ?? 0;
@@ -334,6 +334,7 @@ var LcrFallbackModel = class {
334
334
  ok: true,
335
335
  failedOver: ctx.attempts.length > 1,
336
336
  latencyMs: Date.now() - ctx.startedAt,
337
+ ...ttftMs !== void 0 ? { ttftMs } : {},
337
338
  inputTokens,
338
339
  outputTokens,
339
340
  ...cacheReadTokens > 0 ? { cachedInputTokens: cacheReadTokens } : {},
@@ -433,6 +434,7 @@ var LcrFallbackModel = class {
433
434
  const triedBeforeServing = tried;
434
435
  let usage;
435
436
  let streamedAny = false;
437
+ let ttftMs;
436
438
  const stream = new ReadableStream({
437
439
  async start(controller) {
438
440
  let reader = null;
@@ -446,11 +448,14 @@ var LcrFallbackModel = class {
446
448
  }
447
449
  if (done) break;
448
450
  if (value.type === "finish") usage = value.usage;
451
+ if (ttftMs === void 0 && (value.type === "text-delta" || value.type === "reasoning-delta")) {
452
+ ttftMs = Date.now() - servingAttemptStart;
453
+ }
449
454
  controller.enqueue(value);
450
455
  if (value.type !== "stream-start") streamedAny = true;
451
456
  }
452
457
  self.settleSticky(servingIdx);
453
- self.finalizeOk(ctx, servingProvider, servingAttemptStart, usage);
458
+ self.finalizeOk(ctx, servingProvider, servingAttemptStart, usage, ttftMs);
454
459
  controller.close();
455
460
  } catch (error) {
456
461
  self.emitError(error, servingProvider.label);
@@ -512,7 +517,8 @@ function formatCallRecord(record, opts = {}) {
512
517
  const glyph = !record.ok ? "\u2717" : record.failedOver ? "\u26A0" : "\u2713";
513
518
  const chain = record.attempts.map((a) => a.provider).join("\u2192") || record.winner || "\u2014";
514
519
  const status = formatCost(record);
515
- let line = `${glyph} ${record.model} ${chain} ${record.latencyMs}ms ${status}`;
520
+ const timing = record.ttftMs !== void 0 ? `${record.latencyMs}ms (ttft ${record.ttftMs}ms)` : `${record.latencyMs}ms`;
521
+ let line = `${glyph} ${record.model} ${chain} ${timing} ${status}`;
516
522
  if (record.ok && record.baselineUsd !== void 0 && record.baselineUsd > record.costUsd) {
517
523
  line += ` (saved $${(record.baselineUsd - record.costUsd).toFixed(4)})`;
518
524
  }
package/dist/index.d.cts CHANGED
@@ -85,6 +85,18 @@ interface CallRecord {
85
85
  failedOver: boolean;
86
86
  /** Total wall time across all attempts, ms. */
87
87
  latencyMs: number;
88
+ /**
89
+ * Time to first token (TTFT), ms — the industry-standard responsiveness
90
+ * metric. Measured from the *winning* provider's stream attempt start to its
91
+ * first content token (`text-delta` / `reasoning-delta`), so it captures how
92
+ * fast the model that actually served started replying, not failover overhead
93
+ * (that's already in `latencyMs`). Streaming only: **undefined** for
94
+ * `doGenerate` (the whole response lands at once, so there's no "first token")
95
+ * and for calls that failed before producing any content. With `latencyMs` and
96
+ * `outputTokens`, output throughput is derivable: `outputTokens / ((latencyMs −
97
+ * ttftMs) / 1000)` tokens/sec.
98
+ */
99
+ ttftMs?: number;
88
100
  inputTokens: number;
89
101
  outputTokens: number;
90
102
  /**
@@ -141,6 +153,7 @@ declare function classifyErrorKind(error: unknown): ErrorKind;
141
153
  * latency, cost, and — when anything failed — the reason for each failed hop.
142
154
  *
143
155
  * ✓ text tokenmart 412ms $0.0003
156
+ * ✓ text tokenmart 412ms (ttft 88ms) $0.0003 ← streaming: TTFT shown when known
144
157
  * ⚠ text tokenmart→openrouter 910ms $0.0004 ⤷ tokenmart 502
145
158
  * ✗ text deepseek→tokenmart→openrouter 1240ms FAILED ⤷ deepseek 401, tokenmart 502, openrouter 429
146
159
  *
package/dist/index.d.ts CHANGED
@@ -85,6 +85,18 @@ interface CallRecord {
85
85
  failedOver: boolean;
86
86
  /** Total wall time across all attempts, ms. */
87
87
  latencyMs: number;
88
+ /**
89
+ * Time to first token (TTFT), ms — the industry-standard responsiveness
90
+ * metric. Measured from the *winning* provider's stream attempt start to its
91
+ * first content token (`text-delta` / `reasoning-delta`), so it captures how
92
+ * fast the model that actually served started replying, not failover overhead
93
+ * (that's already in `latencyMs`). Streaming only: **undefined** for
94
+ * `doGenerate` (the whole response lands at once, so there's no "first token")
95
+ * and for calls that failed before producing any content. With `latencyMs` and
96
+ * `outputTokens`, output throughput is derivable: `outputTokens / ((latencyMs −
97
+ * ttftMs) / 1000)` tokens/sec.
98
+ */
99
+ ttftMs?: number;
88
100
  inputTokens: number;
89
101
  outputTokens: number;
90
102
  /**
@@ -141,6 +153,7 @@ declare function classifyErrorKind(error: unknown): ErrorKind;
141
153
  * latency, cost, and — when anything failed — the reason for each failed hop.
142
154
  *
143
155
  * ✓ text tokenmart 412ms $0.0003
156
+ * ✓ text tokenmart 412ms (ttft 88ms) $0.0003 ← streaming: TTFT shown when known
144
157
  * ⚠ text tokenmart→openrouter 910ms $0.0004 ⤷ tokenmart 502
145
158
  * ✗ text deepseek→tokenmart→openrouter 1240ms FAILED ⤷ deepseek 401, tokenmart 502, openrouter 429
146
159
  *
package/dist/index.js CHANGED
@@ -271,7 +271,7 @@ var LcrFallbackModel = class {
271
271
  return max;
272
272
  }
273
273
  /** Winner settled: record the attempt, fire `onCost` (compat) + `onCall`. */
274
- finalizeOk(ctx, provider, attemptStart, usage) {
274
+ finalizeOk(ctx, provider, attemptStart, usage, ttftMs) {
275
275
  ctx.attempts.push({ provider: provider.label, ok: true, latencyMs: Date.now() - attemptStart });
276
276
  const inputTokens = usage?.inputTokens?.total ?? 0;
277
277
  const outputTokens = usage?.outputTokens?.total ?? 0;
@@ -293,6 +293,7 @@ var LcrFallbackModel = class {
293
293
  ok: true,
294
294
  failedOver: ctx.attempts.length > 1,
295
295
  latencyMs: Date.now() - ctx.startedAt,
296
+ ...ttftMs !== void 0 ? { ttftMs } : {},
296
297
  inputTokens,
297
298
  outputTokens,
298
299
  ...cacheReadTokens > 0 ? { cachedInputTokens: cacheReadTokens } : {},
@@ -392,6 +393,7 @@ var LcrFallbackModel = class {
392
393
  const triedBeforeServing = tried;
393
394
  let usage;
394
395
  let streamedAny = false;
396
+ let ttftMs;
395
397
  const stream = new ReadableStream({
396
398
  async start(controller) {
397
399
  let reader = null;
@@ -405,11 +407,14 @@ var LcrFallbackModel = class {
405
407
  }
406
408
  if (done) break;
407
409
  if (value.type === "finish") usage = value.usage;
410
+ if (ttftMs === void 0 && (value.type === "text-delta" || value.type === "reasoning-delta")) {
411
+ ttftMs = Date.now() - servingAttemptStart;
412
+ }
408
413
  controller.enqueue(value);
409
414
  if (value.type !== "stream-start") streamedAny = true;
410
415
  }
411
416
  self.settleSticky(servingIdx);
412
- self.finalizeOk(ctx, servingProvider, servingAttemptStart, usage);
417
+ self.finalizeOk(ctx, servingProvider, servingAttemptStart, usage, ttftMs);
413
418
  controller.close();
414
419
  } catch (error) {
415
420
  self.emitError(error, servingProvider.label);
@@ -471,7 +476,8 @@ function formatCallRecord(record, opts = {}) {
471
476
  const glyph = !record.ok ? "\u2717" : record.failedOver ? "\u26A0" : "\u2713";
472
477
  const chain = record.attempts.map((a) => a.provider).join("\u2192") || record.winner || "\u2014";
473
478
  const status = formatCost(record);
474
- let line = `${glyph} ${record.model} ${chain} ${record.latencyMs}ms ${status}`;
479
+ const timing = record.ttftMs !== void 0 ? `${record.latencyMs}ms (ttft ${record.ttftMs}ms)` : `${record.latencyMs}ms`;
480
+ let line = `${glyph} ${record.model} ${chain} ${timing} ${status}`;
475
481
  if (record.ok && record.baselineUsd !== void 0 && record.baselineUsd > record.costUsd) {
476
482
  line += ` (saved $${(record.baselineUsd - record.costUsd).toFixed(4)})`;
477
483
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-lcr",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Least Cost Routing for LLMs — route every model call to the cheapest available provider, fall back automatically, and track real cost. Built for the Vercel AI SDK.",
5
5
  "keywords": [
6
6
  "ai",