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(agent): add per-agent token / usage / cost stats page (#16319)

Arvin Xu93f93f62ee87
diff --git a/apps/server/src/routers/lambda/usage.ts b/apps/server/src/routers/lambda/usage.ts
index 96c53e7caed..41f2a60a344 100644
--- a/apps/server/src/routers/lambda/usage.ts
+++ b/apps/server/src/routers/lambda/usage.ts
@@ -19,6 +19,24 @@ const usageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
});
export const usageRouter = router({
+ getAgentUsageStats: usageProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ endAt: z.string(),
+ granularity: z.enum(['day', 'week']).default('day'),
+ startAt: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ return await ctx.usageRecordService.getAgentUsageStats(
+ input.agentId,
+ input.startAt,
+ input.endAt,
+ input.granularity,
+ );
+ }),
+
findAndGroupByDateRange: usageProcedure
.input(
z.object({
diff --git a/apps/server/src/services/usage/cost.test.ts b/apps/server/src/services/usage/cost.test.ts
new file mode 100644
index 00000000000..892c91c9c0e
--- /dev/null
+++ b/apps/server/src/services/usage/cost.test.ts
@@ -0,0 +1,74 @@
+import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import { type ModelUsage } from '@/types/message';
+
+import { computeMessageCostSplit } from './cost';
+
+// Pick any builtin model that has cache-read pricing so the savings math is exercised.
+const priced = LOBE_DEFAULT_MODEL_LIST.find(
+ (m) =>
+ m.pricing?.units?.some((u: any) => u.name === 'textInput') &&
+ m.pricing?.units?.some((u: any) => u.name === 'textInput_cacheRead'),
+)!;
+
+describe('computeMessageCostSplit', () => {
+ it('attributes the whole billed cost to input when pricing is unknown', () => {
+ const usage: ModelUsage = { totalInputTokens: 100, totalOutputTokens: 50, totalTokens: 150 };
+ const split = computeMessageCostSplit(usage, 'no-such-provider', 'no-such-model', 0.42);
+
+ expect(split.totalCost).toBe(0.42);
+ expect(split.inputCost).toBe(0.42);
+ expect(split.outputCost).toBe(0);
+ expect(split.cacheWriteCost).toBe(0);
+ expect(split.cacheSavings).toBe(0);
+ });
+
+ it('reconciles the cost split to the authoritative billed cost', () => {
+ const usage: ModelUsage = {
+ cost: 1.5,
+ inputCacheMissTokens: 1000,
+ inputCachedTokens: 4000,
+ inputWriteCacheTokens: 500,
+ totalInputTokens: 5000,
+ totalOutputTokens: 800,
+ totalTokens: 5800,
+ };
+ const split = computeMessageCostSplit(usage, priced.providerId, priced.id, 1.5);
+
+ expect(split.totalCost).toBeCloseTo(1.5, 6);
+ // input (incl. cache-read) + output + cache-write must sum back to the billed total
+ expect(split.inputCost + split.outputCost + split.cacheWriteCost).toBeCloseTo(1.5, 6);
+ expect(split.inputCost).toBeGreaterThan(0);
+ expect(split.outputCost).toBeGreaterThan(0);
+ });
+
+ it('reports positive cache savings when tokens were read from cache', () => {
+ const usage: ModelUsage = {
+ inputCachedTokens: 1_000_000,
+ inputCacheMissTokens: 0,
+ totalInputTokens: 1_000_000,
+ totalOutputTokens: 0,
+ };
+ const split = computeMessageCostSplit(usage, priced.providerId, priced.id, 0);
+
+ // savings = cachedTokens × (inputRate − cachedRate) / 1e6, strictly positive
+ expect(split.cacheSavings).toBeGreaterThan(0);
+ expect(split.cacheReadTokens).toBe(1_000_000);
+ });
+
+ it('passes through token components', () => {
+ const usage: ModelUsage = {
+ inputWriteCacheTokens: 300,
+ totalInputTokens: 1200,
+ totalOutputTokens: 400,
+ totalTokens: 1600,
+ };
+ const split = computeMessageCostSplit(usage, priced.providerId, priced.id, 0);
+
+ expect(split.inputTokens).toBe(1200);
+ expect(split.outputTokens).toBe(400);
+ expect(split.cacheWriteTokens).toBe(300);
+ expect(split.totalTokens).toBe(1600);
+ });
+});
diff --git a/apps/server/src/services/usage/cost.ts b/apps/server/src/services/usage/cost.ts
new file mode 100644
index 00000000000..68b817f4e89
--- /dev/null
+++ b/apps/server/src/services/usage/cost.ts
@@ -0,0 +1,121 @@
+import { USD_TO_CNY } from '@lobechat/const';
+import { LOBE_DEFAULT_MODEL_LIST, type Pricing } from 'model-bank';
+
+import { type ModelUsage } from '@/types/message';
+import {
+ getCachedTextInputUnitRate,
+ getTextInputUnitRate,
+ getTextOutputUnitRate,
+ getWriteCacheInputUnitRate,
+} from '@/utils/pricing';
+
+const PER_MILLION = 1_000_000;
+
+// Pricing is keyed by `provider/model` with an `model`-only fallback so messages
+// whose stored provider differs from the model-bank providerId still resolve.
+const pricingByKey = new Map<string, Pricing | undefined>();
+for (const m of LOBE_DEFAULT_MODEL_LIST) {
+ pricingByKey.set(`${m.providerId}/${m.id}`, m.pricing);
+ if (!pricingByKey.has(m.id)) pricingByKey.set(m.id, m.pricing);
+}
+
+const lookupPricing = (provider?: string | null, model?: string | null): Pricing | undefined => {
+ if (!model) return undefined;
+ if (provider && pricingByKey.has(`${provider}/${model}`)) {
+ return pricingByKey.get(`${provider}/${model}`);
+ }
+ return pricingByKey.get(model);
+};
+
+// Pricing rates live in the model's currency (per million tokens). Normalize to
+// USD so every aggregate is comparable regardless of the model's listed currency.
+const toUsdRate = (rate: number | undefined, currency?: string): number | undefined =>
+ rate === undefined ? undefined : currency === 'CNY' ? rate / USD_TO_CNY : rate;
+
+export interface MessageCostSplit {
+ /** Input tokens that missed the cache and were freshly processed. */
+ cacheMissTokens: number;
+ /** Cached input tokens that were read (cache hits). */
+ cacheReadTokens: number;
+ /** USD saved by reading from cache instead of paying full input rate. */
+ cacheSavings: number;
+ cacheWriteCost: number;
+ cacheWriteTokens: number;
+ /** Input cost incl. the cache-read portion (USD). */
+ inputCost: number;
+ inputTokens: number;
+ outputCost: number;
+ outputTokens: number;
+ totalCost: number;
+ totalTokens: number;
+}
+
+/**
+ * Split a single assistant message's usage into input / output / cache-write
+ * cost + token components, using model-bank pricing. The cost split is scaled to
+ * the authoritative billed `storedCost` so per-bucket sums always match the
+ * headline cost; when pricing is unknown the whole billed cost falls into input.
+ */
+export const computeMessageCostSplit = (
+ usage: ModelUsage | undefined,
+ provider?: string | null,
+ model?: string | null,
+ storedCost = 0,
+): MessageCostSplit => {
+ const pricing = lookupPricing(provider, model);
+ const currency = pricing?.currency;
+
+ const inputRate = toUsdRate(getTextInputUnitRate(pricing), currency);
+ const cachedRate = toUsdRate(getCachedTextInputUnitRate(pricing), currency) ?? inputRate;
+ const writeRate = toUsdRate(getWriteCacheInputUnitRate(pricing), currency) ?? inputRate;
+ const outputRate = toUsdRate(getTextOutputUnitRate(pricing), currency);
+
+ const cacheReadTokens = usage?.inputCachedTokens ?? 0;
+ const totalInputTokens = usage?.totalInputTokens ?? 0;
+ const cacheMissTokens =
+ usage?.inputCacheMissTokens ?? Math.max(0, totalInputTokens - cacheReadTokens);
+ const toolTokens = usage?.inputToolTokens ?? 0;
+ const cacheWriteTokens = usage?.inputWriteCacheTokens ?? 0;
+ const outputTokens = usage?.totalOutputTokens ?? 0;
+
+ let freshInputCost =
+ inputRate === undefined ? 0 : ((cacheMissTokens + toolTokens) * inputRate) / PER_MILLION;
+ let cacheReadCost = cachedRate === undefined ? 0 : (cacheReadTokens * cachedRate) / PER_MILLION;
+ let cacheWriteCost = writeRate === undefined ? 0 : (cacheWriteTokens * writeRate) / PER_MILLION;
+ let outputCost = outputRate === undefined ? 0 : (outputTokens * outputRate) / PER_MILLION;
+ let computedTotal = freshInputCost + cacheReadCost + cacheWriteCost + outputCost;
+
+ // Reconcile the split with the billed cost so cards == chart.
+ if (storedCost > 0) {
+ if (computedTotal > 0) {
+ const scale = storedCost / computedTotal;
+ freshInputCost *= scale;
+ cacheReadCost *= scale;
+ cacheWriteCost *= scale;
+ outputCost *= scale;
+ } else {
+ // No pricing data — attribute the whole billed cost to input.
+ freshInputCost = storedCost;
+ }
+ computedTotal = storedCost;
+ }
+
+ const cacheSavings =
+ inputRate !== undefined && cachedRate !== undefined
+ ? Math.max(0, (cacheReadTokens * (inputRate - cachedRate)) / PER_MILLION)
+ : 0;
+
+ return {
+ cacheMissTokens,
+ cacheReadTokens,
+ cacheSavings,
+ cacheWriteCost,
+ cacheWriteTokens,
+ inputCost: freshInputCost + cacheReadCost,
+ inputTokens: totalInputTokens,
+ outputCost,
+ outputTokens,
+ totalCost: computedTotal,
+ totalTokens: usage?.totalTokens ?? totalInputTokens + outputTokens,
+ };
+};
diff --git a/apps/server/src/services/usage/index.test.ts b/apps/server/src/services/usage/index.test.ts
index 993f92ed670..2296690423a 100644
--- a/apps/server/src/services/usage/index.test.ts
+++ b/apps/server/src/services/usage/index.test.ts
@@ -6,6 +6,18 @@ import { type MessageMetadata } from '@/types/message';
import { UsageRecordService } from './index';
+/**
+ * Recursively walk an object graph (cycle-safe) looking for `target` as a
+ * substring of any string value. Used to assert that a bound value (e.g. an
+ * agent id) made it into the composed drizzle WHERE clause.
+ */
+const deepIncludes = (value: unknown, target: string, seen = new Set<unknown>()): boolean => {
+ if (typeof value === 'string') return value.includes(target);
+ if (!value || typeof value !== 'object' || seen.has(value)) return false;
+ seen.add(value);
+ return Object.values(value as Record<string, unknown>).some((v) => deepIncludes(v, target, seen));
+};
+
describe('UsageRecordService', () => {
let service: UsageRecordService;
let mockDb: LobeChatDatabase;
@@ -19,6 +31,20 @@ describe('UsageRecordService', () => {
mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });
};
+ // Variant that also captures the args passed to `.where(...)` so tests can
+ // assert what ended up in the composed WHERE clause.
+ const setupCapturingMock = (mockMessages: any[]) => {
+ const whereArgs: unknown[] = [];
+ const mockOrderBy = vi.fn().mockResolvedValue(mockMessages);
+ const mockWhere = vi.fn().mockImplementation((arg: unknown) => {
+ whereArgs.push(arg);
+ return { orderBy: mockOrderBy };
+ });
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });
+ return { whereArgs };
+ };
+
beforeEach(() => {
// Create a fresh mock for each test
const mockOrderBy = vi.fn();
@@ -324,6 +350,37 @@ describe('UsageRecordService', () => {
expect(spy).toHaveBeenCalledWith(expect.any(String), expect.any(String), 'agent-99');
});
+ it('scopes the query to a single agent when agentId is provided', async () => {
+ const { whereArgs } = setupCapturingMock([
+ {
+ id: 'msg-1',
+ userId,
+ role: 'assistant',
+ provider: 'openai',
+ model: 'gpt-4',
+ createdAt: dayjs().startOf('month').toDate(),
+ agentId: 'agt_123',
+ metadata: { cost: 0.05, totalInputTokens: 100, totalOutputTokens: 50 } as MessageMetadata,
+ },
+ ]);
+
+ const result = await service.findAndGroupByDay(undefined, 'agt_123');
+
+ // the composed WHERE clause must carry the agent id as a bound value
+ expect(deepIncludes(whereArgs[0], 'agt_123')).toBe(true);
+ // and the records still map through correctly
+ expect(result.some((log) => log.totalRequests > 0)).toBe(true);
+ });
+
+ it('does not add an agent filter when agentId is omitted', async () => {
+ const { whereArgs } = setupCapturingMock([]);
+
+ await service.findAndGroupByDay();
+
+ // no bound value should reference an agent id (none was passed)
+ expect(deepIncludes(whereArgs[0], 'agt_')).toBe(false);
+ });
+
it('should handle specific month parameter', async () => {
const mockMessages = [
{
diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.ts
index b4c4f52b695..d609062d233 100644
--- a/apps/server/src/services/usage/index.ts
+++ b/apps/server/src/services/usage/index.ts
@@ -1,15 +1,24 @@
import dayjs from 'dayjs';
import debug from 'debug';
-import { desc, eq } from 'drizzle-orm';
+import { asc, desc, eq } from 'drizzle-orm';
import { messages } from '@/database/schemas';
import { type LobeChatDatabase } from '@/database/type';
import { genRangeWhere, genWhere } from '@/database/utils/genWhere';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
-import { type MessageMetadata } from '@/types/message';
-import { type UsageLog, type UsageRecordItem } from '@/types/usage/usageRecord';
+import { type MessageMetadata, type ModelUsage } from '@/types/message';
+import {
+ type AgentUsageBucket,
+ type AgentUsageGranularity,
+ type AgentUsageModelRow,
+ type AgentUsageStats,
+ type UsageLog,
+ type UsageRecordItem,
+} from '@/types/usage/usageRecord';
import { formatDate } from '@/utils/format';
+import { computeMessageCostSplit } from './cost';
+
const log = debug('lobe-usage:service');
export class UsageRecordService {
@@ -87,6 +96,7 @@ export class UsageRecordService {
/**
* @description Find usage records by month.
* @param mo Month
+ * @param agentId When provided, only count messages produced by this agent.
* @returns UsageRecordItem[]
*/
findByMonth = async (mo?: string, agentId?: string): Promise<UsageRecordItem[]> => {
@@ -193,6 +203,7 @@ export class UsageRecordService {
/**
* @description Find usage grouped by day for a custom date range (e.g. past 12 months).
* Does not pad missing days for large ranges.
+ * @param agentId When provided, only count messages produced by this agent.
*/
findAndGroupByDateRange = async (
startAt: string,
@@ -202,4 +213,146 @@ export class UsageRecordService {
const spends = await this.findByDateRange(startAt, endAt, agentId);
return this.groupByDay(spends, startAt, endAt, false);
};
+
+ /**
+ * @description Rich per-agent usage stats: cost (with cache savings), token
+ * totals, and per-bucket input/output/cache-write split for a trend chart,
+ * plus a per-model breakdown. Bucketed by day or week across [startAt, endAt].
+ */
+ getAgentUsageStats = async (
+ agentId: string,
+ startAt: string,
+ endAt: string,
+ granularity: AgentUsageGranularity = 'day',
+ ): Promise<AgentUsageStats> => {
+ const rows = await this.db
+ .select({
+ createdAt: messages.createdAt,
+ metadata: messages.metadata,
+ model: messages.model,
+ provider: messages.provider,
+ usage: messages.usage,
+ })
+ .from(messages)
+ .where(
+ genWhere([
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: messages.userId, workspaceId: messages.workspaceId },
+ ),
+ eq(messages.role, 'assistant'),
+ eq(messages.agentId, agentId),
+ genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),
+ ]),
+ )
+ .orderBy(asc(messages.createdAt));
+
+ const bucketStart = (date: Date) =>
+ granularity === 'week' ? dayjs(date).startOf('week') : dayjs(date).startOf('day');
+
+ const buckets = new Map<string, AgentUsageBucket>();
+ const models = new Map<string, AgentUsageModelRow>();
+ const summary = {
+ cacheHitRate: 0,
+ cacheReadTokens: 0,
+ cacheSavings: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ totalCost: 0,
+ totalRequests: 0,
+ totalTokens: 0,
+ };
+ let cacheMissTokens = 0;
+
+ for (const row of rows) {
+ const metadata = row.metadata as MessageMetadata | null;
+ const usage = (row.usage as ModelUsage | null) ?? metadata?.usage;
+ const storedCost = usage?.cost ?? metadata?.cost ?? 0;
+ const split = computeMessageCostSplit(usage, row.provider, row.model, storedCost);
+
+ // bucket
+ const start = bucketStart(row.createdAt);
+ const key = start.format('YYYY-MM-DD');
+ const bucket = buckets.get(key) ?? {
+ cacheWriteCost: 0,
+ cacheWriteTokens: 0,
+ date: start.valueOf(),
+ inputCost: 0,
+ inputTokens: 0,
+ label: start.format('M/D'),
+ outputCost: 0,
+ outputTokens: 0,
+ totalCost: 0,
+ };
+ bucket.inputCost += split.inputCost;
+ bucket.outputCost += split.outputCost;
+ bucket.cacheWriteCost += split.cacheWriteCost;
+ bucket.totalCost += split.totalCost;
+ bucket.inputTokens += split.inputTokens;
+ bucket.outputTokens += split.outputTokens;
+ bucket.cacheWriteTokens += split.cacheWriteTokens;
+ buckets.set(key, bucket);
+
+ // per-model
+ const model = row.model || 'unknown';
+ const provider = row.provider || 'unknown';
+ const modelKey = `${provider}/${model}`;
+ const modelRow = models.get(modelKey) ?? {
+ cost: 0,
+ id: modelKey,
+ model,
+ provider,
+ requests: 0,
+ totalTokens: 0,
+ };
+ modelRow.cost += split.totalCost;
+ modelRow.totalTokens += split.totalTokens;
+ modelRow.requests += 1;
+ models.set(modelKey, modelRow);
+
+ // summary
+ summary.totalCost += split.totalCost;
+ summary.cacheSavings += split.cacheSavings;
+ summary.cacheReadTokens += split.cacheReadTokens;
+ summary.inputTokens += split.inputTokens;
+ summary.outputTokens += split.outputTokens;
+ summary.totalTokens += split.totalTokens;
+ summary.totalRequests += 1;
+ cacheMissTokens += split.cacheMissTokens;
+ }
+
+ const cacheBase = summary.cacheReadTokens + cacheMissTokens;
+ summary.cacheHitRate = cacheBase > 0 ? summary.cacheReadTokens / cacheBase : 0;
+
+ // pad missing buckets so the chart spans the whole range
+ const step = granularity === 'week' ? 'week' : 'day';
+ const padded: AgentUsageBucket[] = [];
+ const end = dayjs(endAt);
+ for (
+ let cursor = bucketStart(dayjs(startAt).toDate());
+ cursor.isBefore(end) || cursor.isSame(end, step);
+ cursor = cursor.add(1, step)
+ ) {
+ const key = cursor.format('YYYY-MM-DD');
+ padded.push(
+ buckets.get(key) ?? {
+ cacheWriteCost: 0,
+ cacheWriteTokens: 0,
+ date: cursor.valueOf(),
+ inputCost: 0,
+ inputTokens: 0,
+ label: cursor.format('M/D'),
+ outputCost: 0,
+ outputTokens: 0,
+ totalCost: 0,
+ },
+ );
+ }
+
+ return {
+ buckets: padded,
+ byModel: [...models.values()].sort((a, b) => b.totalTokens - a.totalTokens),
+ summary,
+ };
+ };
}
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index 0c6d040e846..d51e648f7a2 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -40,5 +40,28 @@
"table.more": "View Details",
"table.title": "Credit Usage Details",
"table.totalToken.input": "Input",
- "table.totalToken.output": "Output"
+ "table.totalToken.output": "Output",
+ "usageStats.breakdown.cost": "Cost",
+ "usageStats.breakdown.model": "Model",
+ "usageStats.breakdown.requests": "Requests",
+ "usageStats.breakdown.title": "Usage by Model",
+ "usageStats.breakdown.totalTokens": "Tokens",
+ "usageStats.byDay": "By day",
+ "usageStats.byWeek": "By week",
+ "usageStats.cards.cacheDesc": "Hit rate {{rate}}% · Read {{read}}",
+ "usageStats.cards.cacheSavings": "Cache savings",
+ "usageStats.cards.cost": "Cost",
+ "usageStats.cards.token": "Token",
+ "usageStats.cards.tokenDesc": "Input {{input}} · Output {{output}}",
+ "usageStats.chart.cacheWrite": "Cache write",
+ "usageStats.chart.input": "Input",
+ "usageStats.chart.output": "Output",
+ "usageStats.chart.spend": "Cost",
+ "usageStats.chart.title": "When this agent spent",
+ "usageStats.chart.tokens": "Token",
+ "usageStats.dimension": "Dimension",
+ "usageStats.entry": "Usage & Cost",
+ "usageStats.range": "Time range",
+ "usageStats.rangeSuffix": "Last {{count}}d",
+ "usageStats.title": "Usage & Cost"
}
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index ac3bdb7c098..189d834ad21 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -40,5 +40,28 @@
"table.more": "查看详情",
"table.title": "计算积分使用详情",
"table.totalToken.input": "输入",
- "table.totalToken.output": "输出"
+ "table.totalToken.output": "输出",
+ "usageStats.breakdown.cost": "费用",
+ "usageStats.breakdown.model": "模型",
+ "usageStats.breakdown.requests": "请求数",
+ "usageStats.breakdown.title": "按模型统计",
+ "usageStats.breakdown.totalTokens": "Tokens",
+ "usageStats.byDay": "按天",
+ "usageStats.byWeek": "按周",
+ "usageStats.cards.cacheDesc": "命中率 {{rate}}% · 读取 {{read}}",
+ "usageStats.cards.cacheSavings": "缓存节省",
+ "usageStats.cards.cost": "费用",
+ "usageStats.cards.token": "Token",
+ "usageStats.cards.tokenDesc": "输入 {{input}} · 输出 {{output}}",
+ "usageStats.chart.cacheWrite": "缓存写入",
+ "usageStats.chart.input": "输入",
+ "usageStats.chart.output": "输出",
+ "usageStats.chart.spend": "费用",
+ "usageStats.chart.title": "这个智能体在何时消耗",
+ "usageStats.chart.tokens": "Token",
+ "usageStats.dimension": "维度",
+ "usageStats.entry": "用量与成本",
+ "usageStats.range": "时间范围",
+ "usageStats.rangeSuffix": "近 {{count}} 天",
+ "usageStats.title": "用量与成本"
}
diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.ts
index 32671810098..33a2e654451 100644
--- a/packages/locales/src/default/spend.ts
+++ b/packages/locales/src/default/spend.ts
@@ -41,4 +41,27 @@ export default {
'table.title': 'Credit Usage Details',
'table.totalToken.input': 'Input',
'table.totalToken.output': 'Output',
+ 'usageStats.breakdown.cost': 'Cost',
+ 'usageStats.breakdown.model': 'Model',
+ 'usageStats.breakdown.requests': 'Requests',
+ 'usageStats.breakdown.title': 'Usage by Model',
+ 'usageStats.breakdown.totalTokens': 'Tokens',
+ 'usageStats.byDay': 'By day',
+ 'usageStats.byWeek': 'By week',
+ 'usageStats.cards.cacheDesc': 'Hit rate {{rate}}% · Read {{read}}',
+ 'usageStats.cards.cacheSavings': 'Cache savings',
+ 'usageStats.cards.cost': 'Cost',
+ 'usageStats.cards.token': 'Token',
+ 'usageStats.cards.tokenDesc': 'Input {{input}} · Output {{output}}',
+ 'usageStats.chart.cacheWrite': 'Cache write',
+ 'usageStats.chart.input': 'Input',
+ 'usageStats.chart.output': 'Output',
+ 'usageStats.chart.spend': 'Cost',
+ 'usageStats.chart.title': 'When this agent spent',
+ 'usageStats.chart.tokens': 'Token',
+ 'usageStats.dimension': 'Dimension',
+ 'usageStats.entry': 'Usage & Cost',
+ 'usageStats.range': 'Time range',
+ 'usageStats.rangeSuffix': 'Last {{count}}d',
+ 'usageStats.title': 'Usage & Cost',
};
diff --git a/packages/types/src/usage/usageRecord.ts b/packages/types/src/usage/usageRecord.ts
index 195757c0f96..a5907b3c97c 100644
--- a/packages/types/src/usage/usageRecord.ts
+++ b/packages/types/src/usage/usageRecord.ts
@@ -52,3 +52,50 @@ export type UsageLog = {
totalSpend: number;
totalTokens: number;
};
+
+/** Time granularity for the agent usage chart buckets. */
+export type AgentUsageGranularity = 'day' | 'week';
+
+/**
+ * One bar in the agent usage trend chart. Cost components are reconciled to the
+ * authoritative billed cost; token components are the raw reported counts.
+ * `input` cost folds the cache-read cost into it (the chart only breaks out
+ * input / output / cache-write, matching the legend).
+ */
+export interface AgentUsageBucket {
+ cacheWriteCost: number;
+ cacheWriteTokens: number;
+ /** Bucket start timestamp (ms), for stable sorting. */
+ date: number;
+ inputCost: number;
+ inputTokens: number;
+ /** Display label, e.g. "5/25" (day) or week-start "5/25" (week). */
+ label: string;
+ outputCost: number;
+ outputTokens: number;
+ totalCost: number;
+}
+
+export interface AgentUsageModelRow {
+ cost: number;
+ id: string;
+ model: string;
+ provider: string;
+ requests: number;
+ totalTokens: number;
+}
+
+export interface AgentUsageStats {
+ buckets: AgentUsageBucket[];
+ byModel: AgentUsageModelRow[];
+ summary: {
+ cacheHitRate: number;
+ cacheReadTokens: number;
+ cacheSavings: number;
+ inputTokens: number;
+ outputTokens: number;
+ totalCost: number;
+ totalRequests: number;
+ totalTokens: number;
+ };
+}
diff --git a/src/features/AgentUsage/ModelBreakdown.tsx b/src/features/AgentUsage/ModelBreakdown.tsx
new file mode 100644
index 00000000000..5f01cbe5212
--- /dev/null
+++ b/src/features/AgentUsage/ModelBreakdown.tsx
@@ -0,0 +1,77 @@
+'use client';
+
+import { ModelIcon } from '@lobehub/icons';
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { Table } from 'antd';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type AgentUsageModelRow } from '@/types/usage/usageRecord';
+import { formatNumber, formatUsageValue } from '@/utils/format';
+
+interface ModelBreakdownProps {
+ isLoading?: boolean;
+ rows: AgentUsageModelRow[];
+}
+
+const ModelBreakdown = memo<ModelBreakdownProps>(({ rows, isLoading }) => {
+ const { t } = useTranslation('spend');
+
+ const columns = [
+ {
+ dataIndex: 'model',
+ key: 'model',
+ render: (model: string, record: AgentUsageModelRow) => (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ModelIcon model={model} size={20} />
+ <Flexbox>
+ <Text ellipsis>{model}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {record.provider}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ ),
+ title: t('usageStats.breakdown.model'),
+ },
+ {
+ align: 'right' as const,
+ dataIndex: 'requests',
+ key: 'requests',
+ render: (value: number) => formatNumber(value),
+ title: t('usageStats.breakdown.requests'),
+ },
+ {
+ align: 'right' as const,
+ dataIndex: 'totalTokens',
+ key: 'totalTokens',
+ render: (value: number) => formatUsageValue(value),
+ title: t('usageStats.breakdown.totalTokens'),
+ },
+ {
+ align: 'right' as const,
+ dataIndex: 'cost',
+ key: 'cost',
+ render: (value: number) => `$${formatNumber(value, 2)}`,
+ title: t('usageStats.breakdown.cost'),
+ },
+ ];
+
+ return (
+ <Block gap={16} variant={'borderless'}>
+ <Text fontSize={16} weight={500}>
+ {t('usageStats.breakdown.title')}
+ </Text>
+ <Table<AgentUsageModelRow>
+ columns={columns}
+ dataSource={rows}
+ loading={isLoading}
+ pagination={false}
+ rowKey={'id'}
+ size={'middle'}
+ />
+ </Block>
+ );
+});
+
+export default ModelBreakdown;
diff --git a/src/features/AgentUsage/StatCards.tsx b/src/features/AgentUsage/StatCards.tsx
new file mode 100644
index 00000000000..c7f6e4bb6ef
--- /dev/null
+++ b/src/features/AgentUsage/StatCards.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { Grid, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import StatisticCard from '@/components/StatisticCard';
+import { type AgentUsageStats } from '@/types/usage/usageRecord';
+import { formatNumber, formatUsageValue } from '@/utils/format';
+
+interface StatCardsProps {
+ isLoading?: boolean;
+ rangeLabel: string;
+ summary: AgentUsageStats['summary'];
+}
+
+const desc = (text: string) => (
+ <Text fontSize={12} type={'secondary'}>
+ {text}
+ </Text>
+);
+
+const StatCards = memo<StatCardsProps>(({ summary, isLoading, rangeLabel }) => {
+ const { t } = useTranslation('spend');
+ const suffix = ` · ${rangeLabel}`;
+
+ return (
+ <Grid gap={8} maxItemWidth={240} rows={3}>
+ <StatisticCard
+ loading={isLoading}
+ title={t('usageStats.cards.cost') + suffix}
+ statistic={{
+ precision: 2,
+ prefix: '$',
+ value: formatNumber(summary.totalCost, 2),
+ }}
+ />
+ <StatisticCard
+ loading={isLoading}
+ title={t('usageStats.cards.cacheSavings') + suffix}
+ statistic={{
+ description: desc(
+ t('usageStats.cards.cacheDesc', {
+ rate: String(Math.round(summary.cacheHitRate * 100)),
+ read: formatUsageValue(summary.cacheReadTokens),
+ }),
+ ),
+ precision: 2,
+ prefix: '$',
+ value: formatNumber(summary.cacheSavings, 2),
+ valueStyle: { color: cssVar.colorSuccess },
+ }}
+ />
+ <StatisticCard
+ loading={isLoading}
+ title={t('usageStats.cards.token') + suffix}
+ statistic={{
+ description: desc(
+ t('usageStats.cards.tokenDesc', {
+ input: formatUsageValue(summary.inputTokens),
+ output: formatUsageValue(summary.outputTokens),
+ }),
+ ),
+ value: formatUsageValue(summary.totalTokens),
+ }}
+ />
+ </Grid>
+ );
+});
+
+export default StatCards;
diff --git a/src/features/AgentUsage/UsageTrendChart.tsx b/src/features/AgentUsage/UsageTrendChart.tsx
new file mode 100644
index 00000000000..b8de095b60a
--- /dev/null
+++ b/src/features/AgentUsage/UsageTrendChart.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { BarChart } from '@lobehub/charts';
+import { Block, Flexbox, Skeleton, Text } from '@lobehub/ui';
+import { Segmented } from '@lobehub/ui/base-ui';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type AgentUsageBucket } from '@/types/usage/usageRecord';
+import { formatNumber, formatTokenNumber } from '@/utils/format';
+
+enum ShowType {
+ Spend = 'spend',
+ Token = 'token',
+}
+
+// 输入 (dark) / 输出 (medium) / 缓存写入 (light) — blue shades matching the design.
+const COLORS = ['#1668dc', '#4096ff', '#91caff'];
+
+interface UsageTrendChartProps {
+ buckets?: AgentUsageBucket[];
+ isLoading?: boolean;
+}
+
+const UsageTrendChart = memo<UsageTrendChartProps>(({ buckets, isLoading }) => {
+ const { t } = useTranslation('spend');
+ const [type, setType] = useState<ShowType>(ShowType.Spend);
+
+ const inputKey = t('usageStats.chart.input');
+ const outputKey = t('usageStats.chart.output');
+ const cacheWriteKey = t('usageStats.chart.cacheWrite');
+ const categories = [inputKey, outputKey, cacheWriteKey];
+
+ const chartData = useMemo(
+ () =>
+ (buckets ?? []).map((b) => ({
+ [cacheWriteKey]: type === ShowType.Spend ? b.cacheWriteCost : b.cacheWriteTokens,
+ [inputKey]: type === ShowType.Spend ? b.inputCost : b.inputTokens,
+ [outputKey]: type === ShowType.Spend ? b.outputCost : b.outputTokens,
+ label: b.label,
+ })),
+ [buckets, type, inputKey, outputKey, cacheWriteKey],
+ );
+
+ return (
+ <Block gap={16} variant={'borderless'}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Text fontSize={16} weight={500}>
+ {t('usageStats.chart.title')}
+ </Text>
+ <Segmented
+ value={type}
+ options={[
+ { label: t('usageStats.chart.spend'), value: ShowType.Spend },
+ { label: t('usageStats.chart.tokens'), value: ShowType.Token },
+ ]}
+ onChange={(value) => setType(value as ShowType)}
+ />
+ </Flexbox>
+ {isLoading ? (
+ <Skeleton.Block height={320} />
+ ) : (
+ <BarChart
+ showLegend
+ stack
+ categories={categories}
+ colors={COLORS}
+ data={chartData}
+ height={320}
+ index={'label'}
+ valueFormatter={(num: number) =>
+ type === ShowType.Spend ? `$${formatNumber(num, 2)}` : formatTokenNumber(num)
+ }
+ />
+ )}
+ </Block>
+ );
+});
+
+export default UsageTrendChart;
diff --git a/src/features/AgentUsage/hooks.ts b/src/features/AgentUsage/hooks.ts
new file mode 100644
index 00000000000..b0fe07772cd
--- /dev/null
+++ b/src/features/AgentUsage/hooks.ts
@@ -0,0 +1,36 @@
+import dayjs from 'dayjs';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { statsKeys } from '@/libs/swr/keys';
+import { usageService } from '@/services/usage';
+import { type AgentUsageGranularity } from '@/types/usage/usageRecord';
+
+export type TimeRange = '7d' | '30d' | '90d';
+
+export const RANGE_DAYS: Record<TimeRange, number> = {
+ '30d': 30,
+ '7d': 7,
+ '90d': 90,
+};
+
+/**
+ * Fetch rich usage + cost stats for a single agent over the selected time range
+ * and granularity. The range resolves to an inclusive `[startAt, endAt]` of the
+ * last N days (ending today).
+ */
+export const useAgentUsageStats = (
+ agentId: string,
+ range: TimeRange,
+ granularity: AgentUsageGranularity,
+) => {
+ const endAt = dayjs().endOf('day').format('YYYY-MM-DD');
+ const startAt = dayjs()
+ .subtract(RANGE_DAYS[range] - 1, 'day')
+ .startOf('day')
+ .format('YYYY-MM-DD');
+
+ return useClientDataSWR(
+ agentId ? statsKeys.agentUsageStat(agentId, startAt, endAt, granularity) : null,
+ async () => usageService.getAgentUsageStats({ agentId, endAt, granularity, startAt }),
+ );
+};
diff --git a/src/features/AgentUsage/index.tsx b/src/features/AgentUsage/index.tsx
new file mode 100644
index 00000000000..c22efe68edc
--- /dev/null
+++ b/src/features/AgentUsage/index.tsx
@@ -0,0 +1,112 @@
+'use client';
+
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { Segmented } from '@lobehub/ui/base-ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentStore } from '@/store/agent';
+import { type AgentUsageGranularity } from '@/types/usage/usageRecord';
+import { StyleSheet } from '@/utils/styles';
+
+import { RANGE_DAYS, type TimeRange, useAgentUsageStats } from './hooks';
+import ModelBreakdown from './ModelBreakdown';
+import StatCards from './StatCards';
+import UsageTrendChart from './UsageTrendChart';
+
+const styles = StyleSheet.create({
+ body: {
+ display: 'flex',
+ overflowY: 'auto',
+ position: 'relative',
+ },
+});
+
+const EMPTY_SUMMARY = {
+ cacheHitRate: 0,
+ cacheReadTokens: 0,
+ cacheSavings: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ totalCost: 0,
+ totalRequests: 0,
+ totalTokens: 0,
+};
+
+const AgentUsage = memo(() => {
+ const { t } = useTranslation('spend');
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ const [range, setRange] = useState<TimeRange>('30d');
+ const [granularity, setGranularity] = useState<AgentUsageGranularity>('day');
+
+ const { data, isLoading } = useAgentUsageStats(activeAgentId ?? '', range, granularity);
+
+ const rangeLabel = t('usageStats.rangeSuffix', { count: RANGE_DAYS[range] });
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ left={
+ <Text fontSize={16} weight={600}>
+ {t('usageStats.title')}
+ </Text>
+ }
+ />
+ <Flexbox flex={1} style={styles.body} width={'100%'}>
+ <WideScreenContainer>
+ <Flexbox gap={16} paddingBlock={16}>
+ <Block gap={16} padding={20} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={13} type={'secondary'}>
+ {t('usageStats.dimension')}
+ </Text>
+ <Segmented
+ size={'small'}
+ value={granularity}
+ options={[
+ { label: t('usageStats.byDay'), value: 'day' },
+ { label: t('usageStats.byWeek'), value: 'week' },
+ ]}
+ onChange={(v) => setGranularity(v as AgentUsageGranularity)}
+ />
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={13} type={'secondary'}>
+ {t('usageStats.range')}
+ </Text>
+ <Segmented
+ size={'small'}
+ value={range}
+ options={[
+ { label: '7d', value: '7d' },
+ { label: '30d', value: '30d' },
+ { label: '90d', value: '90d' },
+ ]}
+ onChange={(v) => setRange(v as TimeRange)}
+ />
+ </Flexbox>
+ </Flexbox>
+ <StatCards
+ isLoading={isLoading}
+ rangeLabel={rangeLabel}
+ summary={data?.summary ?? EMPTY_SUMMARY}
+ />
+ </Block>
+ <Block padding={20} variant={'outlined'}>
+ <UsageTrendChart buckets={data?.buckets} isLoading={isLoading} />
+ </Block>
+ <Block padding={20} variant={'outlined'}>
+ <ModelBreakdown isLoading={isLoading} rows={data?.byModel ?? []} />
+ </Block>
+ </Flexbox>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default AgentUsage;
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 66fbf384254..46e9aeed3d5 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -561,6 +561,16 @@ export const chatToolKeys = {
// ---- stats (settings/stats + user header counts) ------------------------
export const statsKeys = {
+ agentUsageStat: def(
+ 'stats:agentUsageStat',
+ (agentId: string, startAt: string, endAt: string, granularity: string) => [
+ 'stats:agentUsageStat',
+ agentId,
+ startAt,
+ endAt,
+ granularity,
+ ],
+ ),
agents: def('stats:agents', () => ['stats:agents']),
countAgents: def('stats:countAgents', () => ['stats:countAgents']),
countMessages: def('stats:countMessages', () => ['stats:countMessages']),
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index e32122df6dc..a822742c872 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -3,7 +3,14 @@ import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import type { TFunction } from 'i18next';
-import { BotMessageSquareIcon, Download, MoreHorizontal, Settings2Icon, Trash } from 'lucide-react';
+import {
+ BarChart3,
+ BotMessageSquareIcon,
+ Download,
+ MoreHorizontal,
+ Settings2Icon,
+ Trash,
+} from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,7 +36,10 @@ import AgentStatusTag from './AgentStatusTag';
import AgentVersionReviewTag from './AgentVersionReviewTag';
import AutoSaveHint from './AutoSaveHint';
-type HeaderTranslation = TFunction<readonly ['setting', 'chat', 'file', 'common'], undefined>;
+type HeaderTranslation = TFunction<
+ readonly ['setting', 'chat', 'file', 'common', 'spend'],
+ undefined
+>;
const buildAgentProfileMarkdown = (params: {
description?: string;
@@ -81,7 +91,7 @@ const buildAgentProfileMarkdown = (params: {
};
const Header = memo(() => {
- const { t } = useTranslation(['setting', 'chat', 'file', 'common']);
+ const { t } = useTranslation(['setting', 'chat', 'file', 'common', 'spend']);
const navigate = useWorkspaceAwareNavigate();
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
@@ -185,6 +195,14 @@ const Header = memo(() => {
settingsModalRef.current = openAgentSettingsModal();
},
},
+ {
+ icon: <Icon icon={BarChart3} />,
+ key: 'usage-stats',
+ label: t('usageStats.entry', { ns: 'spend' }),
+ onClick: () => {
+ if (activeAgentId) navigate(`/agent/${activeAgentId}/stats`);
+ },
+ },
{ type: 'divider' as const },
{
children: [
@@ -212,7 +230,16 @@ const Header = memo(() => {
onClick: handleDelete,
},
].filter(Boolean);
- }, [canEdit, handleExportMarkdown, handleDelete, t, importMenuItem, transferMenuItems]);
+ }, [
+ activeAgentId,
+ canEdit,
+ handleExportMarkdown,
+ handleDelete,
+ navigate,
+ t,
+ importMenuItem,
+ transferMenuItems,
+ ]);
return (
<NavHeader
diff --git a/src/routes/(main)/agent/stats/index.tsx b/src/routes/(main)/agent/stats/index.tsx
new file mode 100644
index 00000000000..64c3d300774
--- /dev/null
+++ b/src/routes/(main)/agent/stats/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentUsage from '@/features/AgentUsage';
+
+const AgentStatsPage = memo(() => (
+ <Suspense fallback={<Loading debugId="AgentUsage" />}>
+ <AgentUsage />
+ </Suspense>
+));
+
+export default AgentStatsPage;
diff --git a/src/services/usage.ts b/src/services/usage.ts
index 11981bfe66a..6684617d436 100644
--- a/src/services/usage.ts
+++ b/src/services/usage.ts
@@ -1,13 +1,26 @@
-import { lambdaClient } from "@/libs/trpc/client";
+import { lambdaClient } from '@/libs/trpc/client';
+import { type AgentUsageGranularity } from '@/types/usage/usageRecord';
class UsageService {
- findByMonth = async (mo?: string) => {
- return lambdaClient.usage.findByMonth.query({ mo });
- };
+ findByMonth = async (mo?: string) => {
+ return lambdaClient.usage.findByMonth.query({ mo });
+ };
- findAndGroupByDay = async (mo?: string) => {
- return lambdaClient.usage.findAndGroupByDay.query({ mo });
- }
+ findAndGroupByDay = async (mo?: string) => {
+ return lambdaClient.usage.findAndGroupByDay.query({ mo });
+ };
+
+ /**
+ * Rich usage + cost stats for a single agent over a date range.
+ */
+ getAgentUsageStats = async (params: {
+ agentId: string;
+ endAt: string;
+ granularity: AgentUsageGranularity;
+ startAt: string;
+ }) => {
+ return lambdaClient.usage.getAgentUsageStats.query(params);
+ };
}
-export const usageService = new UsageService();
\ No newline at end of file
+export const usageService = new UsageService();
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 5ab74aa34b2..0f1f70903c1 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -57,6 +57,7 @@ import AgentDocumentLayout from '@/routes/(main)/agent/docs/_layout';
import AgentDocumentRoute from '@/routes/(main)/agent/docs/[docId]';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import AgentProfilePage from '@/routes/(main)/agent/profile';
+import AgentStatsPage from '@/routes/(main)/agent/stats';
import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';
import AgentScopedTasksRoute from '@/routes/(main)/agent/tasks';
import AgentTopicsPage from '@/routes/(main)/agent/topics';
@@ -184,6 +185,10 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: <AgentTopicsPage />,
path: 'topics',
},
+ {
+ element: <AgentStatsPage />,
+ path: 'stats',
+ },
{
element: <AgentScopedTasksRoute />,
handle: { meta: tasksRouteMeta },
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index 17b365b223a..d032ea9c6a6 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -110,6 +110,13 @@ export const sharedMainAreaChildren: RouteObject[] = [
),
path: 'topics',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/stats'),
+ 'Desktop > Chat > Stats',
+ ),
+ path: 'stats',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/agent/tasks'),