forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.tsx
More file actions
440 lines (385 loc) · 10.5 KB
/
Copy pathcontext.tsx
File metadata and controls
440 lines (385 loc) · 10.5 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { LanguageModelUsage } from 'ai'
import { type ComponentProps, createContext, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { getUsage } from 'tokenlens'
import { Button } from '@/components/ui/button'
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from '@/components/ui/hover-card'
import { Progress } from '@/components/ui/progress'
import { cn } from '@/lib/utils'
const PERCENT_MAX = 100
const ICON_RADIUS = 10
const ICON_VIEWBOX = 24
const ICON_CENTER = 12
const ICON_STROKE_WIDTH = 2
type ModelId = string
type ContextSchema = {
usedTokens: number
maxTokens: number
usage?: LanguageModelUsage
modelId?: ModelId
}
const ContextContext = createContext<ContextSchema | null>(null)
const useContextValue = () => {
const context = useContext(ContextContext)
if (!context) {
throw new Error('Context components must be used within Context')
}
return context
}
export type ContextProps = ComponentProps<typeof HoverCard> & ContextSchema
export const Context = ({
usedTokens,
maxTokens,
usage,
modelId,
...props
}: ContextProps) => (
<ContextContext.Provider
value={{
usedTokens,
maxTokens,
usage,
modelId,
}}
>
<HoverCard {...props} />
</ContextContext.Provider>
)
const ContextIcon = () => {
const { t } = useTranslation()
const { usedTokens, maxTokens } = useContextValue()
const circumference = 2 * Math.PI * ICON_RADIUS
const usedPercent = usedTokens / maxTokens
const dashOffset = circumference * (1 - usedPercent)
return (
<svg
aria-label={t('Model context usage')}
height='20'
role='img'
style={{ color: 'currentcolor' }}
viewBox={`0 0 ${ICON_VIEWBOX} ${ICON_VIEWBOX}`}
width='20'
>
<circle
cx={ICON_CENTER}
cy={ICON_CENTER}
fill='none'
opacity='0.25'
r={ICON_RADIUS}
stroke='currentColor'
strokeWidth={ICON_STROKE_WIDTH}
/>
<circle
cx={ICON_CENTER}
cy={ICON_CENTER}
fill='none'
opacity='0.7'
r={ICON_RADIUS}
stroke='currentColor'
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={dashOffset}
strokeLinecap='round'
strokeWidth={ICON_STROKE_WIDTH}
style={{ transformOrigin: 'center', transform: 'rotate(-90deg)' }}
/>
</svg>
)
}
export type ContextTriggerProps = ComponentProps<typeof Button>
export const ContextTrigger = ({ children, ...props }: ContextTriggerProps) => {
const { usedTokens, maxTokens } = useContextValue()
const usedPercent = usedTokens / maxTokens
const renderedPercent = new Intl.NumberFormat('en-US', {
style: 'percent',
maximumFractionDigits: 1,
}).format(usedPercent)
return (
<HoverCardTrigger
delay={0}
closeDelay={0}
render={
<Button type='button' variant='ghost' {...props}>
{children ?? (
<>
<span className='text-muted-foreground font-medium'>
{renderedPercent}
</span>
<ContextIcon />
</>
)}
</Button>
}
/>
)
}
export type ContextContentProps = ComponentProps<typeof HoverCardContent>
export const ContextContent = ({
className,
...props
}: ContextContentProps) => (
<HoverCardContent
className={cn('min-w-60 divide-y overflow-hidden p-0', className)}
{...props}
/>
)
export type ContextContentHeaderProps = ComponentProps<'div'>
export const ContextContentHeader = ({
children,
className,
...props
}: ContextContentHeaderProps) => {
const { usedTokens, maxTokens } = useContextValue()
const usedPercent = usedTokens / maxTokens
const displayPct = new Intl.NumberFormat('en-US', {
style: 'percent',
maximumFractionDigits: 1,
}).format(usedPercent)
const used = new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(usedTokens)
const total = new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(maxTokens)
return (
<div className={cn('w-full space-y-2 p-3', className)} {...props}>
{children ?? (
<>
<div className='flex items-center justify-between gap-3 text-xs'>
<p>{displayPct}</p>
<p className='text-muted-foreground font-mono'>
{used} / {total}
</p>
</div>
<div className='space-y-2'>
<Progress className='bg-muted' value={usedPercent * PERCENT_MAX} />
</div>
</>
)}
</div>
)
}
export type ContextContentBodyProps = ComponentProps<'div'>
export const ContextContentBody = ({
children,
className,
...props
}: ContextContentBodyProps) => (
<div className={cn('w-full p-3', className)} {...props}>
{children}
</div>
)
export type ContextContentFooterProps = ComponentProps<'div'>
export const ContextContentFooter = ({
children,
className,
...props
}: ContextContentFooterProps) => {
const { t } = useTranslation()
const { modelId, usage } = useContextValue()
const costUSD = modelId
? getUsage({
modelId,
usage: {
input: usage?.inputTokens ?? 0,
output: usage?.outputTokens ?? 0,
},
}).costUSD?.totalUSD
: undefined
const totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(costUSD ?? 0)
return (
<div
className={cn(
'bg-secondary flex w-full items-center justify-between gap-3 p-3 text-xs',
className
)}
{...props}
>
{children ?? (
<>
<span className='text-muted-foreground'>{t('Total cost')}</span>
<span>{totalCost}</span>
</>
)}
</div>
)
}
export type ContextInputUsageProps = ComponentProps<'div'>
export const ContextInputUsage = ({
className,
children,
...props
}: ContextInputUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const inputTokens = usage?.inputTokens ?? 0
if (children) {
return children
}
if (!inputTokens) {
return null
}
const inputCost = modelId
? getUsage({
modelId,
usage: { input: inputTokens, output: 0 },
}).costUSD?.totalUSD
: undefined
const inputCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(inputCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Input')}</span>
<TokensWithCost costText={inputCostText} tokens={inputTokens} />
</div>
)
}
export type ContextOutputUsageProps = ComponentProps<'div'>
export const ContextOutputUsage = ({
className,
children,
...props
}: ContextOutputUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const outputTokens = usage?.outputTokens ?? 0
if (children) {
return children
}
if (!outputTokens) {
return null
}
const outputCost = modelId
? getUsage({
modelId,
usage: { input: 0, output: outputTokens },
}).costUSD?.totalUSD
: undefined
const outputCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(outputCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Output')}</span>
<TokensWithCost costText={outputCostText} tokens={outputTokens} />
</div>
)
}
export type ContextReasoningUsageProps = ComponentProps<'div'>
export const ContextReasoningUsage = ({
className,
children,
...props
}: ContextReasoningUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const reasoningTokens = usage?.outputTokenDetails.reasoningTokens ?? 0
if (children) {
return children
}
if (!reasoningTokens) {
return null
}
const reasoningCost = modelId
? getUsage({
modelId,
usage: { reasoningTokens },
}).costUSD?.totalUSD
: undefined
const reasoningCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(reasoningCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Reasoning')}</span>
<TokensWithCost costText={reasoningCostText} tokens={reasoningTokens} />
</div>
)
}
export type ContextCacheUsageProps = ComponentProps<'div'>
export const ContextCacheUsage = ({
className,
children,
...props
}: ContextCacheUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const cacheTokens = usage?.inputTokenDetails.cacheReadTokens ?? 0
if (children) {
return children
}
if (!cacheTokens) {
return null
}
const cacheCost = modelId
? getUsage({
modelId,
usage: { cacheReads: cacheTokens, input: 0, output: 0 },
}).costUSD?.totalUSD
: undefined
const cacheCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(cacheCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Cache')}</span>
<TokensWithCost costText={cacheCostText} tokens={cacheTokens} />
</div>
)
}
const TokensWithCost = ({
tokens,
costText,
}: {
tokens?: number
costText?: string
}) => (
<span>
{tokens === undefined
? '—'
: new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(tokens)}
{costText ? (
<span className='text-muted-foreground ml-2'>• {costText}</span>
) : null}
</span>
)