Skip to content

Monitoring Context Window: Metrics and Alerts

Cover: Monitoring Context Window: Metrics and Alerts The context window is the most expensive resource in an LLM API. When it overflows, the model starts to 'forget' the beginning of the dialogue, the quality of responses drops, and costs rise. Below is how to build a context window monitoring system that warns about problems before they become critical.

Why Context Monitoring Is Important

Most LLM APIs charge for incoming and outgoing tokens. The more context, the higher the cost of each request. But the problem is not just about money. When the context window overflows, the model loses information from the beginning of the dialogue — this is called the 'lost middle' effect. The user asks about something discussed at the beginning, but the model no longer remembers.

Without monitoring, you only find out about the problem through user complaints or a suddenly high API bill. With the right metrics and alerts, you can react proactively.

What Metrics to Collect

Four key metrics are collected for each request.

1. Input Tokens

The number of tokens in the incoming request. This includes the system prompt, dialogue history, tools, and user input.

2. Output Tokens

The number of tokens in the model's response. Important for cost calculation and understanding whether the model is generating overly long responses.

3. Total Tokens

The sum of input and output tokens. Shows the overall load on the model.

4. Context Utilization

Percentage of context window usage. Calculated as input_tokens / context_window_size * 100. This is the main metric for alerts.

How to Set Up Metric Collection

A middleware layer is used between the application and the LLM API. It intercepts each request and response, extracts metadata, and sends it to the monitoring system.

import time
from dataclasses import dataclass

@dataclass
class ContextMetrics:
    input_tokens: int
    output_tokens: int
    total_tokens: int
    context_window_size: int
    utilization_percent: float
    latency_ms: float
    timestamp: float

def collect_metrics(response, context_window_size: int) -> ContextMetrics:
    usage = response.usage
    input_tokens = usage.prompt_tokens
    output_tokens = usage.completion_tokens
    total_tokens = usage.total_tokens
    utilization = (input_tokens / context_window_size) * 100
    return ContextMetrics(
        input_tokens=input_tokens,
        output_tokens=output_tokens,
        total_tokens=total_tokens,
        context_window_size=context_window_size,
        utilization_percent=round(utilization, 2),
        latency_ms=response.response_ms,
        timestamp=time.time()
    )

These metrics are sent to the observability system using tracing.

Setting Up Alerts

Alerts should trigger based on threshold values. Three levels are used.

Level Threshold Action
Warning utilization > 70% Log warning, send to dashboard
Critical utilization > 90% Send alert to Telegram, enable context compression mode
Emergency utilization > 100% Stop request, return error to client
def check_context_threshold(metrics: ContextMetrics) -> str | None:
    if metrics.utilization_percent > 90:
        return "critical"
    if metrics.utilization_percent > 70:
        return "warning"
    return None

When a critical alert triggers, a context compression procedure is launched: old dialogue messages are summarized and replaced with a brief summary. This allows continuing work without losing key information.

Strategies to Prevent Overflow

Monitoring is a reaction to the problem. To prevent it, several strategies are used.

Limiting Dialogue History

Not all messages are stored, only the last N. Old messages are either deleted or summarized.

Compressing the System Prompt

The system prompt can take up a significant part of the context. It is regularly reviewed, and unnecessary parts removed. More details in the system prompt guide.

Dynamic Model Selection

For short dialogues, a model with a small context window is used; for long ones, a large one. This allows saving on short requests and not losing quality on long ones.

Token Budgeting

A token budget is set for each dialogue. When the budget is exhausted, the application offers the user to start a new dialogue. More details in the context window management guide.

Dashboard Example

A dashboard is built with three graphs.

  1. Input tokens over time — shows the dynamics of context growth.
  2. Context utilization per dialogue — identifies dialogues approaching the limit.
  3. Cost per dialogue — links context usage to costs.
graph LR
    A[LLM API] -->|response| B[Middleware]
    B -->|metrics| C[Metrics Store]
    C --> D[Dashboard]
    C --> E[Alerting]
    E -->|critical| F[Compression Job]
    F -->|summarized context| A

Conclusion

Monitoring the context window is an essential part of production with LLM API. It helps control costs, prevent quality degradation, and react in time to anomalies. Start with simple metric collection and alerting on threshold values, then add automatic context compression.

For a deeper understanding of observability metrics, refer to the LLM Observability Metrics Glossary. If you want to learn about context caching for cost savings, read the article on prompt caching strategies.