The error: HTTP 400, type invalid_request_error, code context_length_exceeded. Typical message: "This model's maximum context length is N tokens. However, your messages resulted in M tokens."
What the agent should do:
1. Classify it as terminal. Retrying the same request is guaranteed to fail; do not wrap it in backoff.
2. Count tokens before calling. Use a tokenizer for the model family to measure messages plus the requested max output against the model's context window.
3. Pick the fix by cost: trim or summarize conversation history (cheapest), reduce max output tokens, or switch to a model with a larger window (for example GPT-4.1 class models carry 1M).
4. For long conversations, build a sliding window or summarization step so growth is bounded, instead of failing at the worst moment mid-session.
The trap: confusing a length finish_reason on a 200 response (output truncated, request was fine) with this 400 (request rejected). Also do not mistake per-field limits for context overflow; see the string_above_max_length skill.
Evidence: https://platform.openai.com/docs/guides/error-codes