LogoAI SDK Token Usage
Hooks

useTokenCost

Message metadata required

In order to use the hooks, the required metadata-fields for AI SDK Token Usage has to be attached to the message. If you have not done this, read Message Metadata.

The hook useTokenCost can be used to get insight into how much you have spent on token usage.

It provides several convenient, pre-computed values such as the total cost, a detailed cost breakdown per token type (input, output, reasoning, cached input), and the currency used. These values are derived directly from the message metadata and the model’s pricing information, allowing you to easily visualize or calculate spending in your UI.

This is particularly useful when building dashboards, admin views, or chat interfaces that need to display cost summaries, track spending over time, or show real-time pricing feedback to users.

Usage

useTokenCost is simply to use, and needs only an array of messages.

import { useTokenCost } from 'ai-sdk-token-usage';
import { useChat } from '@ai-sdk/react';

export default function Chat() {
  const { messages } = useChat();

  const cost = useTokenCost({ messages }); 
};

Here, cost is an object with three keys:

  1. data: All data related to token usage cost.
  2. isLoading: A boolean used to determine if data is loading or not.
  3. error: If an error occured, this will hold useful information to either debug the issue or display an appropriate message to the user.

The reasoning behind this data structure is that the hook leverages SWR internally for data fetching, which introduces asynchronous behavior. SWR returns an object containing data, error, and isLoading, and useTokenCost follows the same pattern. This makes it intuitive for developers familiar with SWR or React Query to handle loading states, manage errors gracefully, and access the resolved data once available — ensuring a consistent and predictable experience when working with asynchronous hooks.

Read the API signature to understand the full structure of the hook’s inputs and return values, and how each field can be used in your component.


API Signature

Parameters

Prop

Type

Returns

Prop

Type