Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add chat cost estimate support (#14876)

YuTengjingd3973a5cc011
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 3314139c725..eb0dc911f4e 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -5,8 +5,8 @@
"agentOnboardingPromo.description": "Set up your agent teams in a quick chat with Lobe AI. Your existing agents remain unchanged.",
"agentOnboardingPromo.title": "Quick Wizard",
"alert.cloud.action": "Try now",
- "alert.cloud.desc": "All registered users get {{credit}} free computing credits per month—no setup needed. Includes global cloud sync and advanced web search.",
- "alert.cloud.descOnMobile": "All registered users get {{credit}} free computing credits per month—no setup needed.",
+ "alert.cloud.desc": "All registered users get {{credit}} free credits per month—no setup needed. Includes global cloud sync and advanced web search.",
+ "alert.cloud.descOnMobile": "All registered users get {{credit}} free credits per month—no setup needed.",
"alert.cloud.title": "{{name}} beta is live",
"alreadyUpToDate": "Already Up to Date",
"appLoading.appIdle": "Ready to start",
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index 14a4ae5b908..fbc615e50c3 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -35,9 +35,9 @@
"table.columns.type.enums.imageGeneration": "Image Generation",
"table.columns.type.enums.videoGeneration": "Video Generation",
"table.columns.type.title": "Type",
- "table.desc": "Details of computing credits usage for text generation, embedding, image generation, etc.",
+ "table.desc": "Details of credit usage for text generation, embedding, image generation, etc.",
"table.more": "View Details",
- "table.title": "Computing Credits Usage Details",
+ "table.title": "Credit Usage Details",
"table.totalToken.input": "Input",
"table.totalToken.output": "Output"
}
diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.json
index 67fa0138a86..392bd8750ab 100644
--- a/locales/en-US/subscription.json
+++ b/locales/en-US/subscription.json
@@ -29,8 +29,8 @@
"cancelPlan.desc": "After cancellation, you will be downgraded to the free version when the current plan expires.",
"cancelPlan.title": "Cancel Subscription",
"cancelSubscription": "Cancel Subscription",
- "compare.hobbyCreditTooltip": "Does not include monthly computing credits, you need to configure your own model API",
- "compare.monthlyCredit": "Monthly Computing Credits",
+ "compare.hobbyCreditTooltip": "Does not include monthly credits, you need to configure your own model API",
+ "compare.monthlyCredit": "Monthly Credits",
"compare.title": "Plan Comparison",
"compareAllPlans": "View All Plans",
"comparePlans": "View Plans",
@@ -132,11 +132,11 @@
"limitation.chat.topupSuccess.action": "Continue Chatting",
"limitation.chat.topupSuccess.desc": "Your top-up credits are now active. Enjoy AI chatting. Your current plan includes:",
"limitation.chat.topupSuccess.title": "Top-up Successful",
- "limitation.expired.desc": "Your {{plan}} computing credits expired on {{expiredAt}}. Upgrade your plan now to get computing credits.",
- "limitation.expired.title": "Computing Credits Expired",
+ "limitation.expired.desc": "Your {{plan}} credits expired on {{expiredAt}}. Upgrade your plan now to get credits.",
+ "limitation.expired.title": "Credits Expired",
"limitation.hobby.action": "Configured, continue chatting",
"limitation.hobby.configAPI": "Configure API",
- "limitation.hobby.desc": "Your free computing credits have been exhausted. Please configure a custom model API to continue.",
+ "limitation.hobby.desc": "Your free credits have been exhausted. Please configure a custom model API to continue.",
"limitation.hobby.docs": "View configuration docs",
"limitation.hobby.tip": "Remember to switch to a model with custom API Key",
"limitation.hobby.title": "Please Configure Model Service API",
@@ -160,10 +160,10 @@
"limitation.insufficientBudget.title": "Insufficient Credits",
"limitation.limited.action": "Upgrade Now",
"limitation.limited.advanceFeature": "Upgrade to enjoy premium features:",
- "limitation.limited.desc": "Your {{plan}} computing credits have been exhausted. Upgrade now to get more credits.",
- "limitation.limited.descUltimate": "Your {{plan}} computing credits have been exhausted. Please top up credits to continue.",
+ "limitation.limited.desc": "Your {{plan}} credits have been exhausted. Upgrade now to get more credits.",
+ "limitation.limited.descUltimate": "Your {{plan}} credits have been exhausted. Please top up credits to continue.",
"limitation.limited.referralTip": "Invite friends, both get {{reward}}M",
- "limitation.limited.title": "Computing Credits Exhausted",
+ "limitation.limited.title": "Credits Exhausted",
"limitation.limited.topup": "Top-Up Credits",
"limitation.limited.upgrade": "Upgrade to Higher Plan",
"limitation.limited.upgradeToPlan": "Upgrade to {{plan}}",
@@ -187,7 +187,7 @@
"limitation.video.topupSuccess.desc": "Your top-up credits are now active. Enjoy AI video generation. Your current plan includes:",
"limitation.video.topupSuccess.title": "Top-up Successful",
"modelPricing.button": "View Pricing Documentation",
- "modelPricing.desc": "{{name}} uses Credits to measure AI model usage. The table below shows computing credits per 1M Tokens.",
+ "modelPricing.desc": "{{name}} uses Credits to measure AI model usage. The table below shows credits per 1M Tokens.",
"modelPricing.title": "Text Model Pricing",
"models.input": "Input",
"models.intro": "Introduction",
@@ -231,12 +231,12 @@
"plans.credit.api": "Custom API",
"plans.credit.apiDesc": "Requires your own model API configuration",
"plans.credit.apiProvider": "Supports 20+ mainstream model providers including OpenAI / Anthropic / OpenRouter",
- "plans.credit.buy": "Purchase Computing Credits",
- "plans.credit.buyDesc": "Also supports purchasing computing credits on demand",
- "plans.credit.none": "No built-in computing credits",
+ "plans.credit.buy": "Purchase Credits",
+ "plans.credit.buyDesc": "Also supports purchasing credits on demand",
+ "plans.credit.none": "No built-in credits",
"plans.credit.tip": "{{credit}} free credits per month",
- "plans.credit.title": "Computing Credits",
- "plans.credit.tooltip": "Monthly model message computing credits",
+ "plans.credit.title": "Credits",
+ "plans.credit.tooltip": "Monthly model message credits",
"plans.current": "Current Plan",
"plans.downgradePlan": "Target Downgrade Plan",
"plans.downgradeTip": "Your subscription has been canceled. You cannot perform other operations until the cancellation is complete",
@@ -306,16 +306,16 @@
"plans.unlimited": "Unlimited",
"qa.desc": "If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.",
"qa.detail": "View Details",
- "qa.list.credit.a": "Computing credits are a metric used by {{cloud}} to measure AI model usage when calling models. Different AI models consume different amounts of computing credits.",
- "qa.list.credit.q": "What are computing credits?",
+ "qa.list.credit.a": "Credits are how {{cloud}} measures AI model usage. Different AI models consume different amounts of credits.",
+ "qa.list.credit.q": "What are credits?",
"qa.list.embeddings.a": "Vector storage is not equal to the original size of your uploaded or imported dataset, but is calculated based on the vectorization of pure text content in your files. For example, a 1-page PDF file (1000-1500 characters) may only take up about 1 vector storage entry when extracted and vectorized into pure text. You can view your usage under \"{{usage}}\".",
"qa.list.embeddings.q": "How is vector storage calculated?",
- "qa.list.free.a": "{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free computing credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.",
+ "qa.list.free.a": "{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.",
"qa.list.free.q": "Can {{name}} be used for free?",
"qa.list.highUsage.a": "Credit consumption depends heavily on conversation length. As a conversation grows, each new message sends the entire history as input tokens, which increases cost significantly. We recommend starting a new conversation when topics change. Also, if there is a long gap between messages, the prompt cache may expire, causing a spike in cost. Some models like the Gemini Pro series use tiered pricing — input beyond 200K tokens is charged at double the rate.",
"qa.list.highUsage.q": "Why are my credits being consumed faster than expected?",
- "qa.list.limit.a": "{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different computing credits. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>\"{{funds}}\"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.",
- "qa.list.limit.q": "What if I run out of computing credits?",
+ "qa.list.limit.a": "{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different credit amounts. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>\"{{funds}}\"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.",
+ "qa.list.limit.q": "What if I run out of credits?",
"qa.list.management.a": "On the {{subscribe}} page, you can \"Upgrade / Downgrade\" your current subscription plan, or switch between yearly and monthly billing. Through \"{{usage}}-{{management}}\" you can go to Stripe for subscription management, and you can cancel your subscription at any time. After cancellation, you will be automatically downgraded to the free version when your current plan expires.",
"qa.list.management.q": "How do I change or cancel my subscription?",
"qa.support.community": "Community Support",
@@ -426,7 +426,7 @@
"usage.credit.time.days": "{{days}} days",
"usage.credit.time.daysAndHours": "{{days}} days {{hours}} hours",
"usage.credit.time.hours": "{{hours}} hours",
- "usage.credit.title": "Computing Credits Usage",
+ "usage.credit.title": "Credit Usage",
"usage.overview.charge": "Charges",
"usage.overview.included": "Plan Usage",
"usage.overview.onDemand": "On-demand",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 5b1c7065453..7b8dd3fd985 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -220,6 +220,13 @@
"inbox.title": "Lobe AI",
"input.addAi": "添加一条助理消息",
"input.addUser": "添加一条用户消息",
+ "input.costEstimate.creditsPerMillionTokens": "{{credits}} 积分/M tokens",
+ "input.costEstimate.hint": "预估费用:约 {{credits}} 积分",
+ "input.costEstimate.inputLabel": "输入",
+ "input.costEstimate.outputLabel": "输出",
+ "input.costEstimate.settingsLink": "调整提醒阈值",
+ "input.costEstimate.tokenCount": "约 {{tokens}} tokens",
+ "input.costEstimate.tooltip": "基于当前上下文、工具和模型定价估算。实际费用可能不同。",
"input.disclaimer": "助理也可能出错。关键信息请以你的判断为准",
"input.errorMsg": "发送遇到了问题:{{errorMsg}}。你可以重试,或稍后再发",
"input.more": "更多",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index fb91a57f762..a8b56593826 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -5,8 +5,8 @@
"agentOnboardingPromo.description": "与 Lobe AI 快速聊几句,即可设置你的助理团队。你现有的助理不会受到影响。",
"agentOnboardingPromo.title": "快速向导",
"alert.cloud.action": "立即体验",
- "alert.cloud.desc": "所有注册用户每月可获得 {{credit}} 免费计算额度—无需设置。包括全球云同步和高级网页搜索功能。",
- "alert.cloud.descOnMobile": "所有注册用户每月可获得 {{credit}} 免费计算额度—无需设置。",
+ "alert.cloud.desc": "所有注册用户每月可获得 {{credit}} 免费积分—无需设置。包括全球云同步和高级网页搜索功能。",
+ "alert.cloud.descOnMobile": "所有注册用户每月可获得 {{credit}} 免费积分—无需设置。",
"alert.cloud.title": "{{name}} 开始公测",
"alreadyUpToDate": "已是最新版本",
"appLoading.appIdle": "准备启动",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index 9cc719095be..d00fbea2ef3 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -71,10 +71,10 @@
"FileParsingStatus.chunks.status.errorResult": "分块失败,请检查后重试。失败原因:",
"FileParsingStatus.chunks.status.processing": "分块中…",
"FileParsingStatus.chunks.status.processingTip": "服务端正在拆分文本块,关闭页面不会影响进度",
- "GenerationModelItem.creditsPerImageApproximate": "约 {{amount}} 算力积分/张",
- "GenerationModelItem.creditsPerImageExact": "{{amount}} 算力积分/张",
- "GenerationModelItem.creditsPerVideoApproximate": "约 {{amount}} 算力积分/条",
- "GenerationModelItem.creditsPerVideoExact": "{{amount}} 算力积分/条",
+ "GenerationModelItem.creditsPerImageApproximate": "约 {{amount}} 积分/张",
+ "GenerationModelItem.creditsPerImageExact": "{{amount}} 积分/张",
+ "GenerationModelItem.creditsPerVideoApproximate": "约 {{amount}} 积分/条",
+ "GenerationModelItem.creditsPerVideoExact": "{{amount}} 积分/条",
"GoBack.back": "返回",
"HtmlPreview.actions.download": "下载",
"HtmlPreview.actions.preview": "预览",
@@ -121,6 +121,16 @@
"ModelSwitchPanel.detail.context": "上下文长度",
"ModelSwitchPanel.detail.pricing": "价格",
"ModelSwitchPanel.detail.pricing.cachedInput": "缓存输入 ${{amount}}/百万",
+ "ModelSwitchPanel.detail.pricing.credits.cachedInput": "缓存输入 {{amount}} 积分/M tokens",
+ "ModelSwitchPanel.detail.pricing.credits.image": "积分/张",
+ "ModelSwitchPanel.detail.pricing.credits.input": "输入 {{amount}} 积分/M tokens",
+ "ModelSwitchPanel.detail.pricing.credits.megapixel": "积分/MP",
+ "ModelSwitchPanel.detail.pricing.credits.millionCharacters": "积分/M chars",
+ "ModelSwitchPanel.detail.pricing.credits.millionTokens": "积分/M tokens",
+ "ModelSwitchPanel.detail.pricing.credits.output": "输出 {{amount}} 积分/M tokens",
+ "ModelSwitchPanel.detail.pricing.credits.perImage": "约 {{amount}} 积分/张",
+ "ModelSwitchPanel.detail.pricing.credits.perVideo": "约 {{amount}} 积分/条",
+ "ModelSwitchPanel.detail.pricing.credits.second": "积分/s",
"ModelSwitchPanel.detail.pricing.group.audio": "音频",
"ModelSwitchPanel.detail.pricing.group.image": "图像",
"ModelSwitchPanel.detail.pricing.group.text": "文本",
diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.json
index 667a31c20d7..928a8b17575 100644
--- a/locales/zh-CN/subscription.json
+++ b/locales/zh-CN/subscription.json
@@ -55,6 +55,12 @@
"credits.autoTopUp.toggle": "启用自动充值",
"credits.autoTopUp.upgradeHint": "订阅付费计划以启用自动充值",
"credits.autoTopUp.validation.targetMustExceedThreshold": "目标余额必须大于触发阈值",
+ "credits.costEstimateHint.desc": "当下一次模型调用的预估费用达到阈值时,在发送前显示轻量提醒",
+ "credits.costEstimateHint.saveError": "保存费用预估提醒设置失败",
+ "credits.costEstimateHint.saveSuccess": "费用预估提醒设置已保存",
+ "credits.costEstimateHint.threshold": "提醒阈值",
+ "credits.costEstimateHint.title": "费用预估提醒",
+ "credits.costEstimateHint.validation.threshold": "阈值必须大于或等于 0",
"credits.packages.auto": "自动",
"credits.packages.charged": "已扣费 ${{amount}}",
"credits.packages.expired": "已过期",
@@ -231,12 +237,12 @@
"plans.credit.api": "自定义 API",
"plans.credit.apiDesc": "需配置您自己的模型 API",
"plans.credit.apiProvider": "支持 OpenAI / Anthropic / OpenRouter 等 20+ 主流模型提供商",
- "plans.credit.buy": "购买算力积分",
- "plans.credit.buyDesc": "也支持按需购买算力积分",
- "plans.credit.none": "无内置算力积分",
- "plans.credit.tip": "每月赠送 {{credit}} 点免费算力",
- "plans.credit.title": "算力积分",
- "plans.credit.tooltip": "每月模型消息计算所用的算力积分",
+ "plans.credit.buy": "购买积分",
+ "plans.credit.buyDesc": "也支持按需购买积分",
+ "plans.credit.none": "无内置积分",
+ "plans.credit.tip": "每月赠送 {{credit}} 免费积分",
+ "plans.credit.title": "积分",
+ "plans.credit.tooltip": "每月可用于模型调用的积分",
"plans.current": "当前计划",
"plans.downgradePlan": "目标降级计划",
"plans.downgradeTip": "您已取消订阅,需等待取消生效后才能进行其他操作",
@@ -306,16 +312,16 @@
"plans.unlimited": "无限制",
"qa.desc": "如果您的问题未被解答,请查看 <1>产品文档</1> 获取更多常见问题,或联系我们。",
"qa.detail": "查看详情",
- "qa.list.credit.a": "算力积分是 {{cloud}} 用于衡量调用 AI 模型时的使用量指标。不同模型消耗的积分不同。",
- "qa.list.credit.q": "什么是算力积分?",
+ "qa.list.credit.a": "积分是 {{cloud}} 用于衡量 AI 模型调用用量的指标。不同模型消耗的积分不同。",
+ "qa.list.credit.q": "什么是积分?",
"qa.list.embeddings.a": "向量存储并不等于您上传或导入数据集的原始大小,而是根据文件中纯文本内容向量化后的结果计算。例如,一页 PDF 文件(1000-1500 字符)提取为纯文本后,可能只占用约 1 个向量存储条目。您可在“{{usage}}”中查看使用情况。",
"qa.list.embeddings.q": "向量存储是如何计算的?",
- "qa.list.free.a": "{{name}} 始终坚持开源原则。专业开发者可通过部署社区版使用全部开源功能。在 {{cloud}} 中,我们为所有注册用户每月提供 {{credit}} 点免费算力,无需复杂配置即可使用。如需更多使用量,可订阅 {{starter}}、{{premium}} 或 {{ultimate}}。",
+ "qa.list.free.a": "{{name}} 始终坚持开源原则。专业开发者可通过部署社区版使用全部开源功能。在 {{cloud}} 中,我们为所有注册用户每月提供 {{credit}} 免费积分,无需复杂配置即可使用。如需更多使用量,可订阅 {{starter}}、{{premium}} 或 {{ultimate}}。",
"qa.list.free.q": "{{name}} 可以免费使用吗?",
"qa.list.highUsage.a": "积分消耗与对话长度密切相关。随着对话变长,每条新消息都会将完整历史作为输入 token 发送,导致费用显著增加。建议在切换话题时开启新对话。此外,如果两次发送间隔较长,提示词缓存可能失效,也会导致费用骤增。部分模型(如 Gemini Pro 系列)采用分梯度定价,输入超过 200K token 后费率翻倍。",
"qa.list.highUsage.q": "为什么我的积分消耗比预期快?",
- "qa.list.limit.a": "{{cloud}} 的订阅计划分为 {{starter}}、{{premium}} 和 {{ultimate}},每个计划提供不同的算力积分。如当前计划积分不足,建议升级计划。您也可以在<fundsLink>「{{funds}}」</fundsLink>页面购买积分包进行按量付费充值。此外,您也可以配置自定义模型 API 密钥,使用其他来源购买的 API 积分。",
- "qa.list.limit.q": "算力积分用完怎么办?",
+ "qa.list.limit.a": "{{cloud}} 的订阅计划分为 {{starter}}、{{premium}} 和 {{ultimate}},每个计划提供不同的积分额度。如当前计划积分不足,建议升级计划。您也可以在<fundsLink>「{{funds}}」</fundsLink>页面购买积分包进行按量付费充值。此外,您也可以配置自定义模型 API 密钥,使用其他来源购买的 API 积分。",
+ "qa.list.limit.q": "积分用完怎么办?",
"qa.list.management.a": "在 {{subscribe}} 页面,您可以“升级 / 降级”当前订阅计划,或切换年付与月付。在“{{usage}}-{{management}}”中可跳转至 Stripe 进行订阅管理,您可随时取消订阅。取消后,当前计划到期时将自动降级为免费版。",
"qa.list.management.q": "如何更改或取消订阅?",
"qa.support.community": "社区支持",
@@ -426,7 +432,7 @@
"usage.credit.time.days": "{{days}} 天",
"usage.credit.time.daysAndHours": "{{days}} 天 {{hours}} 小时",
"usage.credit.time.hours": "{{hours}} 小时",
- "usage.credit.title": "算力积分使用情况",
+ "usage.credit.title": "积分使用情况",
"usage.overview.charge": "按量计费",
"usage.overview.included": "计划内使用",
"usage.overview.onDemand": "按需使用",
diff --git a/packages/const/src/settings/common.ts b/packages/const/src/settings/common.ts
index efd285641d7..d7dbc27c6f7 100644
--- a/packages/const/src/settings/common.ts
+++ b/packages/const/src/settings/common.ts
@@ -1,8 +1,11 @@
import type { UserGeneralConfig } from '@lobechat/types';
+export const DEFAULT_COST_ESTIMATE_WARNING_THRESHOLD = 2;
+
export const DEFAULT_COMMON_SETTINGS: UserGeneralConfig = {
animationMode: 'agile',
// contextMenuMode not set default value, use env to calc
+ costEstimateWarningThreshold: DEFAULT_COST_ESTIMATE_WARNING_THRESHOLD,
fontSize: 14,
highlighterTheme: 'lobe-theme',
isDevMode: false,
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index 0ba4ab49404..a1207331b12 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -21,16 +21,26 @@ export * from './providers';
export type {
ContextTokenAccounting,
CountContextTokensParams,
+ InputTokenBuckets,
MessageTokenBreakdown,
TokenSourceType,
ToolDefinitionTokenBreakdown,
} from './tokenAccounting';
-export { countContextTokens, DEFAULT_DRIFT_MULTIPLIER } from './tokenAccounting';
+export {
+ addTokenBuckets,
+ countContextTokens,
+ DEFAULT_DRIFT_MULTIPLIER,
+ EMPTY_TOKEN_BUCKETS,
+ estimatePendingUploadTokenBuckets,
+ estimateSentMessageAttachmentTokenBuckets,
+ isTextLikeUploadFile,
+} from './tokenAccounting';
// Processors
export type { PlaceholderValue, PlaceholderValueMap } from './processors';
export {
buildPlaceholderGenerators,
formatPlaceholderValues,
+ getSlicedMessages,
GroupMessageFlattenProcessor,
HistoryTruncateProcessor,
InputTemplateProcessor,
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 577951eb821..3e01099240e 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -9,7 +9,7 @@ export {
type OrchestrationAgentInfo,
} from './GroupOrchestrationFilter';
export { GroupRoleTransformProcessor } from './GroupRoleTransform';
-export { HistoryTruncateProcessor } from './HistoryTruncate';
+export { getSlicedMessages, HistoryTruncateProcessor } from './HistoryTruncate';
export { InputTemplateProcessor } from './InputTemplate';
export { MessageCleanupProcessor } from './MessageCleanup';
export { MessageContentProcessor } from './MessageContent';
diff --git a/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts
new file mode 100644
index 00000000000..595ca362850
--- /dev/null
+++ b/packages/context-engine/src/tokenAccounting/__tests__/attachmentTokenBuckets.test.ts
@@ -0,0 +1,139 @@
+import type { UIChatMessage, UploadFileItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ estimatePendingUploadTokenBuckets,
+ estimateSentMessageAttachmentTokenBuckets,
+ isTextLikeUploadFile,
+} from '../attachmentTokenBuckets';
+
+const mkMsg = (m: Partial<UIChatMessage> & { role: UIChatMessage['role'] }): UIChatMessage =>
+ ({
+ content: '',
+ createdAt: 0,
+ id: 'm',
+ updatedAt: 0,
+ ...m,
+ }) as UIChatMessage;
+
+const mkUploadFile = ({
+ id,
+ name,
+ size,
+ type,
+}: {
+ id: string;
+ name: string;
+ size: number;
+ type: string;
+}): UploadFileItem => ({
+ file: { name, size, type } as File,
+ fileUrl: `https://example.com/${name}`,
+ id,
+ status: 'success',
+});
+
+describe('attachment token buckets', () => {
+ it('estimates persisted file context and visual input buckets', () => {
+ const result = estimateSentMessageAttachmentTokenBuckets(
+ [
+ mkMsg({
+ fileList: [
+ {
+ content: 'parsed text',
+ fileType: 'text/plain',
+ id: 'file-id',
+ name: 'note.txt',
+ size: 11,
+ url: 'https://example.com/note.txt',
+ },
+ ],
+ imageList: [{ alt: 'image.png', id: 'image-id', url: 'https://example.com/image.png' }],
+ role: 'user',
+ videoList: [{ alt: 'video.mp4', id: 'video-id', url: 'https://example.com/video.mp4' }],
+ }),
+ ],
+ { canUseVideo: true, canUseVision: true },
+ );
+
+ expect(result.textTokens).toBeGreaterThan(0);
+ expect(result.imageTokens).toBe(1000);
+ expect(result.videoTokens).toBe(1000);
+ });
+
+ it('keeps file context but skips visual buckets when the model cannot consume them', () => {
+ const result = estimateSentMessageAttachmentTokenBuckets(
+ [
+ mkMsg({
+ imageList: [{ alt: 'image.png', id: 'image-id', url: 'https://example.com/image.png' }],
+ role: 'user',
+ videoList: [{ alt: 'video.mp4', id: 'video-id', url: 'https://example.com/video.mp4' }],
+ }),
+ ],
+ { canUseVideo: false, canUseVision: false },
+ );
+
+ expect(result.textTokens).toBeGreaterThan(0);
+ expect(result.imageTokens).toBe(0);
+ expect(result.videoTokens).toBe(0);
+ });
+
+ it('estimates pending upload buckets with text fallback and loaded text content', () => {
+ const files = [
+ mkUploadFile({ id: 'text-file', name: 'note.txt', size: 40, type: 'text/plain' }),
+ mkUploadFile({ id: 'image-file', name: 'image.png', size: 100, type: 'image/png' }),
+ mkUploadFile({ id: 'video-file', name: 'video.mp4', size: 200, type: 'video/mp4' }),
+ ];
+
+ const fallbackResult = estimatePendingUploadTokenBuckets(
+ files,
+ { canUseVideo: true, canUseVision: true },
+ {},
+ );
+ const loadedResult = estimatePendingUploadTokenBuckets(
+ files,
+ { canUseVideo: true, canUseVision: true },
+ { 'text-file': 'loaded text content' },
+ );
+
+ expect(fallbackResult.textTokens).toBeGreaterThanOrEqual(10);
+ expect(loadedResult.textTokens).toBeGreaterThan(0);
+ expect(fallbackResult.imageTokens).toBe(1000);
+ expect(fallbackResult.videoTokens).toBe(1000);
+ expect(loadedResult.imageTokens).toBe(1000);
+ expect(loadedResult.videoTokens).toBe(1000);
+ });
+
+ it('detects text-like upload files by mime type and extension', () => {
+ expect(
+ isTextLikeUploadFile(
+ mkUploadFile({ id: 'json', name: 'data.bin', size: 1, type: 'application/json' }),
+ ),
+ ).toBe(true);
+ expect(
+ isTextLikeUploadFile(
+ mkUploadFile({
+ id: 'markdown',
+ name: 'README.md',
+ size: 1,
+ type: 'application/octet-stream',
+ }),
+ ),
+ ).toBe(true);
+ expect(
+ isTextLikeUploadFile(
+ mkUploadFile({
+ id: 'typescript',
+ name: 'app.ts',
+ size: 1,
+ type: 'application/octet-stream',
+ }),
+ ),
+ ).toBe(true);
+ expect(
+ isTextLikeUploadFile(
+ mkUploadFile({ id: 'pdf', name: 'document.pdf', size: 1, type: 'application/pdf' }),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts
new file mode 100644
index 00000000000..392884244bc
--- /dev/null
+++ b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts
@@ -0,0 +1,215 @@
+// cspell:ignore tokenx
+import { filesPrompts } from '@lobechat/prompts';
+import type {
+ ChatFileItem,
+ ChatImageItem,
+ ChatVideoItem,
+ UIChatMessage,
+ UploadFileItem,
+} from '@lobechat/types';
+import { getMimeType } from '@lobechat/utils/mimeType';
+import { estimateTokenCount } from 'tokenx';
+
+const ESTIMATE_INPUT_MESSAGE_ID = '__cost_estimate_input__';
+const VISUAL_INPUT_TOKEN_ESTIMATE = 1000;
+const BYTES_PER_TEXT_TOKEN_ESTIMATE = 4;
+const TEXT_UPLOAD_MIME_TYPES = new Set([
+ 'application/javascript',
+ 'application/json',
+ 'application/ld+json',
+ 'application/sql',
+ 'application/toml',
+ 'application/typescript',
+ 'application/x-httpd-php',
+ 'application/x-javascript',
+ 'application/x-ndjson',
+ 'application/x-sh',
+ 'application/x-typescript',
+ 'application/x-yaml',
+ 'application/xml',
+]);
+const TEXT_UPLOAD_EXTENSION_OVERRIDES = new Set(['.cs', '.jsonl', '.ts', '.tsx']);
+
+export interface InputTokenBuckets {
+ imageTokens: number;
+ textTokens: number;
+ videoTokens: number;
+}
+
+interface AttachmentTokenOptions {
+ canUseVideo: boolean;
+ canUseVision: boolean;
+}
+
+export const EMPTY_TOKEN_BUCKETS: InputTokenBuckets = {
+ imageTokens: 0,
+ textTokens: 0,
+ videoTokens: 0,
+};
+
+const countPromptTextTokens = (content: string) => {
+ if (!content) return 0;
+
+ return estimateTokenCount(content);
+};
+
+const countFileContextTokens = ({
+ fileList,
+ imageList,
+ messageId,
+ videoList,
+}: {
+ fileList?: ChatFileItem[];
+ imageList?: ChatImageItem[];
+ messageId: string;
+ videoList?: ChatVideoItem[];
+}) => {
+ const prompt = filesPrompts({
+ addUrl: false,
+ fileList,
+ imageList,
+ messageId,
+ videoList,
+ });
+
+ return countPromptTextTokens(prompt);
+};
+
+export const estimateSentMessageAttachmentTokenBuckets = (
+ messages: UIChatMessage[],
+ { canUseVideo, canUseVision }: AttachmentTokenOptions,
+): InputTokenBuckets => {
+ let textTokens = 0;
+ let imageTokens = 0;
+ let videoTokens = 0;
+
+ for (const message of messages) {
+ if (message.role !== 'user') continue;
+
+ const fileList = message.fileList ?? [];
+ const imageList = message.imageList ?? [];
+ const videoList = message.videoList ?? [];
+
+ if (fileList.length === 0 && imageList.length === 0 && videoList.length === 0) continue;
+
+ textTokens += countFileContextTokens({
+ fileList,
+ imageList,
+ messageId: message.id,
+ videoList,
+ });
+
+ if (canUseVision) {
+ imageTokens += imageList.length * VISUAL_INPUT_TOKEN_ESTIMATE;
+ }
+
+ if (canUseVideo) {
+ videoTokens += videoList.length * VISUAL_INPUT_TOKEN_ESTIMATE;
+ }
+ }
+
+ return {
+ imageTokens,
+ textTokens,
+ videoTokens,
+ };
+};
+
+const getUploadFileUrl = (item: UploadFileItem) =>
+ item.fileUrl || item.base64Url || item.previewUrl || '';
+
+const isTextLikeMimeType = (type: string) =>
+ type.startsWith('text/') || TEXT_UPLOAD_MIME_TYPES.has(type);
+
+const getFileExtension = (name: string) => {
+ const dotIndex = name.lastIndexOf('.');
+
+ return dotIndex >= 0 ? name.slice(dotIndex).toLowerCase() : '';
+};
+
+export const isTextLikeUploadFile = (item: UploadFileItem) => {
+ const declaredType = item.file.type.toLowerCase();
+ const inferredType = getMimeType(item.file.name).toLowerCase();
+ const name = item.file.name.toLowerCase();
+
+ return (
+ isTextLikeMimeType(declaredType) ||
+ isTextLikeMimeType(inferredType) ||
+ TEXT_UPLOAD_EXTENSION_OVERRIDES.has(getFileExtension(name))
+ );
+};
+
+const estimateTextFileTokensBySize = (size: number) =>
+ Math.ceil(size / BYTES_PER_TEXT_TOKEN_ESTIMATE);
+
+export const estimatePendingUploadTokenBuckets = (
+ files: UploadFileItem[],
+ { canUseVideo, canUseVision }: AttachmentTokenOptions,
+ textFileContents: Record<string, string>,
+): InputTokenBuckets => {
+ if (files.length === 0) return EMPTY_TOKEN_BUCKETS;
+
+ const fileList: ChatFileItem[] = [];
+ const imageList: ChatImageItem[] = [];
+ const videoList: ChatVideoItem[] = [];
+ let pendingTextFallbackTokens = 0;
+
+ for (const item of files) {
+ const type = item.file.type || '';
+ const url = getUploadFileUrl(item);
+
+ if (type.startsWith('image')) {
+ imageList.push({
+ alt: item.file.name || item.id,
+ id: item.id,
+ url,
+ });
+ continue;
+ }
+
+ if (type.startsWith('video')) {
+ videoList.push({
+ alt: item.file.name || item.id,
+ id: item.id,
+ url,
+ });
+ continue;
+ }
+
+ const textContent = textFileContents[item.id];
+ if (isTextLikeUploadFile(item) && textContent === undefined) {
+ pendingTextFallbackTokens += estimateTextFileTokensBySize(item.file.size || 0);
+ }
+
+ fileList.push({
+ content: textContent,
+ fileType: type,
+ id: item.id,
+ name: item.file.name || item.id,
+ size: item.file.size || 0,
+ url,
+ });
+ }
+
+ return {
+ imageTokens: canUseVision ? imageList.length * VISUAL_INPUT_TOKEN_ESTIMATE : 0,
+ textTokens:
+ countFileContextTokens({
+ fileList,
+ imageList,
+ messageId: ESTIMATE_INPUT_MESSAGE_ID,
+ videoList,
+ }) + pendingTextFallbackTokens,
+ videoTokens: canUseVideo ? videoList.length * VISUAL_INPUT_TOKEN_ESTIMATE : 0,
+ };
+};
+
+export const addTokenBuckets = (...buckets: InputTokenBuckets[]): InputTokenBuckets =>
+ buckets.reduce<InputTokenBuckets>(
+ (sum, bucket) => ({
+ imageTokens: sum.imageTokens + bucket.imageTokens,
+ textTokens: sum.textTokens + bucket.textTokens,
+ videoTokens: sum.videoTokens + bucket.videoTokens,
+ }),
+ EMPTY_TOKEN_BUCKETS,
+ );
diff --git a/packages/context-engine/src/tokenAccounting/index.ts b/packages/context-engine/src/tokenAccounting/index.ts
index 0fc6a3ceb6c..e6d2e45beb8 100644
--- a/packages/context-engine/src/tokenAccounting/index.ts
+++ b/packages/context-engine/src/tokenAccounting/index.ts
@@ -1,3 +1,4 @@
+// cspell:ignore tokenx
import { estimateTokenCount } from 'tokenx';
import type {
@@ -8,6 +9,8 @@ import type {
ToolDefinitionTokenBreakdown,
} from './types';
+export * from './attachmentTokenBuckets';
+
export const DEFAULT_DRIFT_MULTIPLIER = 1.25;
const ZERO_BY_SOURCE = (): Record<TokenSourceType, number> => ({
diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.ts
index 853ddd19888..d4f6636920c 100644
--- a/packages/model-runtime/src/core/usageConverters/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/index.ts
@@ -3,5 +3,16 @@ export { convertGoogleAIUsage } from './google-ai';
export { convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
export { computeImageCost } from './utils/computeImageCost';
export { computeVideoCost } from './utils/computeVideoCost';
+export {
+ type ChatCostEstimate,
+ type ChatInputTokenEstimate,
+ estimateChatCostFromMessages,
+ type EstimateChatCostFromMessagesOptions,
+ estimateChatCostFromTokens,
+ type EstimateChatCostFromTokensInput,
+ estimateChatOutputTokens,
+ estimateOpenAIChatInputTokens,
+ type EstimateOpenAIChatInputTokensOptions,
+} from './utils/estimateChatCost';
export { resolveImageSinglePrice } from './utils/resolveImageSinglePrice';
export { resolveVideoSinglePrice } from './utils/resolveVideoSinglePrice';
diff --git a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts
new file mode 100644
index 00000000000..4b04e898042
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.test.ts
@@ -0,0 +1,263 @@
+import type { Pricing } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import {
+ estimateChatCostFromMessages,
+ estimateChatCostFromTokens,
+ estimateChatOutputTokens,
+ estimateOpenAIChatInputTokens,
+} from './estimateChatCost';
+
+describe('estimateChatCost', () => {
+ describe('estimateChatOutputTokens', () => {
+ it('applies the output ratio below the cap', () => {
+ expect(estimateChatOutputTokens(4000)).toBe(2000);
+ expect(estimateChatOutputTokens(1000)).toBe(500);
+ });
+
+ it('caps output tokens for large inputs', () => {
+ expect(estimateChatOutputTokens(20_000)).toBe(8192);
+ expect(estimateChatOutputTokens(1_000_000)).toBe(8192);
+ });
+ });
+
+ describe('estimateOpenAIChatInputTokens', () => {
+ it('counts text, tools, reasoning, and image input buckets', () => {
+ const estimate = estimateOpenAIChatInputTokens(
+ [
+ {
+ content: [
+ { text: 'hello world', type: 'text' },
+ { image_url: { url: 'https://example.com/image.png' }, type: 'image_url' },
+ ],
+ role: 'user',
+ },
+ {
+ content: 'assistant response',
+ reasoning: { content: 'hidden reasoning' },
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{"city":"Shanghai"}', name: 'weather' },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ {
+ tools: [
+ {
+ function: {
+ description: 'Get weather',
+ name: 'weather',
+ parameters: { type: 'object' },
+ },
+ type: 'function',
+ },
+ ],
+ },
+ );
+
+ expect(estimate.imageTokens).toBe(1000);
+ expect(estimate.textTokens).toBeGreaterThan(0);
+ expect(estimate.totalTokens).toBe(estimate.textTokens + 1000);
+ expect(estimate.videoTokens).toBe(0);
+ });
+
+ it('counts video inputs in the video token bucket', () => {
+ const estimate = estimateOpenAIChatInputTokens(
+ [
+ {
+ content: [
+ { text: 'summarize this clip', type: 'text' },
+ { type: 'video_url', video_url: { url: 'https://example.com/video.mp4' } },
+ ],
+ role: 'user',
+ },
+ ],
+ { videoTokenEstimate: 1200 },
+ );
+
+ expect(estimate.imageTokens).toBe(0);
+ expect(estimate.textTokens).toBeGreaterThan(0);
+ expect(estimate.totalTokens).toBe(estimate.textTokens + 1200);
+ expect(estimate.videoTokens).toBe(1200);
+ });
+
+ it('handles assistant tool-call messages with null content', () => {
+ const estimate = estimateOpenAIChatInputTokens([
+ {
+ // @ts-expect-error OpenAI-compatible runtime payloads can contain null content.
+ content: null,
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{"city":"Shanghai"}', name: 'weather' },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ },
+ ]);
+
+ expect(estimate.imageTokens).toBe(0);
+ expect(estimate.textTokens).toBeGreaterThan(0);
+ expect(estimate.totalTokens).toBe(estimate.textTokens);
+ expect(estimate.videoTokens).toBe(0);
+ });
+ });
+
+ describe('estimateChatCostFromTokens', () => {
+ it('uses total input tokens to select tiered rates', () => {
+ const pricing: Pricing = {
+ currency: 'USD',
+ units: [
+ {
+ name: 'textInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 1, upTo: 100 },
+ { rate: 2, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'textOutput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 10, upTo: 100 },
+ { rate: 20, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const estimate = estimateChatCostFromTokens(pricing, {
+ outputTextTokens: 10,
+ textTokens: 120,
+ });
+
+ expect(estimate?.estimatedCost).toBe(0.000_44);
+ expect(estimate?.breakdown.map((item) => item.segments?.[0]?.rate)).toEqual([2, 20]);
+ });
+
+ it('returns undefined when pricing is missing', () => {
+ expect(estimateChatCostFromTokens(undefined, { textTokens: 1000 })).toBeUndefined();
+ });
+
+ it('falls multimodal input back to text pricing when dedicated modality units are missing', () => {
+ const pricing: Pricing = {
+ units: [{ name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],
+ };
+
+ const estimate = estimateChatCostFromTokens(pricing, {
+ audioTokens: 400,
+ imageTokens: 200,
+ outputTextTokens: 0,
+ textTokens: 100,
+ videoTokens: 300,
+ });
+
+ expect(estimate?.estimatedCost).toBe(0.001);
+ expect(estimate?.inputAudioTokens).toBe(400);
+ expect(estimate?.inputImageTokens).toBe(200);
+ expect(estimate?.inputTextTokens).toBe(100);
+ expect(estimate?.inputVideoTokens).toBe(300);
+ expect(estimate?.totalInputTokens).toBe(1000);
+ expect(estimate?.breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(
+ 1000,
+ );
+ });
+
+ it('keeps modality input separate when dedicated modality units exist', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const estimate = estimateChatCostFromTokens(pricing, {
+ imageTokens: 200,
+ outputTextTokens: 0,
+ textTokens: 100,
+ });
+
+ expect(estimate?.breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(
+ 100,
+ );
+ expect(estimate?.breakdown.find((item) => item.unit.name === 'imageInput')?.quantity).toBe(
+ 200,
+ );
+ });
+ });
+
+ describe('estimateChatCostFromMessages', () => {
+ it('builds a cost estimate from OpenAI chat messages', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const estimate = estimateChatCostFromMessages(pricing, [
+ { content: 'hello world', role: 'user' },
+ ]);
+
+ expect(estimate?.estimatedCost).toBeGreaterThan(0);
+ expect(estimate?.estimatedOutputTokens).toBeGreaterThan(0);
+ expect(estimate?.totalInputTokens).toBeGreaterThan(0);
+ expect(estimate?.usage.totalTokens).toBe(
+ estimate!.totalInputTokens + estimate!.estimatedOutputTokens,
+ );
+ });
+
+ it('forwards video inputs to video pricing units', () => {
+ const pricing: Pricing = {
+ units: [{ name: 'videoInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' }],
+ };
+
+ const estimate = estimateChatCostFromMessages(
+ pricing,
+ [
+ {
+ content: [{ type: 'video_url', video_url: { url: 'https://example.com/video.mp4' } }],
+ role: 'user',
+ },
+ ],
+ { videoTokenEstimate: 2000 },
+ );
+
+ expect(estimate?.estimatedCost).toBe(0.006);
+ expect(estimate?.inputVideoTokens).toBe(2000);
+ expect(estimate?.totalInputTokens).toBeGreaterThan(2000);
+ expect(estimate?.breakdown.map((item) => item.unit.name)).toEqual(['videoInput']);
+ });
+
+ it('bills estimated image inputs through text pricing when image pricing is unavailable', () => {
+ const pricing: Pricing = {
+ units: [{ name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],
+ };
+
+ const estimate = estimateChatCostFromMessages(
+ pricing,
+ [
+ {
+ content: [{ image_url: { url: 'https://example.com/image.png' }, type: 'image_url' }],
+ role: 'user',
+ },
+ ],
+ { imageTokenEstimate: 2000 },
+ );
+
+ expect(estimate?.inputImageTokens).toBe(2000);
+ expect(estimate?.totalInputTokens).toBeGreaterThan(2000);
+ expect(estimate?.breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(
+ estimate?.totalInputTokens,
+ );
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts
new file mode 100644
index 00000000000..4d9ad7d0146
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts
@@ -0,0 +1,236 @@
+import type { ModelTokensUsage } from '@lobechat/types';
+import type { Pricing, PricingUnitName } from 'model-bank';
+import { estimateTokenCount } from 'tokenx';
+
+import type { ChatCompletionTool, OpenAIChatMessage } from '../../../types/chat';
+import type { ComputeChatCostOptions, PricingComputationResult } from './computeChatCost';
+import { computeChatCost } from './computeChatCost';
+
+const DEFAULT_IMAGE_INPUT_TOKEN_ESTIMATE = 1000;
+const DEFAULT_VIDEO_INPUT_TOKEN_ESTIMATE = 1000;
+const OUTPUT_INPUT_RATIO = 0.5;
+const OUTPUT_TOKEN_CAP = 8192;
+
+export interface ChatInputTokenEstimate {
+ imageTokens: number;
+ textTokens: number;
+ totalTokens: number;
+ videoTokens: number;
+}
+
+export interface EstimateOpenAIChatInputTokensOptions {
+ /**
+ * Conservative token estimate for each image input when exact image accounting is unavailable.
+ */
+ imageTokenEstimate?: number;
+ /**
+ * Tool definitions are counted as input prompt tokens because providers receive them with the
+ * chat request.
+ */
+ tools?: ChatCompletionTool[];
+ /**
+ * Conservative token estimate for each video input when exact video accounting is unavailable.
+ */
+ videoTokenEstimate?: number;
+}
+
+/**
+ * Token buckets used to estimate chat costs before a provider returns real usage.
+ *
+ * Prefer `computeChatCost` with actual provider usage for final billing and reconciliation.
+ */
+export interface EstimateChatCostFromTokensInput {
+ audioTokens?: number;
+ imageTokens?: number;
+ /**
+ * Optional expected output tokens. When omitted, the estimator uses a heuristic based on input
+ * tokens.
+ */
+ outputTextTokens?: number;
+ textTokens: number;
+ videoTokens?: number;
+}
+
+/**
+ * Cost estimate for budget pre-checks and UI hints. This is intentionally approximate and should
+ * not be treated as the authoritative charged amount.
+ */
+export interface ChatCostEstimate extends PricingComputationResult {
+ estimatedCost: number;
+ estimatedOutputTokens: number;
+ inputAudioTokens: number;
+ inputImageTokens: number;
+ inputTextTokens: number;
+ inputVideoTokens: number;
+ totalInputTokens: number;
+ usage: ModelTokensUsage;
+}
+
+export interface EstimateChatCostFromMessagesOptions
+ extends ComputeChatCostOptions, EstimateOpenAIChatInputTokensOptions {}
+
+const estimateSerializableTokens = (value: unknown): number => {
+ if (value === undefined || value === null) return 0;
+
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
+ return text ? estimateTokenCount(text) : 0;
+};
+
+const hasPricingUnit = (pricing: Pricing | undefined, unitName: PricingUnitName) =>
+ pricing?.units.some((unit) => unit.name === unitName) ?? false;
+
+/**
+ * Estimates output tokens for budget pre-checks and UI hints.
+ *
+ * The default heuristic assumes output is half of total input tokens, capped at 8192 tokens.
+ */
+export function estimateChatOutputTokens(totalInputTokens: number): number {
+ return Math.min(totalInputTokens * OUTPUT_INPUT_RATIO, OUTPUT_TOKEN_CAP);
+}
+
+/**
+ * Estimates OpenAI-compatible chat input tokens without requiring provider-side usage.
+ *
+ * This helper is for pre-flight checks only. It counts text-like fields, tool definitions, and a
+ * conservative per-image estimate; use provider usage plus `computeChatCost` for final billing.
+ */
+export function estimateOpenAIChatInputTokens(
+ messages: OpenAIChatMessage[],
+ options: EstimateOpenAIChatInputTokensOptions = {},
+): ChatInputTokenEstimate {
+ const imageTokenEstimate = options.imageTokenEstimate ?? DEFAULT_IMAGE_INPUT_TOKEN_ESTIMATE;
+ const videoTokenEstimate = options.videoTokenEstimate ?? DEFAULT_VIDEO_INPUT_TOKEN_ESTIMATE;
+ let textTokens = 0;
+ let imageTokens = 0;
+ let videoTokens = 0;
+
+ for (const message of messages) {
+ textTokens += estimateSerializableTokens(message.role);
+ textTokens += estimateSerializableTokens(message.name);
+ textTokens += estimateSerializableTokens(message.tool_call_id);
+ textTokens += estimateSerializableTokens(message.tool_calls);
+ textTokens += estimateSerializableTokens(message.reasoning?.content);
+
+ if (typeof message.content === 'string') {
+ textTokens += estimateSerializableTokens(message.content);
+ continue;
+ }
+
+ if (!Array.isArray(message.content)) {
+ textTokens += estimateSerializableTokens(message.content);
+ continue;
+ }
+
+ for (const part of message.content) {
+ if (part.type === 'text') {
+ textTokens += estimateSerializableTokens(part.text);
+ continue;
+ }
+
+ if (part.type === 'image_url') {
+ imageTokens += imageTokenEstimate;
+ continue;
+ }
+
+ if (part.type === 'video_url') {
+ videoTokens += videoTokenEstimate;
+ continue;
+ }
+
+ textTokens += estimateSerializableTokens(part);
+ }
+ }
+
+ textTokens += estimateSerializableTokens(options.tools);
+
+ return {
+ imageTokens,
+ textTokens,
+ totalTokens: textTokens + imageTokens + videoTokens,
+ videoTokens,
+ };
+}
+
+/**
+ * Estimates chat cost from known input token buckets.
+ *
+ * `outputTextTokens` defaults to `estimateChatOutputTokens(totalInputTokens)`. Pricing lookup
+ * options are forwarded to `computeChatCost`.
+ */
+export function estimateChatCostFromTokens(
+ pricing: Pricing | undefined,
+ input: EstimateChatCostFromTokensInput,
+ options?: ComputeChatCostOptions,
+): ChatCostEstimate | undefined {
+ const inputAudioTokens = input.audioTokens ?? 0;
+ const inputImageTokens = input.imageTokens ?? 0;
+ const inputTextTokens = input.textTokens;
+ const inputVideoTokens = input.videoTokens ?? 0;
+ const totalInputTokens = inputTextTokens + inputImageTokens + inputAudioTokens + inputVideoTokens;
+ const estimatedOutputTokens =
+ input.outputTextTokens ?? estimateChatOutputTokens(totalInputTokens);
+ const hasAudioInputUnit = hasPricingUnit(pricing, 'audioInput');
+ const hasImageInputUnit = hasPricingUnit(pricing, 'imageInput');
+ const hasVideoInputUnit = hasPricingUnit(pricing, 'videoInput');
+ // Some model cards price multimodal inputs through text input unless a dedicated unit exists.
+ const billableTextTokens =
+ inputTextTokens +
+ (hasAudioInputUnit ? 0 : inputAudioTokens) +
+ (hasImageInputUnit ? 0 : inputImageTokens) +
+ (hasVideoInputUnit ? 0 : inputVideoTokens);
+
+ const usage: ModelTokensUsage = {
+ inputAudioTokens: hasAudioInputUnit ? inputAudioTokens : undefined,
+ inputImageTokens: hasImageInputUnit ? inputImageTokens : undefined,
+ inputTextTokens: billableTextTokens,
+ inputVideoTokens: hasVideoInputUnit ? inputVideoTokens : undefined,
+ outputTextTokens: estimatedOutputTokens,
+ totalInputTokens,
+ totalOutputTokens: estimatedOutputTokens,
+ totalTokens: totalInputTokens + estimatedOutputTokens,
+ };
+
+ const result = computeChatCost(pricing, usage, options);
+ if (!result) return;
+
+ return {
+ ...result,
+ estimatedCost: result.totalCost,
+ estimatedOutputTokens,
+ inputAudioTokens,
+ inputImageTokens,
+ inputTextTokens,
+ inputVideoTokens,
+ totalInputTokens,
+ usage,
+ };
+}
+
+/**
+ * Estimates chat cost directly from OpenAI-compatible messages and optional tool definitions.
+ *
+ * This is intended for budget pre-checks and UI hints before the model call. Final charged cost
+ * should still be computed from actual provider usage with `computeChatCost`.
+ */
+export function estimateChatCostFromMessages(
+ pricing: Pricing | undefined,
+ messages: OpenAIChatMessage[],
+ options: EstimateChatCostFromMessagesOptions = {},
+): ChatCostEstimate | undefined {
+ const { tools, imageTokenEstimate, lookupParams, usdToCnyRate, videoTokenEstimate } = options;
+ const inputTokens = estimateOpenAIChatInputTokens(messages, {
+ imageTokenEstimate,
+ tools,
+ videoTokenEstimate,
+ });
+
+ return estimateChatCostFromTokens(
+ pricing,
+ {
+ imageTokens: inputTokens.imageTokens,
+ textTokens: inputTokens.textTokens,
+ videoTokens: inputTokens.videoTokens,
+ },
+ { lookupParams, usdToCnyRate },
+ );
+}
diff --git a/packages/model-runtime/src/core/usageConverters/utils/index.ts b/packages/model-runtime/src/core/usageConverters/utils/index.ts
index 4c39a682284..62f3ca03d69 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/index.ts
@@ -13,4 +13,15 @@ export {
type VideoCostResult,
type VideoGenerationParams,
} from './computeVideoCost';
+export {
+ type ChatCostEstimate,
+ type ChatInputTokenEstimate,
+ estimateChatCostFromMessages,
+ type EstimateChatCostFromMessagesOptions,
+ estimateChatCostFromTokens,
+ type EstimateChatCostFromTokensInput,
+ estimateChatOutputTokens,
+ estimateOpenAIChatInputTokens,
+ type EstimateOpenAIChatInputTokensOptions,
+} from './estimateChatCost';
export { withUsageCost } from './withUsageCost';
diff --git a/packages/types/src/user/settings/general.ts b/packages/types/src/user/settings/general.ts
index a18acbad330..6352ee10816 100644
--- a/packages/types/src/user/settings/general.ts
+++ b/packages/types/src/user/settings/general.ts
@@ -9,6 +9,7 @@ export type ContextMenuMode = 'disabled' | 'default';
export interface UserGeneralConfig {
animationMode?: AnimationMode;
contextMenuMode?: ContextMenuMode;
+ costEstimateWarningThreshold?: number;
/**
* Whether to auto-scroll during AI streaming output
* @default true
diff --git a/packages/utils/src/format.test.ts b/packages/utils/src/format.test.ts
index 3f27bf6f007..031056033ef 100644
--- a/packages/utils/src/format.test.ts
+++ b/packages/utils/src/format.test.ts
@@ -13,6 +13,7 @@ import {
formatSpeed,
formatTime,
formatTokenNumber,
+ formatUsageValue,
} from './format';
describe('format', () => {
@@ -254,6 +255,31 @@ describe('format', () => {
});
});
+ describe('formatUsageValue', () => {
+ it('formats token usage details with short units', () => {
+ expect(formatUsageValue(93_405)).toBe('93.4K');
+ expect(formatUsageValue(92_119)).toBe('92.1K');
+ expect(formatUsageValue(3_488)).toBe('3.5K');
+ expect(formatUsageValue(189_018)).toBe('189K');
+ });
+
+ it('formats credit usage details with the same short units', () => {
+ expect(formatUsageValue(16_127)).toBe('16.1K');
+ expect(formatUsageValue(16_179)).toBe('16.2K');
+ });
+
+ it('keeps small token counts readable without suffixes', () => {
+ expect(formatUsageValue(0)).toBe('0');
+ expect(formatUsageValue(6)).toBe('6');
+ expect(formatUsageValue(999)).toBe('999');
+ });
+
+ it('formats million-level token counts with M suffix', () => {
+ expect(formatUsageValue(1_000_000)).toBe('1M');
+ expect(formatUsageValue(1_500_000)).toBe('1.5M');
+ });
+ });
+
describe('formatDate', () => {
it('should format date correctly', () => {
const date = new Date('2023-05-15T12:00:00Z');
diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts
index d30ffae7463..c0dd9846553 100644
--- a/packages/utils/src/format.ts
+++ b/packages/utils/src/format.ts
@@ -77,6 +77,12 @@ export const formatIntergerNumber = (num?: any) => {
return numeral(num).format('0,0');
};
+export const formatUsageValue = (number: number) => {
+ if (number >= 1_000_000) return `${numeral(number / 1_000_000).format('0.[0]')}M`;
+ if (number >= 1_000) return `${numeral(number / 1_000).format('0.[0]')}K`;
+ return numeral(number).format('0,0');
+};
+
export const formatTokenNumber = (num: number): string => {
if (!num && num !== 0) return '--';
diff --git a/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
new file mode 100644
index 00000000000..97fb8f4c678
--- /dev/null
+++ b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
@@ -0,0 +1,4 @@
+import type { ReactNode } from 'react';
+
+export const useBusinessChatInputSendAreaPrefix = (sendAreaPrefix?: ReactNode): ReactNode =>
+ sendAreaPrefix;
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 642fb11b1e8..bac70258f07 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -8,6 +8,7 @@ import { type ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { useBusinessChatInputSendAreaPrefix } from '@/business/client/hooks/useBusinessChatInputSendAreaPrefix';
import type { ActionKeys, ChatInputFeature } from '@/features/ChatInput';
import { ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
import {
@@ -229,6 +230,7 @@ const ChatInput = memo<ChatInputProps>(
// When disableQueue is set (e.g. onboarding), block sending while loading.
const disabled = isInputEmpty || isUploadingFiles || (!!disableQueue && isInputLoading);
const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
+ const businessSendAreaPrefix = useBusinessChatInputSendAreaPrefix(sendAreaPrefix);
// Send handler - gets message, clears editor immediately, then sends
const handleSend: SendButtonHandler = useCallback(
@@ -322,7 +324,7 @@ const ChatInput = memo<ChatInputProps>(
leftContent={leftContent}
placeholderVariant={placeholderVariant}
runtimeConfigSlot={runtimeConfigSlot}
- sendAreaPrefix={sendAreaPrefix}
+ sendAreaPrefix={businessSendAreaPrefix}
showRuntimeConfig={showRuntimeConfig}
/>
</>
diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.test.ts b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.test.ts
deleted file mode 100644
index 4bed73159b3..00000000000
--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { formatUsageValue } from './TokenProgress';
-
-describe('formatUsageValue', () => {
- it('formats token usage details with short units', () => {
- expect(formatUsageValue(93_405)).toBe('93.4K');
- expect(formatUsageValue(92_119)).toBe('92.1K');
- expect(formatUsageValue(3_488)).toBe('3.5K');
- expect(formatUsageValue(189_018)).toBe('189K');
- });
-
- it('formats credit usage details with the same short units', () => {
- expect(formatUsageValue(16_127)).toBe('16.1K');
- expect(formatUsageValue(16_179)).toBe('16.2K');
- });
-
- it('keeps small token counts readable without suffixes', () => {
- expect(formatUsageValue(0)).toBe('0');
- expect(formatUsageValue(6)).toBe('6');
- expect(formatUsageValue(999)).toBe('999');
- });
-
- it('formats million-level token counts with M suffix', () => {
- expect(formatUsageValue(1_000_000)).toBe('1M');
- expect(formatUsageValue(1_500_000)).toBe('1.5M');
- });
-});
diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx
index c194175c785..ffcef8ae8e1 100644
--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx
+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx
@@ -1,6 +1,6 @@
+import { formatUsageValue } from '@lobechat/utils';
import { Flexbox } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import numeral from 'numeral';
import { memo } from 'react';
export interface TokenProgressItem {
@@ -15,12 +15,6 @@ interface TokenProgressProps {
showIcon?: boolean;
}
-export const formatUsageValue = (number: number) => {
- if (number >= 1_000_000) return numeral(number / 1_000_000).format('0.[0]') + 'M';
- if (number >= 1_000) return numeral(number / 1_000).format('0.[0]') + 'K';
- return numeral(number).format('0,0');
-};
-
const TokenProgress = memo<TokenProgressProps>(({ data, showIcon }) => {
const total = data.reduce((acc, item) => acc + item.value, 0);
diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
index 8173ad3912d..1ffd4298197 100644
--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
@@ -1,4 +1,5 @@
import { type ModelPerformance, type ModelUsage } from '@lobechat/types';
+import { formatUsageValue } from '@lobechat/utils';
import { Center, Flexbox, Icon, Popover } from '@lobehub/ui';
import { Divider } from 'antd';
import { cssVar } from 'antd-style';
@@ -15,7 +16,7 @@ import { formatNumber, formatShortenNumber } from '@/utils/format';
import AnimatedNumber from './AnimatedNumber';
import ModelCard from './ModelCard';
import type { TokenProgressItem } from './TokenProgress';
-import TokenProgress, { formatUsageValue } from './TokenProgress';
+import TokenProgress from './TokenProgress';
import { getDetailsToken } from './tokens';
interface TokenDetailProps {
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx
new file mode 100644
index 00000000000..ebbf9f40968
--- /dev/null
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx
@@ -0,0 +1,196 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+import ModelDetailPanel from './ModelDetailPanel';
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({
+ actionText: 'actionText',
+ container: 'container',
+ originalPriceText: 'originalPriceText',
+ priceValue: 'priceValue',
+ row: 'row',
+ titleText: 'titleText',
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Accordion: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ AccordionItem: ({
+ action,
+ children,
+ title,
+ }: {
+ action?: ReactNode;
+ children?: ReactNode;
+ title?: ReactNode;
+ }) => (
+ <section>
+ <div>{title}</div>
+ <div>{action}</div>
+ <div>{children}</div>
+ </section>
+ ),
+ Flexbox: ({ children, ...props }: { children?: ReactNode }) => <div {...props}>{children}</div>,
+ Icon: () => <span />,
+ Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ Tooltip: ({ children, title }: { children: ReactNode; title?: ReactNode }) => (
+ <span>
+ {title}
+ {children}
+ </span>
+ ),
+}));
+
+vi.mock('@/hooks/useEnabledChatModels', () => ({
+ useEnabledChatModels: () => [],
+}));
+
+const globalState = {
+ status: {
+ modelDetailPanelExpandedKeys: ['pricing'],
+ },
+ updateModelDetailPanelExpandedKeys: vi.fn(),
+};
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: typeof globalState) => unknown) => selector(globalState),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ modelDetailPanelExpandedKeys: (state: typeof globalState) =>
+ state.status.modelDetailPanelExpandedKeys,
+ },
+}));
+
+const translations: Record<string, string> = {
+ 'ModelSwitchPanel.detail.context': 'Context Length',
+ 'ModelSwitchPanel.detail.pricing': 'Pricing',
+ 'ModelSwitchPanel.detail.pricing.credits.input': 'Input {{amount}} credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.output': 'Output {{amount}} credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.perImage': '~ {{amount}} credits / image',
+ 'ModelSwitchPanel.detail.pricing.credits.perVideo': '~ {{amount}} credits / video',
+ 'ModelSwitchPanel.detail.pricing.credits.image': 'credits/img',
+ 'ModelSwitchPanel.detail.pricing.credits.millionTokens': 'credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.group.image': 'Image',
+ 'ModelSwitchPanel.detail.pricing.group.text': 'Text',
+ 'ModelSwitchPanel.detail.pricing.input': 'Input ${{amount}}/M',
+ 'ModelSwitchPanel.detail.pricing.output': 'Output ${{amount}}/M',
+ 'ModelSwitchPanel.detail.pricing.perImage': '~ ${{amount}} / image',
+ 'ModelSwitchPanel.detail.pricing.perVideo': '~ ${{amount}} / video',
+ 'ModelSwitchPanel.detail.pricing.unit.imageGeneration': 'Image Generation',
+ 'ModelSwitchPanel.detail.pricing.unit.textInput': 'Input',
+ 'ModelSwitchPanel.detail.pricing.unit.textOutput': 'Output',
+};
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, string>) => {
+ const template = translations[key] ?? options?.defaultValue ?? key;
+
+ return template.replaceAll(/\{\{(\w+)\}\}/g, (_, name) => options?.[name] ?? '');
+ },
+ }),
+}));
+
+const textPricing = {
+ currency: 'USD',
+ units: [
+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 25, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+};
+
+const imagePricing = {
+ approximatePricePerImage: 0.04,
+ approximatePricePerVideo: 0.8,
+ currency: 'USD',
+ units: [{ name: 'imageGeneration', rate: 0.04, strategy: 'fixed', unit: 'image' }],
+};
+
+const createEnabledList = (
+ provider: string,
+ pricing: Record<string, unknown>,
+): EnabledProviderWithModels[] => [
+ {
+ children: [
+ {
+ abilities: {},
+ contextWindowTokens: 1_000_000,
+ displayName: 'Test Model',
+ id: 'test-model',
+ pricing,
+ type: 'chat',
+ } as any,
+ ],
+ id: provider,
+ name: provider,
+ source: 'builtin',
+ },
+];
+
+describe('ModelDetailPanel pricing', () => {
+ it('renders branding provider token pricing in credits', () => {
+ const { container } = render(
+ <ModelDetailPanel
+ enabledList={createEnabledList('lobehub', textPricing)}
+ model="test-model"
+ provider="lobehub"
+ />,
+ );
+
+ expect(screen.getByText('5M credits/M tokens')).toBeInTheDocument();
+ expect(screen.getByText('25M credits/M tokens')).toBeInTheDocument();
+ expect(container).not.toHaveTextContent('$5.00');
+ });
+
+ it('keeps dollar pricing for non-branding providers', () => {
+ const { container } = render(
+ <ModelDetailPanel
+ enabledList={createEnabledList('openai', textPricing)}
+ model="test-model"
+ provider="openai"
+ />,
+ );
+
+ expect(container).toHaveTextContent('$5.00/M tokens');
+ expect(container).toHaveTextContent('$25.00/M tokens');
+ expect(container).not.toHaveTextContent('credits/M tokens');
+ });
+
+ it('renders branding provider image and video pricing in credits', () => {
+ const imageResult = render(
+ <ModelDetailPanel
+ enabledList={createEnabledList('lobehub', imagePricing)}
+ model="test-model"
+ pricingMode="image"
+ provider="lobehub"
+ />,
+ );
+
+ expect(imageResult.container).toHaveTextContent('~ 40.0K credits / image');
+ expect(imageResult.container).toHaveTextContent('40.0K credits/img');
+ expect(imageResult.container).not.toHaveTextContent('$0.04');
+
+ imageResult.unmount();
+
+ const videoResult = render(
+ <ModelDetailPanel
+ enabledList={createEnabledList('lobehub', imagePricing)}
+ model="test-model"
+ pricingMode="video"
+ provider="lobehub"
+ />,
+ );
+
+ expect(videoResult.container).toHaveTextContent('~ 800.0K credits / video');
+ expect(videoResult.container).not.toHaveTextContent('$0.80');
+ });
+});
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
index 20bf35c2fc6..9a7af5e054e 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
@@ -1,7 +1,8 @@
+import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { getCachedTextInputUnitRate } from '@lobechat/utils';
import { Accordion, AccordionItem, Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { type LucideIcon } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
import {
ArrowDownToDot,
ArrowUpFromDot,
@@ -14,15 +15,15 @@ import {
VideoIcon,
WrenchIcon,
} from 'lucide-react';
-import {
- type FixedPricingUnit,
- type ModelPriceCurrency,
- type Pricing,
- type PricingUnit,
- type PricingUnitName,
- type TieredPricingUnit,
+import type {
+ FixedPricingUnit,
+ ModelPriceCurrency,
+ Pricing,
+ PricingUnit,
+ PricingUnitName,
+ TieredPricingUnit,
} from 'model-bank';
-import { type FC } from 'react';
+import type { FC } from 'react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -31,7 +32,7 @@ import { useGlobalStore } from '@/store/global';
import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
import type { EnabledProviderWithModels } from '@/types/aiProvider';
-import { formatTokenNumber } from '@/utils/format';
+import { formatNumber, formatShortenNumber, formatTokenNumber } from '@/utils/format';
import {
formatPriceByCurrency,
getOriginalUnitRateByName,
@@ -75,10 +76,37 @@ interface FormattedUnitPrice {
original?: string;
}
-const formatPricingRate = (rate: number | undefined, currency?: ModelPriceCurrency) =>
- typeof rate === 'number' ? formatPriceByCurrency(rate, currency) : '0';
+const BRANDING_CREDIT_UNIT = 1_000_000;
+const MILLION_SCALE_UNITS = new Set<PricingUnit['unit']>(['millionCharacters', 'millionTokens']);
+
+interface FormatPricingRateOptions {
+ isCreditPricing?: boolean;
+ unit?: PricingUnit['unit'];
+}
+
+const formatBrandingCreditRate = (rate: number, unit?: PricingUnit['unit']) => {
+ if (unit && MILLION_SCALE_UNITS.has(unit)) return `${formatNumber(rate)}M`;
+
+ return String(formatShortenNumber(Math.round(rate * BRANDING_CREDIT_UNIT)));
+};
+
+const formatPricingRate = (
+ rate: number | undefined,
+ currency?: ModelPriceCurrency,
+ options: FormatPricingRateOptions = {},
+) => {
+ if (typeof rate !== 'number') return '0';
+
+ return options.isCreditPricing
+ ? formatBrandingCreditRate(rate, options.unit)
+ : formatPriceByCurrency(rate, currency);
+};
-const getFormattedUnitPrice = (pricing: Pricing, unitName: PricingUnitName): FormattedUnitPrice => {
+const getFormattedUnitPrice = (
+ pricing: Pricing,
+ unitName: PricingUnitName,
+ isCreditPricing: boolean,
+): FormattedUnitPrice => {
const currency = pricing.currency as ModelPriceCurrency | undefined;
const currentRate =
unitName === 'textInput'
@@ -89,17 +117,25 @@ const getFormattedUnitPrice = (pricing: Pricing, unitName: PricingUnitName): For
const originalRate = getOriginalUnitRateByName(pricing, unitName);
return {
- current: formatPricingRate(currentRate, currency),
+ current: formatPricingRate(currentRate, currency, {
+ isCreditPricing,
+ unit: 'millionTokens',
+ }),
original:
- typeof originalRate === 'number' ? formatPriceByCurrency(originalRate, currency) : undefined,
+ typeof originalRate === 'number'
+ ? formatPricingRate(originalRate, currency, {
+ isCreditPricing,
+ unit: 'millionTokens',
+ })
+ : undefined,
};
};
-const getPrice = (pricing: Pricing) => {
+const getPrice = (pricing: Pricing, isCreditPricing: boolean) => {
return {
- cachedInput: getFormattedUnitPrice(pricing, 'textInput_cacheRead'),
- input: getFormattedUnitPrice(pricing, 'textInput'),
- output: getFormattedUnitPrice(pricing, 'textOutput'),
+ cachedInput: getFormattedUnitPrice(pricing, 'textInput_cacheRead', isCreditPricing),
+ input: getFormattedUnitPrice(pricing, 'textInput', isCreditPricing),
+ output: getFormattedUnitPrice(pricing, 'textOutput', isCreditPricing),
};
};
@@ -186,14 +222,23 @@ const PriceValue: FC<PriceValueProps> = ({ price, prefix = '', suffix = '' }) =>
</span>
);
-const formatUnitRate = (unit: PricingUnit, currency?: ModelPriceCurrency): FormattedUnitPrice => {
+const formatUnitRate = (
+ unit: PricingUnit,
+ currency?: ModelPriceCurrency,
+ isCreditPricing?: boolean,
+): FormattedUnitPrice => {
+ const formatRate = (rate: number) =>
+ formatPricingRate(rate, currency, { isCreditPricing, unit: unit.unit });
+ const formatRange = (low: string, high: string) =>
+ isCreditPricing ? `${low} ~ ${high}` : `${low} ~ $${high}`;
+
if (unit.strategy === 'fixed') {
const fixedUnit = unit as FixedPricingUnit;
return {
- current: formatPriceByCurrency(fixedUnit.rate, currency),
+ current: formatRate(fixedUnit.rate),
original:
typeof fixedUnit.originalRate === 'number' && fixedUnit.originalRate > fixedUnit.rate
- ? formatPriceByCurrency(fixedUnit.originalRate, currency)
+ ? formatRate(fixedUnit.originalRate)
: undefined,
};
}
@@ -201,25 +246,25 @@ const formatUnitRate = (unit: PricingUnit, currency?: ModelPriceCurrency): Forma
if (unit.strategy === 'tiered') {
const tiers = (unit as TieredPricingUnit).tiers;
if (tiers.length === 1) {
- const price = formatPriceByCurrency(tiers[0].rate, currency);
+ const price = formatRate(tiers[0].rate);
return { current: price };
}
- const low = formatPriceByCurrency(tiers[0].rate, currency);
- const high = formatPriceByCurrency(tiers.at(-1)!.rate, currency);
- return { current: `${low} ~ $${high}` };
+ const low = formatRate(tiers[0].rate);
+ const high = formatRate(tiers.at(-1)!.rate);
+ return { current: formatRange(low, high) };
}
// lookup strategy
if (unit.strategy === 'lookup') {
const prices = Object.values(unit.lookup.prices);
if (prices.length === 1) {
- const price = formatPriceByCurrency(prices[0], currency);
+ const price = formatRate(prices[0]);
return { current: price };
}
const sorted = [...prices].sort((a, b) => a - b);
- const low = formatPriceByCurrency(sorted[0], currency);
- const high = formatPriceByCurrency(sorted.at(-1)!, currency);
- return { current: `${low} ~ $${high}` };
+ const low = formatRate(sorted[0]);
+ const high = formatRate(sorted.at(-1)!);
+ return { current: formatRange(low, high) };
}
return { current: '-' };
@@ -285,8 +330,9 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
const updateExpandedKeys = useGlobalStore((s) => s.updateModelDetailPanelExpandedKeys);
const pricing = model?.pricing;
+ const isCreditPricing = provider === BRANDING_PROVIDER;
const hasPricing = !!pricing;
- const formatPrice = pricing ? getPrice(pricing) : null;
+ const formatPrice = pricing ? getPrice(pricing, isCreditPricing) : null;
const pricingGroups = useMemo(
() => (pricing ? groupPricingUnits(pricing.units) : []),
[pricing],
@@ -296,21 +342,57 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
if (!pricing || !pricingMode) return null;
const currency = pricing.currency as ModelPriceCurrency | undefined;
if (pricingMode === 'image' && typeof pricing.approximatePricePerImage === 'number') {
- const amount = formatPriceByCurrency(pricing.approximatePricePerImage, currency);
- return t('ModelSwitchPanel.detail.pricing.perImage', {
- amount,
- defaultValue: '~ ${{amount}} / image',
- });
+ const amount = isCreditPricing
+ ? formatBrandingCreditRate(pricing.approximatePricePerImage, 'image')
+ : formatPriceByCurrency(pricing.approximatePricePerImage, currency);
+ return t(
+ isCreditPricing
+ ? 'ModelSwitchPanel.detail.pricing.credits.perImage'
+ : 'ModelSwitchPanel.detail.pricing.perImage',
+ {
+ amount,
+ defaultValue: isCreditPricing
+ ? '~ {{amount}} credits / image'
+ : '~ ${{amount}} / image',
+ },
+ );
}
if (pricingMode === 'video' && typeof pricing.approximatePricePerVideo === 'number') {
- const amount = formatPriceByCurrency(pricing.approximatePricePerVideo, currency);
- return t('ModelSwitchPanel.detail.pricing.perVideo', {
- amount,
- defaultValue: '~ ${{amount}} / video',
- });
+ const amount = isCreditPricing
+ ? formatBrandingCreditRate(pricing.approximatePricePerVideo)
+ : formatPriceByCurrency(pricing.approximatePricePerVideo, currency);
+ return t(
+ isCreditPricing
+ ? 'ModelSwitchPanel.detail.pricing.credits.perVideo'
+ : 'ModelSwitchPanel.detail.pricing.perVideo',
+ {
+ amount,
+ defaultValue: isCreditPricing
+ ? '~ {{amount}} credits / video'
+ : '~ ${{amount}} / video',
+ },
+ );
}
return null;
- }, [pricing, pricingMode, t]);
+ }, [isCreditPricing, pricing, pricingMode, t]);
+
+ const getCreditsUnitLabel = (unit: PricingUnit['unit']) =>
+ t(`ModelSwitchPanel.detail.pricing.credits.${unit}` as any, {
+ defaultValue: `credits${UNIT_LABEL_MAP[unit] || ''}`,
+ });
+
+ const getPricingTooltip = (key: 'cachedInput' | 'input' | 'output', amount: string): string => {
+ if (isCreditPricing) {
+ return t(`ModelSwitchPanel.detail.pricing.credits.${key}` as any, { amount });
+ }
+
+ const fallbackKey =
+ key === 'cachedInput'
+ ? 'ModelSwitchPanel.detail.pricing.cachedInput'
+ : `ModelSwitchPanel.detail.pricing.${key}`;
+
+ return t(fallbackKey as any, { amount });
+ };
if (!model) return null;
@@ -440,9 +522,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
<Flexbox horizontal align={'center'} className={styles.actionText} gap={8}>
{getCachedTextInputUnitRate(model.pricing!) && (
<Tooltip
- title={t('ModelSwitchPanel.detail.pricing.cachedInput', {
- amount: formatPrice!.cachedInput.current,
- })}
+ title={getPricingTooltip('cachedInput', formatPrice!.cachedInput.current)}
>
<Flexbox horizontal align={'center'} gap={2}>
<Icon icon={CircleFadingArrowUp} size={'small'} />
@@ -450,21 +530,13 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
</Flexbox>
</Tooltip>
)}
- <Tooltip
- title={t('ModelSwitchPanel.detail.pricing.input', {
- amount: formatPrice!.input.current,
- })}
- >
+ <Tooltip title={getPricingTooltip('input', formatPrice!.input.current)}>
<Flexbox horizontal align={'center'} gap={2}>
<Icon icon={ArrowUpFromDot} size={'small'} />
<PriceValue price={formatPrice!.input} />
</Flexbox>
</Tooltip>
- <Tooltip
- title={t('ModelSwitchPanel.detail.pricing.output', {
- amount: formatPrice!.output.current,
- })}
- >
+ <Tooltip title={getPricingTooltip('output', formatPrice!.output.current)}>
<Flexbox horizontal align={'center'} gap={2}>
<Icon icon={ArrowDownToDot} size={'small'} />
<PriceValue price={formatPrice!.output} />
@@ -518,12 +590,17 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
</span>
</Flexbox>
<PriceValue
- prefix="$"
- suffix={UNIT_LABEL_MAP[unit.unit] || ''}
+ prefix={isCreditPricing ? '' : '$'}
price={formatUnitRate(
unit,
model.pricing?.currency as ModelPriceCurrency,
+ isCreditPricing,
)}
+ suffix={
+ isCreditPricing
+ ? ` ${getCreditsUnitLabel(unit.unit)}`
+ : UNIT_LABEL_MAP[unit.unit] || ''
+ }
/>
</Flexbox>
))}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index a19ac69d27b..6c8efcc2963 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -185,6 +185,14 @@ export default {
'inbox.title': 'Lobe AI',
'input.addAi': 'Add an AI message',
'input.addUser': 'Add a user message',
+ 'input.costEstimate.creditsPerMillionTokens': '{{credits}} credits/M tokens',
+ 'input.costEstimate.hint': 'Estimated cost: ~{{credits}} credits',
+ 'input.costEstimate.inputLabel': 'Input',
+ 'input.costEstimate.outputLabel': 'Output',
+ 'input.costEstimate.settingsLink': 'Adjust warning threshold',
+ 'input.costEstimate.tokenCount': '~{{tokens}} tokens',
+ 'input.costEstimate.tooltip':
+ 'Estimated from current context, tools, and model pricing. Actual cost may vary.',
'input.disclaimer': 'Agents can make mistakes. Use your judgment for critical info.',
'input.errorMsg': 'Send failed: {{errorMsg}}. Retry, or send again later.',
'input.more': 'More',
diff --git a/src/locales/default/common.ts b/src/locales/default/common.ts
index d477222df5c..54a3733d3bd 100644
--- a/src/locales/default/common.ts
+++ b/src/locales/default/common.ts
@@ -3,9 +3,9 @@ export default {
'advanceSettings': 'Advanced Settings',
'alert.cloud.action': 'Try now',
'alert.cloud.desc':
- 'All registered users get {{credit}} free computing credits per month—no setup needed. Includes global cloud sync and advanced web search.',
+ 'All registered users get {{credit}} free credits per month—no setup needed. Includes global cloud sync and advanced web search.',
'alert.cloud.descOnMobile':
- 'All registered users get {{credit}} free computing credits per month—no setup needed.',
+ 'All registered users get {{credit}} free credits per month—no setup needed.',
'alert.cloud.title': '{{name}} beta is live',
'agentOnboardingPromo.actionLabel': 'Try it now',
'agentOnboardingPromo.description':
diff --git a/src/locales/default/components.ts b/src/locales/default/components.ts
index f07d3e834cb..40666d210ee 100644
--- a/src/locales/default/components.ts
+++ b/src/locales/default/components.ts
@@ -140,6 +140,16 @@ export default {
'ModelSwitchPanel.detail.context': 'Context Length',
'ModelSwitchPanel.detail.pricing': 'Pricing',
'ModelSwitchPanel.detail.pricing.cachedInput': 'Cached input ${{amount}}/M',
+ 'ModelSwitchPanel.detail.pricing.credits.cachedInput': 'Cached input {{amount}} credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.input': 'Input {{amount}} credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.output': 'Output {{amount}} credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.perImage': '~ {{amount}} credits / image',
+ 'ModelSwitchPanel.detail.pricing.credits.perVideo': '~ {{amount}} credits / video',
+ 'ModelSwitchPanel.detail.pricing.credits.image': 'credits/img',
+ 'ModelSwitchPanel.detail.pricing.credits.megapixel': 'credits/MP',
+ 'ModelSwitchPanel.detail.pricing.credits.millionCharacters': 'credits/M chars',
+ 'ModelSwitchPanel.detail.pricing.credits.millionTokens': 'credits/M tokens',
+ 'ModelSwitchPanel.detail.pricing.credits.second': 'credits/s',
'ModelSwitchPanel.detail.pricing.group.audio': 'Audio',
'ModelSwitchPanel.detail.pricing.group.image': 'Image',
'ModelSwitchPanel.detail.pricing.group.text': 'Text',
diff --git a/src/locales/default/spend.ts b/src/locales/default/spend.ts
index 18923615c1d..0d2a5fd2cc0 100644
--- a/src/locales/default/spend.ts
+++ b/src/locales/default/spend.ts
@@ -35,10 +35,9 @@ export default {
'table.columns.type.enums.imageGeneration': 'Image Generation',
'table.columns.type.enums.videoGeneration': 'Video Generation',
'table.columns.type.title': 'Type',
- 'table.desc':
- 'Details of computing credits usage for text generation, embedding, image generation, etc.',
+ 'table.desc': 'Details of credit usage for text generation, embedding, image generation, etc.',
'table.more': 'View Details',
- 'table.title': 'Computing Credits Usage Details',
+ 'table.title': 'Credit Usage Details',
'table.totalToken.input': 'Input',
'table.totalToken.output': 'Output',
};
diff --git a/src/locales/default/subscription.ts b/src/locales/default/subscription.ts
index ef23429bbd2..19488cd4d63 100644
--- a/src/locales/default/subscription.ts
+++ b/src/locales/default/subscription.ts
@@ -38,8 +38,8 @@ export default {
'cancelPlan.title': 'Cancel Subscription',
'cancelSubscription': 'Cancel Subscription',
'compare.hobbyCreditTooltip':
- 'Does not include monthly computing credits, you need to configure your own model API',
- 'compare.monthlyCredit': 'Monthly Computing Credits',
+ 'Does not include monthly credits, you need to configure your own model API',
+ 'compare.monthlyCredit': 'Monthly Credits',
'compare.title': 'Plan Comparison',
'compareAllPlans': 'View All Plans',
'comparePlans': 'View Plans',
@@ -87,6 +87,13 @@ export default {
'credits.autoTopUp.upgradeHint': 'Subscribe to a paid plan to enable auto top-up',
'credits.autoTopUp.validation.targetMustExceedThreshold':
'Target balance must be greater than threshold',
+ 'credits.costEstimateHint.desc':
+ 'Show a lightweight warning before sending when the estimated model cost reaches your threshold',
+ 'credits.costEstimateHint.saveError': 'Failed to save cost estimate alert settings',
+ 'credits.costEstimateHint.saveSuccess': 'Cost estimate alert settings saved',
+ 'credits.costEstimateHint.threshold': 'Warning Threshold',
+ 'credits.costEstimateHint.title': 'Cost Estimate Alert',
+ 'credits.costEstimateHint.validation.threshold': 'Threshold must be greater than or equal to 0',
'credits.packages.expired': 'Expired',
'credits.packages.expiresIn': 'Expires in {{days}} days',
'credits.packages.expiresToday': 'Expires today',
@@ -150,8 +157,8 @@ export default {
'Your top-up credits are now active. Enjoy AI chatting. Your current plan includes:',
'limitation.chat.topupSuccess.title': 'Top-up Successful',
'limitation.expired.desc':
- 'Your {{plan}} computing credits expired on {{expiredAt}}. Upgrade your plan now to get computing credits.',
- 'limitation.expired.title': 'Computing Credits Expired',
+ 'Your {{plan}} credits expired on {{expiredAt}}. Upgrade your plan now to get credits.',
+ 'limitation.expired.title': 'Credits Expired',
'limitation.insufficientBudget.approximateDesc':
'This request may need more credits. Top up credits or upgrade your plan.',
'limitation.insufficientBudget.available': 'Available Credits',
@@ -168,7 +175,7 @@ export default {
'limitation.hobby.action': 'Configured, continue chatting',
'limitation.hobby.configAPI': 'Configure API',
'limitation.hobby.desc':
- 'Your free computing credits have been exhausted. Please configure a custom model API to continue.',
+ 'Your free credits have been exhausted. Please configure a custom model API to continue.',
'limitation.hobby.docs': 'View configuration docs',
'limitation.hobby.tip': 'Remember to switch to a model with custom API Key',
'limitation.hobby.title': 'Please Configure Model Service API',
@@ -197,11 +204,11 @@ export default {
'limitation.limited.action': 'Upgrade Now',
'limitation.limited.advanceFeature': 'Upgrade to enjoy premium features:',
'limitation.limited.desc':
- 'Your {{plan}} computing credits have been exhausted. Upgrade now to get more credits.',
+ 'Your {{plan}} credits have been exhausted. Upgrade now to get more credits.',
'limitation.limited.descUltimate':
- 'Your {{plan}} computing credits have been exhausted. Please top up credits to continue.',
+ 'Your {{plan}} credits have been exhausted. Please top up credits to continue.',
'limitation.limited.referralTip': 'Invite friends, both get {{reward}}M',
- 'limitation.limited.title': 'Computing Credits Exhausted',
+ 'limitation.limited.title': 'Credits Exhausted',
'limitation.limited.topup': 'Top-Up Credits',
'limitation.limited.upgrade': 'Upgrade to Higher Plan',
'limitation.limited.upgradeToPlan': 'Upgrade to {{plan}}',
@@ -219,7 +226,7 @@ export default {
'limitation.providers.tooltip': 'Custom API service is only available for paid plans',
'modelPricing.button': 'View Pricing Documentation',
'modelPricing.desc':
- '{{name}} uses Credits to measure AI model usage. The table below shows computing credits per 1M Tokens.',
+ '{{name}} uses Credits to measure AI model usage. The table below shows credits per 1M Tokens.',
'modelPricing.title': 'Text Model Pricing',
'models.input': 'Input',
'models.intro': 'Introduction',
@@ -265,12 +272,12 @@ export default {
'plans.credit.apiDesc': 'Requires your own model API configuration',
'plans.credit.apiProvider':
'Supports 20+ mainstream model providers including OpenAI / Anthropic / OpenRouter',
- 'plans.credit.buy': 'Purchase Computing Credits',
- 'plans.credit.buyDesc': 'Also supports purchasing computing credits on demand',
- 'plans.credit.none': 'No built-in computing credits',
+ 'plans.credit.buy': 'Purchase Credits',
+ 'plans.credit.buyDesc': 'Also supports purchasing credits on demand',
+ 'plans.credit.none': 'No built-in credits',
'plans.credit.tip': '{{credit}} free credits per month',
- 'plans.credit.title': 'Computing Credits',
- 'plans.credit.tooltip': 'Monthly model message computing credits',
+ 'plans.credit.title': 'Credits',
+ 'plans.credit.tooltip': 'Monthly model message credits',
'plans.current': 'Current Plan',
'plans.downgradePlan': 'Target Downgrade Plan',
'plans.downgradeTip':
@@ -351,17 +358,17 @@ export default {
'If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.',
'qa.detail': 'View Details',
'qa.list.credit.a':
- 'Computing credits are a metric used by {{cloud}} to measure AI model usage when calling models. Different AI models consume different amounts of computing credits.',
- 'qa.list.credit.q': 'What are computing credits?',
+ 'Credits are how {{cloud}} measures AI model usage. Different AI models consume different amounts of credits.',
+ 'qa.list.credit.q': 'What are credits?',
'qa.list.embeddings.a':
'Vector storage is not equal to the original size of your uploaded or imported dataset, but is calculated based on the vectorization of pure text content in your files. For example, a 1-page PDF file (1000-1500 characters) may only take up about 1 vector storage entry when extracted and vectorized into pure text. You can view your usage under "{{usage}}".',
'qa.list.embeddings.q': 'How is vector storage calculated?',
'qa.list.free.a':
- '{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free computing credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.',
+ '{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.',
'qa.list.free.q': 'Can {{name}} be used for free?',
'qa.list.limit.a':
- '{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different computing credits. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>"{{funds}}"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.',
- 'qa.list.limit.q': 'What if I run out of computing credits?',
+ '{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different credit amounts. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>"{{funds}}"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.',
+ 'qa.list.limit.q': 'What if I run out of credits?',
'qa.list.highUsage.a':
'Credit consumption depends heavily on conversation length. As a conversation grows, each new message sends the entire history as input tokens, which increases cost significantly. We recommend starting a new conversation when topics change. Also, if there is a long gap between messages, the prompt cache may expire, causing a spike in cost. Some models like the Gemini Pro series use tiered pricing — input beyond 200K tokens is charged at double the rate.',
'qa.list.highUsage.q': 'Why are my credits being consumed faster than expected?',
@@ -493,7 +500,7 @@ export default {
'usage.credit.time.days': '{{days}} days',
'usage.credit.time.daysAndHours': '{{days}} days {{hours}} hours',
'usage.credit.time.hours': '{{hours}} hours',
- 'usage.credit.title': 'Computing Credits Usage',
+ 'usage.credit.title': 'Credit Usage',
'usage.overview.charge': 'Charges',
'usage.overview.included': 'Plan Usage',
'usage.overview.onDemand': 'On-demand',
diff --git a/src/store/user/selectors.ts b/src/store/user/selectors.ts
index 4ac0f042a23..a3342d28923 100644
--- a/src/store/user/selectors.ts
+++ b/src/store/user/selectors.ts
@@ -8,4 +8,5 @@ export {
systemAgentSelectors,
toolInterventionSelectors,
userGeneralSettingsSelectors,
+ userUsageSettingsSelectors,
} from './slices/settings/selectors';
diff --git a/src/store/user/slices/settings/selectors/general.test.ts b/src/store/user/slices/settings/selectors/general.test.ts
index bfc77e38224..82ec9e3137e 100644
--- a/src/store/user/slices/settings/selectors/general.test.ts
+++ b/src/store/user/slices/settings/selectors/general.test.ts
@@ -18,6 +18,7 @@ describe('settingsSelectors', () => {
expect(result).toEqual({
animationMode: 'agile',
+ costEstimateWarningThreshold: 2,
fontSize: 12,
highlighterTheme: 'lobe-theme',
isDevMode: false,
diff --git a/src/store/user/slices/settings/selectors/index.ts b/src/store/user/slices/settings/selectors/index.ts
index fb0e6e474c1..2f85a1c90be 100644
--- a/src/store/user/slices/settings/selectors/index.ts
+++ b/src/store/user/slices/settings/selectors/index.ts
@@ -3,3 +3,4 @@ export { keyVaultsConfigSelectors } from './keyVaults';
export { settingsSelectors } from './settings';
export { systemAgentSelectors } from './systemAgent';
export { type ApprovalMode, toolInterventionSelectors } from './toolIntervention';
+export { userUsageSettingsSelectors } from './usage';
diff --git a/src/store/user/slices/settings/selectors/usage.test.ts b/src/store/user/slices/settings/selectors/usage.test.ts
new file mode 100644
index 00000000000..476ee7ee9f4
--- /dev/null
+++ b/src/store/user/slices/settings/selectors/usage.test.ts
@@ -0,0 +1,30 @@
+import type { UserStore } from '@/store/user';
+import type { UserState } from '@/store/user/initialState';
+import { initialState } from '@/store/user/initialState';
+import { merge } from '@/utils/merge';
+
+import { userUsageSettingsSelectors } from './usage';
+
+describe('userUsageSettingsSelectors', () => {
+ describe('costEstimateWarningThreshold', () => {
+ it('should return the default threshold', () => {
+ const result = userUsageSettingsSelectors.costEstimateWarningThreshold(
+ initialState as UserStore,
+ );
+
+ expect(result).toBe(2);
+ });
+
+ it('should read the persisted threshold from general settings', () => {
+ const s: UserState = merge(initialState, {
+ settings: {
+ general: { costEstimateWarningThreshold: 0.5 },
+ },
+ });
+
+ const result = userUsageSettingsSelectors.costEstimateWarningThreshold(s as UserStore);
+
+ expect(result).toBe(0.5);
+ });
+ });
+});
diff --git a/src/store/user/slices/settings/selectors/usage.ts b/src/store/user/slices/settings/selectors/usage.ts
new file mode 100644
index 00000000000..6ca831d1a77
--- /dev/null
+++ b/src/store/user/slices/settings/selectors/usage.ts
@@ -0,0 +1,12 @@
+import { DEFAULT_COST_ESTIMATE_WARNING_THRESHOLD } from '@lobechat/const';
+
+import type { UserStore } from '../../../store';
+import { currentSettings } from './settings';
+
+const costEstimateWarningThreshold = (s: UserStore) =>
+ currentSettings(s).general.costEstimateWarningThreshold ??
+ DEFAULT_COST_ESTIMATE_WARNING_THRESHOLD;
+
+export const userUsageSettingsSelectors = {
+ costEstimateWarningThreshold,
+};