LogoAI SDK Token Usage
Hooks

useTokenContext

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 useTokenContext can be used to get insight into how much of the context window is remaining.

It provides several convenient, pre-computed values such as the remaining and used tokens, percentage used, a boolean to determine if the context window is exceeded and more! These values are derived directly from the message metadata and the model’s defined context window, allowing you to easily visualize or enforce token limits in your UI.

This is particularly useful when building chat interfaces or tools that need to display usage progress, disable input when nearing the limit, or warn users about potential truncation.

Usage

useTokenContext is simple to use, and needs only the messages in the chat + the canonical slug for the currently selected model.

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

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

  const context = useTokenContext({ messages, canonicalSlug: 'openai/gpt-5' }); 
};
A canonical slug is a string composed of the provider and model id, split by a slash /. Needed for correct look-up in model registry.

Here, context is an object with three keys:

  1. data: All data related to token context.
  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 useTokenContext 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