File size: 8,871 Bytes
7d506e1 3a4d158 7d506e1 3a4d158 406122e 3a4d158 7d506e1 3a4d158 7d506e1 3a4d158 7d506e1 4ecc3bd 3a4d158 1b98491 3a4d158 6283446 406122e 7d506e1 d76b37c 7d506e1 d76b37c 7d506e1 9e28f0f 1b98491 9e28f0f 1b98491 9e28f0f 7d506e1 3a4d158 7d506e1 3a4d158 7d506e1 66cb9ac 7d506e1 3a4d158 7d506e1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | import { type ReactNode, useEffect, useMemo, useState } from 'react';
import {
Alert,
Box,
Button,
CircularProgress,
Divider,
Link,
Popover,
Tooltip,
Typography,
} from '@mui/material';
import PaidOutlinedIcon from '@mui/icons-material/PaidOutlined';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import { useSessionStore } from '@/store/sessionStore';
import {
type HfAccountUsageBucket,
type HfInferenceProvidersCredits,
type UsageBucket,
useUsageStore,
} from '@/store/usageStore';
function formatUsd(value: number | undefined): string {
const amount = value ?? 0;
if (amount > 0 && amount < 0.01) return '<$0.01';
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}
function formatCount(value: number | undefined): string {
return new Intl.NumberFormat('en-US').format(value ?? 0);
}
function contextTokenCount(telemetry: UsageBucket | null | undefined): number | undefined {
if (!telemetry) return undefined;
if (telemetry.total_tokens > 0) {
return Math.max(0, telemetry.total_tokens - telemetry.completion_tokens);
}
return (
telemetry.prompt_tokens +
telemetry.cache_read_tokens +
telemetry.cache_creation_tokens
);
}
function billingUnavailableMessage(error: string | null | undefined): string | null {
if (!error) return null;
if (error === 'missing_hf_token') return 'Sign in to view HF account billing usage.';
if (error === 'billing_usage_unavailable') {
return 'HF billing usage is unavailable. Showing app-observed calls and tokens; inference cost may be incomplete.';
}
return 'HF billing usage is unavailable. Showing app-observed calls and tokens; inference cost may be incomplete.';
}
function UsageRow({
label,
value,
strong = false,
}: {
label: string;
value: string;
strong?: boolean;
}) {
return (
<>
<Typography variant="body2" color="text.secondary">
{label}
</Typography>
<Typography
variant="body2"
sx={{ fontWeight: strong ? 700 : 400, fontVariantNumeric: 'tabular-nums' }}
>
{value}
</Typography>
</>
);
}
function UsageGrid({ children }: { children: ReactNode }) {
return (
<Box
sx={{
display: 'grid',
gridTemplateColumns: '1fr auto',
columnGap: 2,
rowGap: 0.5,
mt: 0.75,
}}
>
{children}
</Box>
);
}
function AccountUsageSection({
title,
account,
telemetry,
}: {
title: string;
account: HfAccountUsageBucket | null | undefined;
telemetry: UsageBucket | null | undefined;
}) {
const useJobEstimate =
!account || (account.hf_jobs_usd <= 0 && (telemetry?.hf_jobs_estimated_usd ?? 0) > 0);
return (
<Box sx={{ py: 1 }}>
<Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 700 }}>
{title}
</Typography>
<UsageGrid>
<UsageRow
label="Inference Providers"
value={account ? formatUsd(account.inference_providers_usd) : 'Unavailable'}
strong
/>
<UsageRow
label="HF Jobs"
value={formatUsd(
useJobEstimate ? telemetry?.hf_jobs_estimated_usd : account?.hf_jobs_usd,
)}
/>
<UsageRow
label="HF Sandboxes"
value={formatUsd(telemetry?.sandbox_estimated_usd)}
/>
<UsageRow label="LLM calls" value={formatCount(telemetry?.llm_calls)} />
<UsageRow
label="Input tokens"
value={formatCount(contextTokenCount(telemetry))}
/>
<UsageRow
label="Output tokens"
value={formatCount(telemetry?.completion_tokens)}
/>
</UsageGrid>
</Box>
);
}
function CreditsSection({ credits }: { credits: HfInferenceProvidersCredits | null | undefined }) {
if (!credits) return null;
return (
<>
<Divider />
<Box sx={{ py: 1 }}>
<Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 700 }}>
Inference credits
</Typography>
<UsageGrid>
<UsageRow
label="Included remaining"
value={formatUsd(credits.remaining_included_usd)}
strong
/>
<UsageRow
label="Used / included"
value={`${formatUsd(credits.used_usd)} / ${formatUsd(credits.included_usd)}`}
/>
{credits.limit_usd > 0 && (
<UsageRow
label="Spend limit remaining"
value={formatUsd(credits.remaining_limit_usd)}
/>
)}
</UsageGrid>
</Box>
</>
);
}
export default function UsageMeter() {
const activeSessionId = useSessionStore((state) => state.activeSessionId);
const activeSessionYoloSpend = useSessionStore((state) => {
const active = state.sessions.find((session) => session.id === state.activeSessionId);
return active?.autoApprovalEstimatedSpendUsd ?? null;
});
const { usage, isLoading, error, fetchUsage } = useUsageStore();
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
useEffect(() => {
void fetchUsage(activeSessionId);
}, [activeSessionId, activeSessionYoloSpend, fetchUsage]);
const accountSessionInference =
usage?.hf_account?.current_session?.inference_providers_usd;
const sessionTotal =
accountSessionInference == null
? usage?.session?.total_usd
: accountSessionInference +
(usage?.session?.hf_jobs_estimated_usd ?? 0) +
(usage?.session?.sandbox_estimated_usd ?? 0);
const links = useMemo(() => usage?.links ?? {}, [usage?.links]);
const billingMessage = billingUnavailableMessage(usage?.hf_account?.error);
const open = Boolean(anchorEl);
return (
<>
<Tooltip title="Usage">
<Button
size="small"
variant="outlined"
startIcon={isLoading ? <CircularProgress size={14} /> : <PaidOutlinedIcon fontSize="small" />}
onClick={(event) => setAnchorEl(event.currentTarget)}
sx={{
minWidth: { xs: 58, sm: 84 },
height: 32,
px: { xs: 0.75, sm: 1 },
borderColor: 'divider',
color: 'text.secondary',
fontVariantNumeric: 'tabular-nums',
'& .MuiButton-startIcon': { mr: { xs: 0.25, sm: 0.5 } },
'&:hover': { borderColor: 'primary.main', color: 'primary.main' },
}}
>
{sessionTotal == null ? 'Usage' : formatUsd(sessionTotal)}
</Button>
</Tooltip>
<Popover
open={open}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
slotProps={{
paper: {
sx: {
width: 320,
maxWidth: 'calc(100vw - 24px)',
maxHeight: 'calc(100vh - 24px)',
overflowY: 'auto',
p: 2,
border: '1px solid',
borderColor: 'divider',
},
},
}}
>
<Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
Usage
</Typography>
<Typography variant="caption" color="text.secondary">
Estimated from HF account usage per session.
</Typography>
{error ? (
<Typography variant="body2" color="error" sx={{ mt: 1.5 }}>
{error}
</Typography>
) : (
<>
{billingMessage && (
<Alert severity="info" sx={{ mt: 1.5, py: 0.25 }}>
{billingMessage}
</Alert>
)}
<AccountUsageSection
title="Current session"
account={usage?.hf_account?.current_session ?? null}
telemetry={usage?.session ?? null}
/>
<CreditsSection credits={usage?.hf_account?.inference_providers_credits} />
</>
)}
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, pt: 1 }}>
{links.hf_billing && (
<Link href={links.hf_billing} target="_blank" rel="noopener noreferrer" underline="hover" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.25, fontSize: '0.75rem' }}>
HF billing <OpenInNewIcon sx={{ fontSize: 12 }} />
</Link>
)}
{links.jobs_pricing && (
<Link href={links.jobs_pricing} target="_blank" rel="noopener noreferrer" underline="hover" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.25, fontSize: '0.75rem' }}>
Jobs pricing <OpenInNewIcon sx={{ fontSize: 12 }} />
</Link>
)}
</Box>
</Popover>
</>
);
}
|