Lesson 1 of 4 Troubleshooting GenAI Applications

Diagnosing Context Window Overflow and Truncation

This lesson covers diagnosis and remedies for content handling problems: inputs that exceed the context window, frameworks that silently drop content, and responses that are cut off.

Learning outcomes

After completing this lesson, you will be able to:

  • Diagnose context window overflow.
  • Recognize truncation from the max_tokens stop reason.
  • Fit content to the budget with dynamic chunking and prompt design.

Diagnosing context window overflow

Context window overflow occurs when system prompt, conversation history, retrieved context, tool definitions and the requested output together exceed the model's limit. Bedrock rejects such requests with a ValidationException describing the input as too long. Some frameworks and applications instead truncate silently, dropping old history or the end of a document, which shows up as answers that ignore information the user provided. Diagnosis compares token counts (from the usage field, invocation logs or estimation) with the model's documented limit and inspects what was actually sent.

The following diagram shows the parts of a request that share the context window.

Context window overflow. The system prompt, conversation history, retrieved context, tool definitions and the requested output together exceed the model's limit. Bedrock rejects the request with a ValidationException, while some frameworks truncate silently, dropping old history or the end of a document.
The proportions are schematic.
Fix the problem

Context that does not fit

Exam skills 5.2.1

Find the fix for each context window problem.

Log in to try this activity Interactive activities are free with an account.

Truncation-related error analysis

When the response is cut off, the stopReason is max_tokens: the output reached the maxTokens limit. Symptoms include sentences ending mid-word, incomplete lists and invalid JSON missing its closing braces. Remedies are to raise maxTokens within the model's output limit, ask for more concise output, generate long content in sections, or request structured output with fewer fields. Applications should always check the stop reason rather than assuming a complete response.

r = brt.converse(modelId=model_id, messages=messages, inferenceConfig={"maxTokens": 400})
if r["stopReason"] == "max_tokens":
    log.warning("Truncated response", extra={"requestId": r["ResponseMetadata"]["RequestId"],
                                             "outputTokens": r["usage"]["outputTokens"]})
    # retry with a higher limit, ask for a shorter answer, or continue generation

The following diagram matches each symptom to its fix.

Diagnosing incomplete contract analysis from invocation logs. JSON parse failures had stopReason max_tokens, so maxTokens is raised and each call extracts fewer fields. ValidationExceptions came from inputs above the context window, so long contracts are processed section by section with a final combining step.
Invocation logs distinguished the two problems.

Dynamic chunking and prompt design

Dynamic chunking strategies adapt content to the remaining budget: compute the tokens available after the system prompt, history and expected output, then choose how many retrieved chunks to include, or split a long document into parts for map-reduce processing. Conversation history is summarised once it exceeds a threshold. Prompt design optimisation removes redundant instructions and examples, moves long reference material into retrieval rather than the system prompt, and places critical instructions at the start and repeated at the end, because models attend less reliably to the middle of very long contexts. A model with a larger context window is an option, at higher cost and latency. The following table summarises symptoms and remedies.

SymptomCauseRemedy
ValidationException: input too longContext window exceededFewer chunks, summarised history, map-reduce, larger-context model
Answers ignore early conversation detailsSilent history truncationRunning summary; store key facts as session attributes
Response ends mid-sentence; stopReason max_tokensOutput limit reachedRaise maxTokens; request concise output; generate in sections
Invalid JSON at the endTruncated structured outputRaise maxTokens; fewer fields; validate and retry
Instructions ignored in long promptsLost in the middleInstructions at start and end; shorter context
Fill in the number

Budgeting the context window

Exam skills 5.2.1

Work out how many retrieved chunks fit in the remaining context budget.

Log in to try this activity Interactive activities are free with an account.
Worked example

Incomplete contract analysis

A contract analysis feature sometimes returns JSON that fails to parse, and long contracts produce a ValidationException.

Invocation logs show stopReason max_tokens on the parse failures and inputs above the context window on the exceptions. The fix raises maxTokens for the extraction step, reduces fields per call, and processes long contracts section by section with a final combining step.

Check yourself

What should code check before parsing a model response?

Show answer

The stopReason, to confirm the output was not truncated.

Exam Tips

Remember for the exam

  • Input too long: ValidationException; compare token counts with the context window.
  • stopReason max_tokens: output truncated; raise maxTokens or shorten output.
  • Always check stopReason before parsing output.
  • Fit content dynamically: fewer chunks, summarised history, map-reduce.