diff --git a/CHANGELOG.md b/CHANGELOG.md index d2bbaaf47..af2cfccf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # 印度占星 Skill 更新日志 +## 2026-11-27 · 只问西洋占星时少送印度盘时间数据;后台成本按缓存命中拆价 + +- 只问西洋占星时,问答不再把印度盘的运程、行运、年运等时间数据送给模型(这类回答本来就没有时间部分),每题输入少约 2.8–3 万个全价 token;印度和两边对照的问答不变 +- 后台聊天成本:命中缓存的输入按官网命中价算,没命中的按输入单价,输出另算;上线配置的聊天估算按实测命中份额,价格出处写在一处;Skill 版本不变(BUG-2432) + ## 2026-11-27 · 问答首轮少付一部分输入费 - 占星师每轮都送的路由全文、解读状态合同和工作顺序改放在问答系统提示末尾(文字不变),工具结果里不再重复,供应商缓存按低价计;每题约少 7,300 个全价输入 token diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 59fb4c539..6cadd0e05 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -33229,3 +33229,22 @@ - **防复发**:测试里涉及运行时钟(工具阶段 / 答题时钟)的先后,一律用 `manualDeadlines` 手动到点,不用 sleep 和真实毫秒差。 - **关联记录**:Gitea #344;BUG-1053(单步写回答、时钟交接);`consult-answer-clock-20261001`。 - **修复版本**:`claude/flaky-2423`(基于 origin/next 18d17250f,未推送)。 + +## BUG-2432 | 只问西洋占星时仍把印度盘的时间卡送给模型;后台聊天成本把命中缓存的输入也按全价算(BUG-2424 后续) + +- 状态:fixed-pending-verify(本地分支 `claude/cost-followup`,未推送;待 staging 核对后台成本)。 +- 首次发现 / 最近更新:2026-11-27(BUG-2424 实测时发现;负责人 2026-11-27 同意两项)。 +- 现象:(1)用户只问西洋占星(写回答的模型在 run-jyotish-consultation 上声明 `western_chart: "only"`)时,工具结果仍带印度盘的整张时间卡(`claim_cards` 里 `category: timing`:Vimshottari / Narayana / 其它运程、行运、Sade Sati、年运、快星行运、预先算好的运期 / 重叠 / 时间条段落表,约 5.7 万字符),回答写出来后程序又把时间部分删掉(`withoutTimeParts`),这部分输入白付。(2)后台「上线配置」的聊天成本估算和问答结算写进用量账的 `cost_microusd` 都按「全部输入 × 未命中单价」算,是上限;实测约一半输入命中缓存。 +- 触发条件:(1)每个只问西洋的首轮回答;(2)每次聊天结算、上线配置页显示估算。 +- 根因:(1)BUG-2342 第二轮只在回答一侧按 scope 删时间部分,模型输入侧没有按同一个声明裁卡。(2)模型记录只存输入、输出两个单价,结算公式没有读供应商返回的命中 token 数(账里 `metadata.cache.readTokens` 一直有记录);估算常量没有命中份额。 +- 修复: + - (1)`toModelEvidenceView` 加 `westernOnly` 选项,只在 `westernScope(input.western_chart) === "only"` 时为真(结构化声明,不看用户原话):模型看到的 `claim_cards` 去掉 timing 卡,`evidence_index.map.timing` 随之不生成。服务端卡(`ctx.state.evidenceCard`)不变,事实核对、补写、时间条仍读完整卡;回答侧 `shapeWesternOnly` 的删除保留作兜底。印度问题和 `both` 逐字节不变。命盘卡、领域卡、`western_natal`、methodology 都照旧。 + - (2)新增 `frontend/src/lib/model-token-prices.ts`:官网价格表(高峰时段,元 / 百万 token;flash 命中 0.04、未命中 2、输出 8;v4-pro 命中 0.30、未命中 9、输出 27;来源 https://api-docs.deepseek.com/zh-cn/quick_start/pricing ,2026-11-27 核对,非高峰半价)和 `tokenCostMicrousd`(命中按命中价、其余输入按输入单价、输出按输出单价)。已保存模型的命中价 = 它的输入单价 × 同名模型官网的命中 / 未命中比例(flash 1/50,pro 1/30);表里没有的模型名查不到命中价,仍全部按输入单价(上限)。`model-catalog` 给已发布模型和兜底模型带上 `cacheHitCostMicrousdPerMillion`;`consult/settlement.ts` 的 `costMicrousd` 用供应商返回的 `cache.readTokens`;上线配置的聊天估算加 `cachedInput: 79_600`(BUG-2424 同批实测,约 53%),报告类没有命中实测,仍按全价。`LAUNCH_KNOWN_MODEL_PRICES_CNY` 改为从价格表取(同一组数字),页面说明改为「命中缓存的输入按官网命中价另算」。 +- 验证: + - 实测(公开 AA 盘、deepseek-flash,两题只问西洋,四次运行均声明 `only`):工具结果 16.3 万 → 10.7 万字符(性格)、14.1 万 → 8.5 万字符(事业);写回答那一步未命中 6.98 万 → 4.20 万、6.50 万 → 3.67 万 token,命中不变(4.06 万);每题成本 0.173 → 0.120 元、0.172 → 0.131 元(约少 24–30%)。回答:两次都没有时间部分,「判断依据」全是西洋盘条目,事实核对无不符、禁句 0;结论与要点同向(性格:外表随和、内里主意定、憋情绪;事业:一对一专业顾问、写作讲课、审核调查,不适合带大团队和场面型销售),措辞差异在单次样本波动内。数据在 `eval-read-1116/cost-2432/`。 + - 按新价格,聊天估算(flash)约 0.383 元 → 0.227 元。 + - 新增 `frontend/tests/chat-cost-followup-2432.test.ts`(7 项:三个领域只问西洋时不带 timing 卡和索引、其余字段逐字节相同、服务端卡不变、少 2 万字符以上;印度与 both 逐字节不变且只读结构化声明;回答侧删除仍在;价格表与来源;拆价算式;估算按实测命中份额、未列模型仍是上限;结算读命中数、目录带命中价)。改动断言:`western-chat-2342.test.ts`(原值:`western_chart: true` 时除 `western_natal` 外逐字节相同;新值:`true` 等于 only,只少 timing 卡,另加 both 逐字节相同;原因:本条);`admin-clarity-20261116.test.ts`(原值 26,680;新值 19,140;原因:BUG-2424 改了用量常量没改这条测试,origin/next 上已是红的;该用例的模型没有名字,查不到命中价,结果等于全价)。 +- 防复发:模型输入按 scope 裁剪只认工具上的结构化声明;价格只在 `model-token-prices.ts` 一处,带官网地址和核对日期。 +- 已知限制:非高峰时段实价是高峰的一半,估算仍按高峰;报告、合盘、年运结算的 `cost_microusd` 仍按全价(不在本次范围);已保存的其它供应商模型没有命中价。 +- 关联记录:BUG-2424(缓存与成本实测)、BUG-2342(西洋问答形状)、BUG-2231 / BUG-1937 / BUG-1940(上线配置成本估算与官网价)。 +- 修复版本:`claude/cost-followup`(本地,未推送)。 diff --git a/frontend/src/components/admin/launch-setup.tsx b/frontend/src/components/admin/launch-setup.tsx index e7a31e761..82b2de795 100644 --- a/frontend/src/components/admin/launch-setup.tsx +++ b/frontend/src/components/admin/launch-setup.tsx @@ -519,7 +519,7 @@ export default function LaunchSetup() { - 单价按高峰时段、没有命中缓存的价格填,算出来的成本偏高,毛利是保守值。 + 单价按高峰时段、没有命中缓存的价格填;命中缓存的输入按官网命中价另算。 diff --git a/frontend/src/lib/admin/launch-setup.ts b/frontend/src/lib/admin/launch-setup.ts index d78631f1c..ea4543ddb 100644 --- a/frontend/src/lib/admin/launch-setup.ts +++ b/frontend/src/lib/admin/launch-setup.ts @@ -7,6 +7,8 @@ * admin APIs. */ +import { cacheHitCostMicrousdPerMillion, MODEL_LIST_PRICES_CNY, tokenCostMicrousd } from "../model-token-prices.ts"; + /** The features that are actually billed today, in the order the page shows them. */ export const LAUNCH_FEATURES = [ { key: "chat.standard", label: "聊天" }, @@ -209,23 +211,31 @@ export function launchMargin(saleCny: number | null, costCny: number | null): nu * BUG-2424 原值 { input: 176_000, output: 22_700 };新值:2026-11-27 本地六个首轮回答(事业、婚恋、财运、一年事业、 * 印度和西洋对比、只按 KP)缓存改动之后、缓存已热的平均,按供应商逐次返回的用量相加(含补漏和改写调用):输入约 * 151,000(其中约 79,600 命中缓存)、输出约 10,100;原因:BUG-2247 之后回答变短,每次调用的实测比旧样本小。 - * 这里仍按输入全价估,命中缓存的那部分实际约为全价的 1/50,所以是上限。 + * BUG-2432 原值:这里按输入全价估(上限);新值:`cachedInput` 是其中命中缓存的输入(聊天取 BUG-2424 同一批实测的 79,600,约 53%), + * 按官网命中价另算(model-token-prices.ts);报告类没有命中实测,`cachedInput` 不写,仍按全价;原因:负责人 2026-11-27 同意。 */ -export const LAUNCH_TYPICAL_TOKENS: Readonly> = { - "chat.standard": { input: 151_000, output: 10_100 }, +export const LAUNCH_TYPICAL_TOKENS: Readonly> = { + "chat.standard": { input: 151_000, output: 10_100, cachedInput: 79_600 }, "report.full": { input: 126_000, output: 33_000 }, "annual.full": { input: 108_000, output: 86_000 }, "synastry.full": { input: 360_000, output: 102_000 }, }; -/** Estimated cost of one run from the default model's unit prices. Null until both prices are filled. */ -export function launchEstimatedCostMicrousd( - model: Pick | null, - featureKey: LaunchFeatureKey, -): number | null { +type LaunchCostModel = Pick & { providerModel?: string }; + +/** + * Estimated cost of one run from the default model's unit prices. Null until both prices are filled. + * BUG-2432: cache-hit input at the model's official hit price (its input price × the listed hit / miss ratio), the rest + * at the input price; a model whose name is not listed keeps the full input price for all input. + */ +export function launchEstimatedCostMicrousd(model: LaunchCostModel | null, featureKey: LaunchFeatureKey): number | null { if (!model || !(model.inputCostMicrousdPerMillion > 0) || !(model.outputCostMicrousdPerMillion > 0)) return null; const tokens = LAUNCH_TYPICAL_TOKENS[featureKey]; - return (tokens.input * model.inputCostMicrousdPerMillion + tokens.output * model.outputCostMicrousdPerMillion) / 1_000_000; + const hit = cacheHitCostMicrousdPerMillion(model.providerModel, model.inputCostMicrousdPerMillion); + return tokenCostMicrousd( + { inputTokens: tokens.input, outputTokens: tokens.output, cachedInputTokens: tokens.cachedInput ?? 0 }, + { inputCostMicrousdPerMillion: model.inputCostMicrousdPerMillion, outputCostMicrousdPerMillion: model.outputCostMicrousdPerMillion, ...(hit === undefined ? {} : { cacheHitCostMicrousdPerMillion: hit }) }, + ); } /** @@ -236,7 +246,7 @@ export function launchEstimatedCostMicrousd( export function launchFeatureCost(input: Readonly<{ runs: number; p95Microusd: number | null; - model: Pick | null; + model: LaunchCostModel | null; featureKey: LaunchFeatureKey; }>): { microusd: number; source: "measured" | "estimate" } | null { if (input.runs > 0 && input.p95Microusd !== null && input.p95Microusd > 0) return { microusd: input.p95Microusd, source: "measured" }; @@ -247,13 +257,13 @@ export function launchFeatureCost(input: Readonly<{ /** * Official list prices in CNY per million tokens, used to pre-fill the unit * prices of a model that has never been saved here (BUG-1940). Peak hours, - * input without a cache hit: the most expensive tier, so cost is an upper bound. - * Source: the provider's price table the owner pasted on 2026-11-16. + * input without a cache hit: the price the admin stores as 「输入单价」. + * 原值:本文件内写死,来源「the provider's price table the owner pasted on 2026-11-16」;新值:取自 model-token-prices.ts + * (同一组数字,带官网地址和核对日期);原因:BUG-2432,价格常量只放一处。 */ -export const LAUNCH_KNOWN_MODEL_PRICES_CNY: Readonly> = { - "deepseek-flash": { inputCny: 2, outputCny: 8 }, - "deepseek-v4-pro": { inputCny: 9, outputCny: 27 }, -}; +export const LAUNCH_KNOWN_MODEL_PRICES_CNY: Readonly> = Object.fromEntries( + Object.entries(MODEL_LIST_PRICES_CNY).map(([name, price]) => [name, { inputCny: price.inputCny, outputCny: price.outputCny }]), +); export type LaunchPriceSuggestion = Readonly<{ inputCny: number; outputCny: number; source: "saved" | "preset" }>; diff --git a/frontend/src/lib/consult/settlement.ts b/frontend/src/lib/consult/settlement.ts index 689e6dc17..b74c38ea4 100644 --- a/frontend/src/lib/consult/settlement.ts +++ b/frontend/src/lib/consult/settlement.ts @@ -10,6 +10,7 @@ import { consultationUsageMetadata } from "@/lib/consultation-step-timing"; import type { SmalltalkUsage } from "@/lib/consultation-smalltalk"; import { resolveFeaturePricing } from "@/lib/feature-pricing"; import { servedModel } from "@/lib/model-serve-scope"; +import { tokenCostMicrousd } from "@/lib/model-token-prices"; type RpcClient = { rpc(name: string, args: Record): Promise<{ @@ -41,6 +42,7 @@ export type ConsultSettlementContext = { configVersion?: number; inputCostMicrousdPerMillion?: number; outputCostMicrousdPerMillion?: number; + cacheHitCostMicrousdPerMillion?: number; }; getClassification: () => { usage: SmalltalkUsage; @@ -283,10 +285,9 @@ export function createConsultSettlement(ctx: ConsultSettlementContext) { modelConfigVersion: served.configVersion, inputTokens, outputTokens, - costMicrousd: Math.round(( - inputTokens * (served.inputCostMicrousdPerMillion ?? 0) - + outputTokens * (served.outputCostMicrousdPerMillion ?? 0) - ) / 1_000_000), + // BUG-2432: 原值 inputTokens × 输入单价 + outputTokens × 输出单价(命中缓存的输入也按全价);新值:供应商返回的命中 + // token(cache.readTokens)按命中价,其余输入按输入单价;原因:负责人 2026-11-27 同意,后台成本不再是上限。 + costMicrousd: Math.round(tokenCostMicrousd({ inputTokens, outputTokens, cachedInputTokens: cache?.readTokens ?? 0 }, served)), durationMs: Date.now() - usageStartedAt, metadata: { ...(cache ? { cache: { ...cache, hit: cache.readTokens > 0 } } : {}), diff --git a/frontend/src/lib/model-catalog.ts b/frontend/src/lib/model-catalog.ts index 1f295bf07..6367841bd 100644 --- a/frontend/src/lib/model-catalog.ts +++ b/frontend/src/lib/model-catalog.ts @@ -7,6 +7,7 @@ import { queryAdminRows } from "@/lib/admin/database"; import { modelVersionCacheTtlMs } from "@/lib/consult/prep-flags"; import { assertAllowedModelProviderUrl } from "@/lib/epay/gateway-policy"; import { providerKeyPool, type PoolKey } from "@/lib/model-key-pool"; +import { cacheHitCostMicrousdPerMillion } from "@/lib/model-token-prices"; import { decryptModelProviderApiKey, type ModelProviderType } from "@/lib/model-provider-policy"; import { PooledProviderLanguageModel, type FallbackTarget, type PooledKey } from "@/lib/pooled-language-model"; @@ -113,9 +114,15 @@ async function resolveRow(row: PublishedModelRow): Promise(` select c.model_id,v.version,v.label,v.description,v.provider_model,v.credit_cost,v.is_default, @@ -143,6 +150,7 @@ async function resolveFallback(modelId: string): Promise configVersion: fallback.configVersion, inputCostMicrousdPerMillion: fallback.inputCostMicrousdPerMillion, outputCostMicrousdPerMillion: fallback.outputCostMicrousdPerMillion, + ...(fallback.cacheHitCostMicrousdPerMillion === undefined ? {} : { cacheHitCostMicrousdPerMillion: fallback.cacheHitCostMicrousdPerMillion }), }, }; } diff --git a/frontend/src/lib/model-serve-scope.ts b/frontend/src/lib/model-serve-scope.ts index 2deb87056..2ad445be8 100644 --- a/frontend/src/lib/model-serve-scope.ts +++ b/frontend/src/lib/model-serve-scope.ts @@ -15,6 +15,8 @@ export type ServedModel = Readonly<{ configVersion?: number; inputCostMicrousdPerMillion?: number; outputCostMicrousdPerMillion?: number; + /** BUG-2432: the cache-hit input price, from the official hit / miss ratio of the model name (model-token-prices.ts). */ + cacheHitCostMicrousdPerMillion?: number; }>; const scope = new AsyncLocalStorage>(); diff --git a/frontend/src/lib/model-token-prices.ts b/frontend/src/lib/model-token-prices.ts new file mode 100644 index 000000000..86e21621c --- /dev/null +++ b/frontend/src/lib/model-token-prices.ts @@ -0,0 +1,55 @@ +/** + * BUG-2432: the providers' official list prices, CNY per million tokens, in one place. + * + * Source: https://api-docs.deepseek.com/zh-cn/quick_start/pricing (English: https://api-docs.deepseek.com/quick_start/pricing), + * read 2026-11-27. Peak hours (北京时间工作日 9:00–12:00、14:00–18:00); every other hour is half price, so a cost from + * these is an upper bound for the time of day. `deepseek-flash` is DeepSeek-V4.1-Flash-1017; the legacy name + * `deepseek-v4-flash` is still accepted and billed at the flash price. + * + * model cache hit cache miss output + * deepseek-flash 0.04 2 8 + * deepseek-v4-pro 0.30 9 27 + * + * The admin stores only the input (cache-miss) and output prices of a model; the cache-hit price of a saved model is + * its input price times the official hit / miss ratio of the same model name (1/50 flash, 1/30 pro). A model not in + * this table has no known hit price, and its cached input is priced at the full input price (upper bound). + */ +export const MODEL_LIST_PRICES_CNY: Readonly> = { + "deepseek-flash": { cacheHitCny: 0.04, inputCny: 2, outputCny: 8 }, + "deepseek-v4-pro": { cacheHitCny: 0.3, inputCny: 9, outputCny: 27 }, +}; + +/** The official cache-hit / cache-miss input price ratio of a provider model name, or null when it is not listed. */ +export function cacheHitPriceRatio(providerModel: string | null | undefined): number | null { + const price = MODEL_LIST_PRICES_CNY[(providerModel ?? "").trim().toLowerCase()]; + return price && price.inputCny > 0 ? price.cacheHitCny / price.inputCny : null; +} + +/** The cache-hit input price (micro-USD per million) of a saved model, from its input price; undefined when unknown. */ +export function cacheHitCostMicrousdPerMillion(providerModel: string | null | undefined, inputCostMicrousdPerMillion: number | null | undefined): number | undefined { + const ratio = cacheHitPriceRatio(providerModel); + if (ratio === null || typeof inputCostMicrousdPerMillion !== "number" || !Number.isFinite(inputCostMicrousdPerMillion) || inputCostMicrousdPerMillion < 0) return undefined; + return Math.round(inputCostMicrousdPerMillion * ratio); +} + +export type TokenPrices = Readonly<{ + inputCostMicrousdPerMillion?: number; + outputCostMicrousdPerMillion?: number; + cacheHitCostMicrousdPerMillion?: number; +}>; + +/** + * Cost of one run in micro-USD: cache-hit input at the hit price, the rest of the input at the input (miss) price, + * output at the output price. `inputTokens` is the whole prompt (hit + miss), as the providers report it; without a + * hit price the cached part is priced as input. + */ +export function tokenCostMicrousd( + usage: Readonly<{ inputTokens: number; outputTokens: number; cachedInputTokens?: number | null }>, + prices: TokenPrices, +): number { + const input = Math.max(0, usage.inputTokens); + const cached = Math.min(input, Math.max(0, usage.cachedInputTokens ?? 0)); + const miss = prices.inputCostMicrousdPerMillion ?? 0; + const hit = prices.cacheHitCostMicrousdPerMillion ?? miss; + return ((input - cached) * miss + cached * hit + Math.max(0, usage.outputTokens) * (prices.outputCostMicrousdPerMillion ?? 0)) / 1_000_000; +} diff --git a/frontend/src/mastra/consultation-tools.ts b/frontend/src/mastra/consultation-tools.ts index 59d70d2a2..06bfd8c4a 100644 --- a/frontend/src/mastra/consultation-tools.ts +++ b/frontend/src/mastra/consultation-tools.ts @@ -1176,13 +1176,22 @@ function withEvidencePacks( return out; } +/** BUG-2432: the claim cards a Western-only answer reads: everything but the Indian timing card. */ +export function withoutIndianTimingCard(claimCards: readonly T[]): T[] { + return claimCards.filter((claim) => claim.category !== "timing"); +} + /** * What the answer-writing model reads (D1): the answer contract and the * evidence card. The full per-domain result stays in `full` on the server. */ -export function toModelEvidenceView(full: FullDomainPlanContext, card: EvidenceCard, askedQuestion?: string | null) { +export function toModelEvidenceView(full: FullDomainPlanContext, card: EvidenceCard, askedQuestion?: string | null, options: Readonly<{ westernOnly?: boolean }> = {}) { const consultations = "consultations" in full && Array.isArray(full.consultations) ? full.consultations : null; - const claimCards = evidenceCardClaimCards(card); + // BUG-2432: a Western-only turn (western_chart "only", the writer's own declaration) has no time section and no time + // label — the program removes them when written (withoutTimeParts) — so the Indian timing claim card, the source of + // those parts, is not sent; its evidence_index entries go with it. The server card (ctx.state.evidenceCard) is + // untouched, and Indian / both-sides turns are byte-identical. + const claimCards = options.westernOnly ? withoutIndianTimingCard(evidenceCardClaimCards(card)) : evidenceCardClaimCards(card); // BUG-1985: the pack's time scope comes from the question this turn asks (the split question, // BUG-1980), not from the engine's echo of it. const packQuestion = askedQuestion ?? (typeof full.question === "string" ? full.question : null); @@ -1905,7 +1914,7 @@ export function createConsultationTools(ctx: ConsultationAgentContext) { if (day.calendar) card.day_calendar = day.calendar; appendConsultationRuntimeStep(ctx.state, { kind: "tool", name: "day-calendar", status: day.calendar ? "completed" : "failed", durationMs: day.elapsedMs, ...(day.reason ? { failureCode: day.reason } : {}) }); } - const modelView: ConsultationModelEvidenceView & { western_natal?: unknown } = toModelEvidenceView(modelContext, card, userIntent); + const modelView: ConsultationModelEvidenceView & { western_natal?: unknown } = toModelEvidenceView(modelContext, card, userIntent, { westernOnly: scope === "only" }); ctx.state.evidenceCard = card; ctx.state.evidenceCardChars = JSON.stringify({ claim_cards: modelView.claim_cards, diff --git a/frontend/src/mastra/model.ts b/frontend/src/mastra/model.ts index ed516528f..889043ecf 100644 --- a/frontend/src/mastra/model.ts +++ b/frontend/src/mastra/model.ts @@ -16,6 +16,8 @@ export type ResolvedLanguageModel = PublicLanguageModel & { readonly configVersion?: number; readonly inputCostMicrousdPerMillion?: number; readonly outputCostMicrousdPerMillion?: number; + /** BUG-2432: the cache-hit input price (model-token-prices.ts); undefined when the model name has no listed hit price. */ + readonly cacheHitCostMicrousdPerMillion?: number; readonly contextWindow?: number | null; }; diff --git a/frontend/tests/admin-clarity-20261116.test.ts b/frontend/tests/admin-clarity-20261116.test.ts index b83476031..ed0622d4b 100644 --- a/frontend/tests/admin-clarity-20261116.test.ts +++ b/frontend/tests/admin-clarity-20261116.test.ts @@ -13,15 +13,18 @@ test("the launch page estimates a cost while a feature has no priced usage (BUG- // 原值: 100k in × $0.10/M + 13k out × $0.40/M = 10,000 + 5,200 = 15,200 microusd // 新值: 176k in × $0.10/M + 22.7k out × $0.40/M = 17,600 + 9,080 = 26,680 microusd // 原因: BUG-2231,聊天估算按 2026-11-23 新写法的实测用量 - assert.equal(launchEstimatedCostMicrousd(model, "chat.standard"), 26_680); + // 原值: 26,680(176k / 22.7k);新值: 151k × $0.10/M + 10.1k × $0.40/M = 15,100 + 4,040 = 19,140 microusd; + // 原因: BUG-2424 把用量改成 151k / 10.1k 时没跟着改这里(origin/next 38fb38d00 上这条就是红的);这个模型没有名字, + // 查不到官网命中价,命中的 79.6k 仍按全价(BUG-2432),所以和全价相同。 + assert.equal(launchEstimatedCostMicrousd(model, "chat.standard"), 19_140); assert.equal(launchEstimatedCostMicrousd(null, "chat.standard"), null); assert.equal(launchEstimatedCostMicrousd({ inputCostMicrousdPerMillion: 0, outputCostMicrousdPerMillion: 400_000 }, "chat.standard"), null); for (const feature of LAUNCH_FEATURES) assert.ok((launchEstimatedCostMicrousd(model, feature.key) ?? 0) > 0, feature.key); - assert.deepEqual(launchFeatureCost({ runs: 0, p95Microusd: null, model, featureKey: "chat.standard" }), { microusd: 26_680, source: "estimate" }); + assert.deepEqual(launchFeatureCost({ runs: 0, p95Microusd: null, model, featureKey: "chat.standard" }), { microusd: 19_140, source: "estimate" }); assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 9_000, model, featureKey: "chat.standard" }), { microusd: 9_000, source: "measured" }); // Runs settled before the unit prices were filled carry cost 0: not a measurement. - assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 0, model, featureKey: "chat.standard" }), { microusd: 26_680, source: "estimate" }); + assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 0, model, featureKey: "chat.standard" }), { microusd: 19_140, source: "estimate" }); assert.equal(launchFeatureCost({ runs: 0, p95Microusd: null, model: null, featureKey: "chat.standard" }), null); const page = source("src/components/admin/launch-setup.tsx"); diff --git a/frontend/tests/chat-cost-followup-2432.test.ts b/frontend/tests/chat-cost-followup-2432.test.ts new file mode 100644 index 000000000..143094d51 --- /dev/null +++ b/frontend/tests/chat-cost-followup-2432.test.ts @@ -0,0 +1,127 @@ +/** + * BUG-2432 (owner 2026-11-27, follow-ups to BUG-2424): + * (1) A Western-only turn (western_chart "only", the writer's own declaration) does not send the Indian timing claim card: + * the program removes the answer's time section and time labels anyway (withoutTimeParts). Indian and both-sides + * turns are byte-identical; the server card keeps its timing; the strip stays as the safety net. + * (2) The chat cost prices cache-hit input at the official hit price, cache-miss input and output at theirs. + */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +import { launchEstimatedCostMicrousd, LAUNCH_KNOWN_MODEL_PRICES_CNY, LAUNCH_TYPICAL_TOKENS, cnyPerMillionToMicrousd } from "../src/lib/admin/launch-setup.ts"; +import { cacheHitCostMicrousdPerMillion, cacheHitPriceRatio, MODEL_LIST_PRICES_CNY, tokenCostMicrousd } from "../src/lib/model-token-prices.ts"; +import { createConsultationRuntimeState, createConsultationTools, withoutIndianTimingCard } from "../src/mastra/consultation-tools.ts"; +import { publicServerChart } from "./consult-natal-agent-test-support.ts"; + +type Json = Record; +const obama = JSON.parse(readFileSync(new URL("./fixtures/western-obama-2340.json", import.meta.url), "utf8")) as Json; +const golden = JSON.parse(readFileSync(new URL("./fixtures/consult-evidence-card-golden.json", import.meta.url), "utf8")) as { + charts: Array<{ id: string; workflow: Json }>; +}; +const source = (path: string) => readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); + +async function run(domains: string[], western?: "only" | "both") { + const workflow = golden.charts.find((chart) => chart.id === "steve_jobs")!.workflow; + const state = createConsultationRuntimeState(); + const tools = createConsultationTools({ + userId: "u", sessionId: "s", requestId: "cost-2432", consultationMode: "verified_chart", + serverChart: publicServerChart as never, state, + runWorkflow: async () => structuredClone(workflow) as never, + westernFetch: (async () => new Response(JSON.stringify(obama), { status: 200 })) as unknown as typeof fetch, + requestTime: new Date("2026-09-27T04:00:00.000Z"), + }); + const writer = { writer: { custom: async () => {} } } as never; + const view = await tools["run-jyotish-consultation"].execute!({ question: "q", domains, ...(western ? { western_chart: western } : {}) } as never, writer) as Json; + return { view, state }; +} + +const cards = (view: Json) => view.claim_cards as Array<{ category: string }>; +const indexMap = (view: Json) => ((view.evidence_index as Json | undefined)?.map ?? {}) as Json; + +test("a Western-only turn leaves out the Indian timing card and its index entries; the rest is the Indian turn's bytes", async () => { + for (const domains of [["general"], ["career"], ["marriage"]]) { + const indian = await run(domains); + const only = await run(domains, "only"); + assert.ok(cards(indian.view).some((claim) => claim.category === "timing"), "the Indian turn carries the timing card"); + assert.deepEqual(cards(only.view).map((claim) => claim.category), cards(indian.view).map((claim) => claim.category).filter((category) => category !== "timing")); + assert.equal(JSON.stringify(cards(only.view)), JSON.stringify(withoutIndianTimingCard(cards(indian.view))), `${domains}: natal and domain cards unchanged`); + assert.ok("timing" in indexMap(indian.view)); + assert.equal("timing" in indexMap(only.view), false); + for (const key of Object.keys(indian.view)) { + if (key === "claim_cards" || key === "evidence_index") continue; + assert.equal(JSON.stringify(only.view[key]), JSON.stringify(indian.view[key]), `${domains}: ${key} unchanged`); + } + assert.ok(only.view.western_natal, "the Western facts are still sent"); + // The server card keeps the timing (fact guard, repair and strip read it). + assert.deepEqual(only.state.evidenceCard!.base.timing, indian.state.evidenceCard!.base.timing); + const saved = indian.state.modelVisibleChars! - only.state.modelVisibleChars! + JSON.stringify(only.view.western_natal).length; + assert.ok(saved > 20_000, `${domains}: ${saved} fewer characters`); + } +}); + +test("Indian and both-sides turns are byte-identical to before", async () => { + const indian = await run(["career"]); + const both = await run(["career"], "both"); + const { western_natal: _w, ...rest } = both.view; + assert.equal(JSON.stringify(rest), JSON.stringify(indian.view)); + const tools = source("src/mastra/consultation-tools.ts"); + // Decided from the structured flag only, never from the user's words. + assert.match(tools, /toModelEvidenceView\(modelContext, card, userIntent, \{ westernOnly: scope === "only" \}\)/u); + assert.match(tools, /const scope = westernScope\(input\.western_chart\);/u); +}); + +test("the answer-side strip stays as the safety net", () => { + const stream = source("src/lib/stream-agent-response.ts"); + assert.match(stream, /function shapeWesternOnly[\s\S]*?const time = withoutTimeParts\(fullOutput\);/u); +}); + +test("official prices: one table, with the source page and the date", () => { + const file = source("src/lib/model-token-prices.ts"); + assert.match(file, /https:\/\/api-docs\.deepseek\.com\/zh-cn\/quick_start\/pricing/u); + assert.match(file, /read 2026-11-27/u); + assert.deepEqual(MODEL_LIST_PRICES_CNY["deepseek-flash"], { cacheHitCny: 0.04, inputCny: 2, outputCny: 8 }); + assert.deepEqual(MODEL_LIST_PRICES_CNY["deepseek-v4-pro"], { cacheHitCny: 0.3, inputCny: 9, outputCny: 27 }); + assert.deepEqual(LAUNCH_KNOWN_MODEL_PRICES_CNY, { "deepseek-flash": { inputCny: 2, outputCny: 8 }, "deepseek-v4-pro": { inputCny: 9, outputCny: 27 } }); + assert.doesNotMatch(source("src/lib/admin/launch-setup.ts"), /inputCny: 2, outputCny: 8/u, "no second copy of the numbers"); + assert.equal(cacheHitPriceRatio("deepseek-flash"), 0.02); + assert.ok(Math.abs(cacheHitPriceRatio("DeepSeek-V4-Pro")! - 1 / 30) < 1e-12); + assert.equal(cacheHitPriceRatio("some-other-model"), null); + assert.equal(cacheHitCostMicrousdPerMillion("deepseek-flash", 277_778), 5_556); + assert.equal(cacheHitCostMicrousdPerMillion("unknown", 277_778), undefined); +}); + +test("cost split: hit input at the hit price, miss input and output at theirs; no hit price prices it all as input", () => { + const prices = { inputCostMicrousdPerMillion: 2_000_000, outputCostMicrousdPerMillion: 8_000_000, cacheHitCostMicrousdPerMillion: 40_000 }; + // 100k in (60k hit) + 10k out: 40k × 2 + 60k × 0.04 + 10k × 8 = 80,000 + 2,400 + 80,000. + assert.equal(tokenCostMicrousd({ inputTokens: 100_000, cachedInputTokens: 60_000, outputTokens: 10_000 }, prices), 162_400); + assert.equal(tokenCostMicrousd({ inputTokens: 100_000, cachedInputTokens: 0, outputTokens: 10_000 }, prices), 280_000); + assert.equal(tokenCostMicrousd({ inputTokens: 100_000, cachedInputTokens: 60_000, outputTokens: 10_000 }, { ...prices, cacheHitCostMicrousdPerMillion: undefined }), 280_000); + // More hits than prompt tokens never yields a negative miss part. + assert.equal(tokenCostMicrousd({ inputTokens: 1_000, cachedInputTokens: 5_000, outputTokens: 0 }, prices), 40); +}); + +test("the launch estimate splits chat input by the BUG-2424 measured hit share for a listed model", () => { + const usd = 7.2; + const flash = { providerModel: "deepseek-flash", inputCostMicrousdPerMillion: cnyPerMillionToMicrousd(2, usd), outputCostMicrousdPerMillion: cnyPerMillionToMicrousd(8, usd) }; + const chat = LAUNCH_TYPICAL_TOKENS["chat.standard"]; + assert.equal(chat.cachedInput, 79_600); + const estimate = launchEstimatedCostMicrousd(flash, "chat.standard")!; + const cny = (estimate / 1_000_000) * usd; + // (151,000 − 79,600) × 2 + 79,600 × 0.04 + 10,100 × 8 = 142,800 + 3,184 + 80,800 → 0.2268 CNY (was 0.3828 at full price). + assert.ok(Math.abs(cny - 0.226784) < 0.0005, `chat estimate ${cny}`); + const full = launchEstimatedCostMicrousd({ ...flash, providerModel: "unlisted" }, "chat.standard")!; + assert.ok(Math.abs((full / 1_000_000) * usd - 0.3828) < 0.0005, "an unlisted model keeps the full-price upper bound"); + // Reports have no measured hit share: unchanged. + assert.equal(launchEstimatedCostMicrousd(flash, "report.full"), launchEstimatedCostMicrousd({ ...flash, providerModel: "unlisted" }, "report.full")); +}); + +test("the recorded chat cost uses the provider's own cache-hit count; the catalog carries the hit price", () => { + const settlement = source("src/lib/consult/settlement.ts"); + assert.match(settlement, /costMicrousd: Math\.round\(tokenCostMicrousd\(\{ inputTokens, outputTokens, cachedInputTokens: cache\?\.readTokens \?\? 0 \}, served\)\)/u); + const catalog = source("src/lib/model-catalog.ts"); + assert.match(catalog, /\.\.\.cacheHitPrice\(row\.provider_model, Number\(row\.input_cost\)\)/u); + assert.match(catalog, /cacheHitCostMicrousdPerMillion: fallback\.cacheHitCostMicrousdPerMillion/u); + const page = source("src/components/admin/launch-setup.tsx"); + assert.doesNotMatch(page, /积分/u); +}); diff --git a/frontend/tests/western-chat-2342.test.ts b/frontend/tests/western-chat-2342.test.ts index e0208550f..64bd48365 100644 --- a/frontend/tests/western-chat-2342.test.ts +++ b/frontend/tests/western-chat-2342.test.ts @@ -126,12 +126,23 @@ test("western_chart: true puts the Western facts next to the card; without it th assert.equal(calls.length, 1); assert.deepEqual(western.western_natal, westernNatalToolFacts(obama)); const { western_natal: _dropped, ...rest } = western; - assert.equal(JSON.stringify(rest), JSON.stringify(vedic), "the card and everything else are the same bytes"); - assert.equal(flagged.state.evidenceCardChars, plain.state.evidenceCardChars); + // 原值:western_chart: true 时除 western_natal 外与印度盘结果逐字节相同,evidenceCardChars 相等; + // 新值:true 等于 "only",模型看到的结果不带印度时间卡(timing),其余逐字节相同;"both" 仍逐字节相同; + // 原因:BUG-2432,只问西洋时程序会删掉回答的时间部分,时间卡送了也白送。 + const withoutTiming = { ...vedic, claim_cards: (vedic.claim_cards as Json[]).filter((claim) => claim.category !== "timing") }; + assert.deepEqual(Object.keys(rest), Object.keys(vedic)); + assert.equal(JSON.stringify(rest.claim_cards), JSON.stringify(withoutTiming.claim_cards), "only the timing card is left out"); + assert.ok(flagged.state.evidenceCardChars! < plain.state.evidenceCardChars!); + assert.deepEqual(flagged.state.evidenceCard!.base.timing, plain.state.evidenceCard!.base.timing, "the server card keeps its timing"); // A later western:natal lookup reuses the same read. const lookup = await flagged.tools[CONSULTATION_EVIDENCE_LOOKUP_TOOL_ID].execute!({ section: "western:natal" } as never, writer) as Json; assert.deepEqual(lookup.data, western.western_natal); assert.equal(calls.length, 1); + const both = make(); + const twoSides = await both.tools["run-jyotish-consultation"].execute!({ question: "q", domains: ["parents"], western_chart: "both" } as never, writer) as Json; + const { western_natal: _bothDropped, ...bothRest } = twoSides; + assert.equal(JSON.stringify(bothRest), JSON.stringify(vedic), "both sides: the card and everything else are the same bytes"); + assert.equal(both.state.evidenceCardChars, plain.state.evidenceCardChars); }); test("a failed Western read falls back to the card's short Western block, never to nothing", async () => {