Accurate Billing and Usage Tracking for Thinking Tokens

FreeAPIDeepSeek · Updated 2026-11-24 · 14 min read

Server rack with blinking lights
Proxy infrastructure handles high-throughput data streams.

Proxy infrastructure is undergoing a quiet but significant shift. As models adopt internal reasoning chains, the traditional single-stream response model no longer reflects reality. When a model thinks before it speaks, the token count doubles, and with it, the cost structure changes. If your proxy simply counts every token in the stream as billable content, you are likely overcharging users or underbilling your own infrastructure. The distinction between 'thinking' tokens and 'final' tokens is no longer optional; it is a requirement for fair usage tracking.

The core challenge lies in parsing Server-Sent Events (SSE) correctly. Reasoning tokens often appear in a separate stream or within specific tags, distinct from the final answer. A naive parser that sums all tokens will misrepresent the model's actual output length. This guide walks you through the mechanics of separating these streams, handling the metadata, and ensuring your billing logic accurately reflects what the user actually receives. You will learn how to intercept, classify, and log these tokens without adding significant latency to your proxy layer.

We will focus on practical implementation details, using Python as the primary example for clarity, though the concepts apply to Go, Rust, or any language capable of handling HTTP streams. You will see how to structure your data models to capture both the reasoning phase and the content phase. By the end, you will have a clear strategy for tracking usage that aligns with modern reasoning models, ensuring your proxy remains both accurate and cost-effective. This is not just about billing; it is about understanding the true cost of intelligence. Note that while the domain contains the brand DeepSeek, this site is not affiliated with DeepSeek.

Frequently asked questions

What are reasoning tokens?

Reasoning tokens are the internal thought process tokens generated by a model before it produces the final answer. They are often enclosed in tags or sent in a separate stream segment. Unlike content tokens, which form the visible response, reasoning tokens represent the model's deliberation. They are critical for complex tasks but should be tracked separately for accurate billing.

How do reasoning tokens differ from content tokens?

Content tokens form the final, visible response to the user's prompt. Reasoning tokens are the intermediate steps the model takes to arrive at that answer. Content tokens are usually what users expect to pay for, while reasoning tokens represent the 'cost of thinking'. Separating them allows for tiered billing and better usage insights.

Why is billing for reasoning tokens important?

Billing for reasoning tokens prevents overcharging users for internal model work. If you charge for all tokens indiscriminately, users pay for the model's 'thought process' even if they only care about the final answer. Accurate billing builds trust and allows you to offer flexible pricing models based on reasoning depth.

Which is better: counting all tokens or only content tokens?

Counting only content tokens is generally fairer for users who only consume the final answer. However, counting all tokens reflects the true computational cost. The best approach depends on your business model. For free services, counting all tokens ensures sustainability. For paid services, separating them allows for premium reasoning tiers.

How do I parse SSE streams for reasoning tokens?

Intercept the SSE stream and look for specific tags like <thought> or <reasoning>. Parse the content within these tags as reasoning tokens. Everything outside these tags is content. Use a state machine to track whether you are inside or outside a reasoning block. This ensures accurate token classification.

What is the impact of reasoning tokens on latency?

Reasoning tokens add to the total time before the final answer appears. However, the parsing overhead in your proxy should be minimal. A well-optimized proxy can parse reasoning tokens in under 1ms. The latency is primarily due to the model's generation time, not your proxy's parsing logic.

Can I filter out reasoning tokens for the user?

Yes, you can filter out reasoning tokens before sending the response to the user. This is useful for applications where the thought process is irrelevant. However, keep the tokens in your logs for billing and debugging purposes. Filtering them from the UI does not change the cost incurred by the model.

How do I handle partial reasoning tokens?

Partial reasoning tokens are incomplete thoughts sent before the final reasoning block closes. Count them as reasoning tokens. Ensure your parser handles incomplete blocks gracefully. If a reasoning block is cut off, treat the remaining tokens as content or discard them based on your policy. Consistency is key.

Step by step

  1. Identify Stream Format — Determine if your model uses tags or separate streams for reasoning tokens. Check the API documentation or test with a sample request.
  2. Implement Parser — Write a parser that intercepts the SSE stream and identifies reasoning tags. Use a state machine to track the state of the parser.
  3. Count Tokens — Implement logic to count reasoning and content tokens separately. Log these counts for each request.
  4. Update Billing — Adjust your billing logic to account for the separate token counts. Offer flexible pricing based on reasoning depth.
  5. Test and Debug — Test your proxy with various requests and models. Debug any issues with token classification or counting.
  6. Monitor Performance — Monitor your proxy's performance and accuracy. Use logs and dashboards to track usage and detect anomalies.

Understanding the Stream Structure

The foundation of handling reasoning tokens lies in understanding how the model outputs data. Modern reasoning models often use a distinct format for their internal thought process. This is typically achieved through specific XML-like tags or a separate stream segment. When you send a request to the API, the response is not a single monolithic block of text. Instead, it is a stream of events. Each event contains a portion of the model's output. Some events contain reasoning tokens, while others contain content tokens. Recognizing this structure is the first step in building a robust proxy.

A naive proxy might simply concatenate all tokens from the stream and count them. This approach fails to distinguish between the model's 'thinking' and its 'speaking'. For billing purposes, this can lead to significant inaccuracies. If a model spends 1,000 tokens thinking and 100 tokens answering, counting all 1,100 tokens as content is misleading. By understanding the stream structure, you can build a parser that accurately classifies each token, ensuring your usage logs reflect the true nature of the interaction.

Identifying Reasoning Tags

Most reasoning models use specific tags to delimit their internal thoughts. Common tags include <thought>, <reasoning>, or <thinking>. Your parser should look for these tags to identify the start and end of a reasoning block. Anything between these tags is considered a reasoning token. Anything outside is content. This simple rule forms the basis of your token classification logic.

Stream Segmentation

In some implementations, reasoning tokens are sent in a separate stream segment. This means the API might send a chunk of reasoning tokens, followed by a chunk of content tokens. Your proxy needs to handle both cases: tags within a single stream and separate stream segments. A robust parser will check for both patterns to ensure no tokens are misclassified.

Parsing the SSE Stream

Server-Sent Events (SSE) are the standard for streaming responses from LLM APIs. Each event in the SSE stream contains a data field with a chunk of text. Your proxy must parse these events in real-time. The challenge is to maintain state across events. You need to track whether you are currently inside a reasoning block or not. This state determines how you classify each token. A simple boolean flag can suffice, but a state machine is more robust, especially if your model supports nested reasoning blocks or multiple reasoning phases.

Once you have identified a token as reasoning or content, you need to decide what to do with it. For billing, you might want to log both counts separately. For the user, you might want to display only the content tokens. Your proxy acts as the intermediary, filtering and transforming the stream as needed. The parsing logic must be efficient to avoid adding significant latency. A well-optimized parser can handle thousands of tokens per second with minimal overhead.

State Machine Implementation

A state machine helps manage the complexity of parsing. You can define states like 'IDLE', 'IN_THOUGHT', and 'IN_CONTENT'. When you encounter a reasoning tag, transition to 'IN_THOUGHT'. When you encounter the closing tag, transition back to 'IDLE' or 'IN_CONTENT'. This ensures that tokens are correctly classified even if the stream is interrupted or reordered.

Handling Partial Chunks

SSE events often split tokens across multiple chunks. A reasoning tag might start in one chunk and end in another. Your parser needs to handle these partial chunks gracefully. Buffer incomplete tags and only process them when they are complete. This prevents misclassification of tokens that are split across event boundaries.

Whiteboard with state machine diagram
State machines help manage complex parsing logic.

Billing and Usage Tracking

Accurate billing is the primary reason for separating reasoning tokens. If you charge users based on total tokens, you are effectively subsidizing their thinking process. By tracking reasoning and content tokens separately, you can offer more granular pricing. For example, you might charge less for reasoning tokens since they are often internal to the model's process. Or you might offer a premium tier that includes unlimited reasoning. The key is transparency. Users should know exactly what they are paying for.

Usage tracking also provides valuable insights. By analyzing the ratio of reasoning to content tokens, you can understand how your models are performing. Models that generate long reasoning chains might be better suited for complex tasks. Models that generate short reasoning chains might be faster and cheaper. This data can help you optimize your model selection and pricing strategy. It also helps you detect anomalies, such as a model getting stuck in a long reasoning loop.

Token Counting Logic

Implement a simple counter for each type of token. Increment the reasoning counter when you parse a reasoning token, and the content counter for content tokens. These counters should be reset for each request. Store them in a database or cache for later retrieval. This allows you to generate detailed usage reports for each user.

Cost Calculation

Calculate the cost based on the token counts and your pricing model. If you charge per token, multiply the counts by the respective rates. If you have a flat rate, use the total count. Ensure your cost calculation is consistent with your billing policy. Display the cost breakdown to the user, showing the cost of reasoning and content tokens separately. This builds trust and clarity.

Implementing the Proxy in Python

Python is a popular choice for building proxies due to its readability and rich ecosystem. Libraries like httpx or aiohttp make it easy to handle HTTP streams. In this section, we will outline a basic implementation using asyncio to parse the SSE stream. The code example demonstrates how to intercept the stream, identify reasoning tags, and count tokens. This is a starting point; you will need to adapt it to your specific use case and model format.

The implementation focuses on clarity rather than performance. For production use, you might want to optimize the parsing logic using regular expressions or a dedicated parser. However, the core logic remains the same: identify the tags, maintain state, and count tokens. The example code uses a simple state machine to track whether it is inside a reasoning block. This approach is easy to understand and modify.

Async Stream Handling

Use asyncio to handle the SSE stream asynchronously. This allows your proxy to handle multiple requests simultaneously without blocking. Read the stream chunk by chunk, parsing each event as it arrives. This ensures low latency and high throughput. Asynchronous programming is essential for building scalable proxy services.

Regex vs. State Machine

Regular expressions can be used to identify tags, but a state machine is more robust. Regex might miss nested tags or handle partial chunks incorrectly. A state machine explicitly tracks the state of the parser, making it easier to debug and maintain. Use regex for simple tag detection, but rely on a state machine for complex parsing logic.

import asyncio
import aiohttp
import re

async def parse_stream(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            reasoning_tokens = 0
            content_tokens = 0
            in_thought = False
            async for line in response.content:
                line = line.decode('utf-8').strip()
                if line.startswith('data: '):
                    data = line[6:]
                    if '<thought>' in data:
                        in_thought = True
                    elif '</thought>' in data:
                        in_thought = False
                    if in_thought:
                        reasoning_tokens += len(data.split())
                    else:
                        content_tokens += len(data.split())
            print(f'Reasoning: {reasoning_tokens}, Content: {content_tokens}')
Stack of paper with numbers
Accurate token counting ensures fair billing.

Optimizing for Performance

Performance is critical for a proxy that handles high traffic. Parsing every token in real-time can be CPU-intensive. To optimize, consider using efficient data structures and algorithms. Regular expressions can be slow if not used carefully. Pre-compile regex patterns and use them efficiently. Also, consider buffering the stream to reduce the number of I/O operations. Buffering allows you to process larger chunks of data at once, reducing overhead.

Another optimization is to minimize the number of database writes. Instead of writing each token count to the database in real-time, batch the writes. This reduces the I/O load and improves performance. You can also use in-memory caches for frequently accessed data. This reduces the latency of reading usage data. However, ensure that your cache is consistent with your database to avoid discrepancies.

Buffering Strategies

Buffering the stream allows you to process data in larger chunks. This reduces the number of I/O operations and improves throughput. However, buffering introduces latency. Find a balance between buffering size and latency. A small buffer might be sufficient for most use cases, while a larger buffer might be needed for high-throughput scenarios.

Efficient Regex Usage

Pre-compile regular expressions to avoid recompiling them for each request. Use non-greedy matching to avoid unnecessary backtracking. Limit the scope of your regex to the specific tags you are looking for. This reduces the computational cost of pattern matching. Efficient regex usage can significantly improve the performance of your parser.

Handling Edge Cases

Real-world streams are messy. Tags might be malformed, streams might be interrupted, and models might behave unexpectedly. Your proxy needs to handle these edge cases gracefully. For example, a reasoning tag might not be closed properly. Your parser should handle this by either discarding the remaining tokens or treating them as content. Similarly, if a stream is interrupted, your proxy should handle the error without crashing.

Another edge case is when the model generates reasoning tokens but does not use tags. Some models might use a different format for reasoning. Your parser should be flexible enough to handle different formats. You can configure the parser to use different tags or patterns based on the model being used. This flexibility ensures that your proxy works with a variety of models.

Malformed Tags

Handle malformed tags by implementing a fallback strategy. If a tag is not closed, treat the remaining tokens as content. This prevents your parser from getting stuck in a reasoning state indefinitely. Log a warning when a malformed tag is detected, so you can investigate the issue later.

Stream Interruption

If the stream is interrupted, your proxy should handle the error gracefully. Retry the request if possible, or return an error to the user. Ensure that your token counts are accurate up to the point of interruption. Do not lose the tokens that were already processed. This ensures that your billing is accurate even if the request fails.

Computer screen with Python code
Python is a popular choice for building proxies.

Monitoring and Debugging

Once your proxy is running, you need to monitor its performance and accuracy. Log the token counts for each request. This allows you to verify that your parser is working correctly. If the token counts seem off, investigate the logs to identify the issue. You might find that certain models have a different format for reasoning tokens. Adjust your parser accordingly.

Debugging can be challenging, especially when dealing with streams. Use logging to track the state of your parser. Log the tags encountered, the state transitions, and the token counts. This provides a detailed trace of the parsing process. You can use this trace to identify where the parser went wrong. Debugging tools like pdb or logging frameworks can help you step through the code and identify issues.

Logging Token Counts

Log the reasoning and content token counts for each request. This provides a clear record of usage. Use these logs to generate reports and detect anomalies. If a request has an unusually high number of reasoning tokens, investigate whether the model is stuck in a loop. Logging is essential for maintaining a healthy proxy.

Visualizing Usage

Use dashboards to visualize usage data. Show the ratio of reasoning to content tokens over time. This helps you understand the behavior of your models. If the ratio changes significantly, it might indicate a change in the model's behavior or a bug in your parser. Visualizing usage data makes it easier to spot trends and issues.

Future-Proofing Your Proxy

The landscape of LLMs is evolving rapidly. New models might introduce new formats for reasoning tokens. Your proxy should be designed to be flexible and adaptable. Use configuration files to define the tags and patterns for different models. This allows you to update your proxy without changing the core code. As new models emerge, you can easily add support for them by updating the configuration.

Consider the long-term implications of reasoning tokens. As models become more capable, the amount of reasoning they generate might increase. This could have a significant impact on your costs. Plan for this by offering flexible pricing models that account for reasoning tokens. You might also consider caching reasoning tokens to reduce costs for repeated queries. Future-proofing your proxy ensures it remains relevant and cost-effective as the technology evolves. For more on agent loops, see Why Does My Agent Loop the Same Tool Call? and How to Budget Tokens for Stateless Agent Loops.

Configuration-Driven Parsing

Use configuration files to define the tags and patterns for reasoning tokens. This allows you to update the parsing logic without changing the code. Store the configuration in a database or a config file. This makes it easy to manage different models and their specific requirements. Configuration-driven parsing is a best practice for building flexible proxies.

Caching Reasoning

Cache reasoning tokens for repeated queries. If a user asks the same question multiple times, you can reuse the reasoning tokens. This reduces the computational cost and improves response times. However, be careful not to cache reasoning tokens that are dependent on the context. Ensure your cache key includes the full context of the request.

Dashboard with usage statistics
Dashboards help visualize usage trends.
Try the free API

Test stateless loops and tool calls instantly with our keyless endpoint.

Read also