{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-assistant-03",
  "description": "Questions about token usage numbers, with the tokens and cost shown for each answer and a change that waits for approval.",
  "registryDependencies": [
    "card",
    "https://www.dashboardblocks.com/r/radix/ai-assistant.json",
    "https://www.dashboardblocks.com/r/radix/ai-chat.json",
    "https://www.dashboardblocks.com/r/radix/ai-usage.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/details.json",
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/kpi.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/ai-assistant/ai-assistant-03.tsx",
      "content": "'use client'\n\nimport {\n  ChatComposer,\n  ChatConversation,\n  ChatMessages,\n  type SuggestedPrompt,\n  SuggestedPrompts,\n} from '@/registry/components/dashboardblocks/ai-assistant'\nimport {\n  type AIChat,\n  getMessageText,\n} from '@/registry/components/dashboardblocks/ai-message'\nimport type { AIToolLabel } from '@/registry/components/dashboardblocks/ai-parts'\nimport {\n  type TokenCounts,\n  type TokenPrices,\n  TokenSplitBar,\n  formatTokens,\n  formatUsd,\n  getCacheHitRate,\n  getTokenCost,\n  tokenPartColors,\n} from '@/registry/components/dashboardblocks/ai-usage'\nimport {\n  BlockReady,\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport { Details } from '@/registry/components/dashboardblocks/details'\nimport { KPIValue } from '@/registry/components/dashboardblocks/kpi'\nimport { formatPercent } from '@/registry/lib/dashboardblocks/format'\nimport { useId, useRef } from 'react'\n\nimport { Card, CardContent } from '@/components/ui/card'\n\ninterface AiAssistant3Props extends BlockStateProps {\n  /**\n   * The chat it runs: `useChat()` from `@ai-sdk/react`, or `useChatStream` for any other stream.\n   * A reply's tokens show under it when its `metadata.usage` is `{ input, cached, output }`: send it from the route with `messageMetadata`.\n   * A tool that waits for approval continues once answered when `useChat` has `sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses`.\n   */\n  chat: AIChat\n  description: string\n  prices: TokenPrices\n  suggestions: SuggestedPrompt[]\n  title: string\n  /** What each tool is called, by its name, or `{ running, done }` for what it's doing while it runs. Others read as their name in words. */\n  toolLabels?: Record<string, AIToolLabel>\n  /** Leave out to show the empty state. */\n  tokens?: TokenCounts\n}\n\nconst exampleProps: Omit<AiAssistant3Props, 'chat'> = {\n  description: 'All models this month. Output is 8% of the tokens and 38% of the cost.',\n  prices: { cached: 0.3, input: 3, output: 15 },\n  suggestions: [\n    {\n      label: 'Cap support summaries',\n      prompt: 'Cap support summaries at 400 tokens',\n    },\n    {\n      label: 'Raise the cache hit rate',\n      prompt: 'How can we raise the cache hit rate?',\n    },\n    { label: 'Forecast next month', prompt: 'Forecast next month’s cost' },\n  ],\n  title: 'Token usage',\n  toolLabels: {\n    get_monthly_usage: {\n      done: 'Read the last three months of usage',\n      running: 'Reading the last three months of usage',\n    },\n    get_usage_by_feature: {\n      done: 'Read usage by feature',\n      running: 'Reading usage by feature',\n    },\n    set_output_limit: 'Set an output limit',\n  },\n  tokens: { cached: 83_000_000, input: 197_000_000, output: 25_500_000 },\n}\n\nfunction readUsage(metadata: unknown): TokenCounts | undefined {\n  if (typeof metadata !== 'object' || metadata === null || !('usage' in metadata)) {\n    return undefined\n  }\n  const { usage } = metadata\n  if (typeof usage !== 'object' || usage === null) return undefined\n  const { cached, input, output } = usage as Record<string, unknown>\n  if (typeof input !== 'number' || typeof output !== 'number') return undefined\n  return { cached: typeof cached === 'number' ? cached : 0, input, output }\n}\n\nconst tokenParts = [\n  { key: 'input', label: 'Input' },\n  { key: 'cached', label: 'Cached' },\n  { key: 'output', label: 'Output' },\n] as const\n\nconst AiAssistant3 = (props: AiAssistant3Props) => {\n  const {\n    description,\n    prices,\n    errorMessage,\n    status: blockStatus,\n    suggestions,\n    title,\n    toolLabels,\n    tokens = { input: 0, output: 0 },\n  } = props\n  const state = getBlockState(blockStatus, props.tokens)\n  const askId = useId()\n  const { chat } = props\n  const { messages, status } = chat\n  const composerRef = useRef<HTMLTextAreaElement>(null)\n  const asked = new Set(messages.map(getMessageText))\n  const remaining = suggestions.filter(\n    (prompt) => !asked.has(prompt.prompt ?? prompt.label),\n  )\n  const total = tokens.input + (tokens.cached ?? 0) + tokens.output\n\n  return (\n    <Card>\n      <CardContent>\n        <BlockStateProvider errorMessage={errorMessage} state={state}>\n          <section className='@container flex flex-col gap-4'>\n            <header className='flex flex-col gap-0.5'>\n              <h2 className='font-semibold tracking-tight'>{title}</h2>\n              <p className='text-muted-foreground text-sm'>{description}</p>\n            </header>\n            <dl className='grid grid-cols-2 gap-x-6 gap-y-4 border-t pt-4 @md:grid-cols-3'>\n              <div className='col-span-2 flex flex-col gap-1 @md:col-span-1'>\n                <dt className='text-muted-foreground text-sm'>Tokens</dt>\n                <dd>\n                  <KPIValue\n                    className='whitespace-nowrap'\n                    value={total}\n                    format={formatTokens}\n                  />\n                </dd>\n              </div>\n              {state !== 'empty' && state !== 'error' && (\n                <>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>Cost</dt>\n                    <dd>\n                      <KPIValue\n                        className='text-2xl'\n                        value={getTokenCost(tokens, prices)}\n                        format={formatUsd}\n                      />\n                    </dd>\n                  </div>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>From the cache</dt>\n                    <dd>\n                      <KPIValue\n                        className='text-2xl'\n                        value={getCacheHitRate(tokens)}\n                        format={(rate) =>\n                          formatPercent(rate, { maximumFractionDigits: 0 })\n                        }\n                      />\n                    </dd>\n                  </div>\n                </>\n              )}\n            </dl>\n            {state !== 'empty' && state !== 'error' && (\n              <>\n                <div className='flex flex-col gap-2'>\n                  <TokenSplitBar tokens={tokens} />\n                  <BlockReady className='text-xs'>\n                    <ul className='text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-xs tabular-nums'>\n                      {tokenParts.map((part) => (\n                        <li key={part.key} className='flex items-center gap-1.5'>\n                          <span\n                            aria-hidden\n                            className='size-2.5 rounded-[3px]'\n                            style={{\n                              backgroundColor: tokenPartColors[part.key],\n                            }}\n                          />\n                          {part.label}\n                          <span className='text-foreground font-medium'>\n                            {formatTokens(tokens[part.key] ?? 0)}\n                          </span>\n                        </li>\n                      ))}\n                    </ul>\n                  </BlockReady>\n                </div>\n                <section\n                  aria-labelledby={askId}\n                  className='flex flex-col gap-3 border-t pt-4'\n                >\n                  <h3 id={askId} className='text-sm font-medium'>\n                    Ask about this data\n                  </h3>\n                  <ChatMessages\n                    status={status}\n                    latest={messages.at(-1)}\n                    label='Questions about this data'\n                    className='max-h-96'\n                    contentClassName='gap-5 ps-0 pe-4 pt-0'\n                  >\n                    {state && <BlockStateRows rows={2} />}\n                    {!state && messages.length === 0 && (\n                      <SuggestedPrompts\n                        label='Suggested questions'\n                        prompts={suggestions}\n                        onSelect={(question) => chat.sendMessage({ text: question })}\n                      />\n                    )}\n                    {!state && (\n                      <ChatConversation\n                        chat={chat}\n                        composerRef={composerRef}\n                        followUps={() => remaining}\n                        toolLabels={toolLabels}\n                        footer={(reply) => {\n                          const replyUsage = readUsage(reply.metadata)\n                          if (!replyUsage) return null\n                          return (\n                            <p className='text-muted-foreground flex justify-between gap-3 text-xs tabular-nums'>\n                              <Details>\n                                <span>\n                                  {formatTokens(\n                                    replyUsage.input + (replyUsage.cached ?? 0),\n                                  )}{' '}\n                                  in\n                                </span>\n                                <span>{formatTokens(replyUsage.output)} out</span>\n                              </Details>\n                              <span>{formatUsd(getTokenCost(replyUsage, prices))}</span>\n                            </p>\n                          )\n                        }}\n                      />\n                    )}\n                  </ChatMessages>\n                  <ChatComposer\n                    disabled={!!state}\n                    status={status}\n                    textareaRef={composerRef}\n                    onSubmit={chat.sendMessage}\n                    onStop={chat.stop}\n                    label='Ask about this data'\n                    placeholder='Ask about token usage'\n                  />\n                </section>\n              </>\n            )}\n          </section>\n        </BlockStateProvider>\n      </CardContent>\n    </Card>\n  )\n}\n\nexport { AiAssistant3, exampleProps as aiAssistant3ExampleProps, type AiAssistant3Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-assistant/ai-assistant-03.tsx"
    }
  ],
  "meta": {
    "shows": "Questions about token usage numbers, with the tokens and cost shown for each answer and a change that waits for approval.",
    "size": "half",
    "usedWith": [
      "ai-usage-01",
      "ai-assistant-02"
    ],
    "component": "AiAssistant3",
    "props": "{ chat: { addToolApprovalResponse?: (response: { approved: boolean; id: string; reason?: string }) => unknown; error?: Error; messages: { id: string; metadata?: unknown; parts: ({ citations?: { endIndex?: number; source: { id: string; sourceType: \"url\"; title?: string; url: string } | { id: string; sourceType: \"document\"; title: string } }[]; state?: \"done\" | \"streaming\"; text: string; type: \"text\" } | { state?: \"done\" | \"streaming\"; text: string; type: \"reasoning\" } | { type: `tool-${string}`; approval?: { approved?: boolean; id: string; isAutomatic?: boolean; reason?: string; requestReason?: string }; errorText?: string; input?: unknown; output?: unknown; preliminary?: boolean; state: \"input-streaming\" | \"input-available\" | \"approval-requested\" | \"approval-responded\" | \"output-available\" | \"output-error\" | \"output-denied\"; title?: string; toolCallId: string } | { toolName: string; type: \"dynamic-tool\"; approval?: { approved?: boolean; id: string; isAutomatic?: boolean; reason?: string; requestReason?: string }; errorText?: string; input?: unknown; output?: unknown; preliminary?: boolean; state: \"input-streaming\" | \"input-available\" | \"approval-requested\" | \"approval-responded\" | \"output-available\" | \"output-error\" | \"output-denied\"; title?: string; toolCallId: string } | { sourceId: string; title?: string; type: \"source-url\"; url: string } | { filename?: string; mediaType: string; sourceId: string; title: string; type: \"source-document\" } | { filename?: string; mediaType: string; type: \"file\"; url: string } | { data: unknown; id?: string; type: `data-${string}` } | { type: \"step-start\" | \"custom\" | \"reasoning-file\" | \"steering-message\" })[]; role: \"system\" | \"user\" | \"assistant\" }[]; regenerate: (options: { messageId?: string }) => unknown; selectVersion?: (messageId: string, index: number) => unknown; sendMessage: (message: { files?: { filename?: string; mediaType: string; type: \"file\"; url: string }[]; messageId?: string; metadata?: unknown; text: string }) => unknown; setMessages?: (messages: []) => void; status: \"error\" | \"streaming\" | \"ready\" | \"submitted\"; stop: () => unknown; versions?: {  } }; description: string; prices: { cached?: number; input: number; output: number }; suggestions: { icon?: ReactNode; label: string; prompt?: string }[]; title: string; toolLabels?: Record<string, string | { done: string; running: string }>; tokens?: { cached?: number; input: number; output: number }; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
