{"record":{"id":"a73256fc049c06c1","repo":"affaan-m/ECC","slug":"contextlengtherror-msg-provider-providertype-claude-from-e","errorCode":null,"errorMessage":"ContextLengthError(msg, provider=ProviderType.CLAUDE) from e","messagePattern":"ContextLengthError\\(msg, provider=ProviderType\\.CLAUDE\\) from e","errorType":"exception","errorClass":"ContextLengthError","httpStatus":null,"severity":"error","filePath":"src/llm/providers/claude.py","lineNumber":132,"sourceCode":"                model=response.model,\n                usage={\n                    \"input_tokens\": response.usage.input_tokens,\n                    \"output_tokens\": response.usage.output_tokens,\n                    \"cache_creation_input_tokens\": getattr(\n                        response.usage, \"cache_creation_input_tokens\", 0\n                    ),\n                    \"cache_read_input_tokens\": getattr(response.usage, \"cache_read_input_tokens\", 0),\n                },\n                stop_reason=response.stop_reason,\n            )\n        except Exception as e:\n            msg = str(e)\n            if \"401\" in msg or \"authentication\" in msg.lower():\n                raise AuthenticationError(msg, provider=ProviderType.CLAUDE) from e\n            if \"429\" in msg or \"rate_limit\" in msg.lower():\n                raise RateLimitError(msg, provider=ProviderType.CLAUDE) from e\n            if \"context\" in msg.lower() and \"length\" in msg.lower():\n                raise ContextLengthError(msg, provider=ProviderType.CLAUDE) from e\n            raise\n\n    def list_models(self) -> list[ModelInfo]:\n        return self._models.copy()\n\n    def validate_config(self) -> bool:\n        return bool(self.client.api_key)\n\n    def get_default_model(self) -> str:\n        return _DEFAULT_MODEL\n","sourceCodeStart":114,"sourceCodeEnd":143,"githubUrl":"https://github.com/affaan-m/ECC/blob/8321021c54d670126ce3b2969d5deb880b4b0c2a/src/llm/providers/claude.py#L114-L143","documentation":"The Claude LLM provider wraps all exceptions from its generate() call and re-raises them as typed provider errors. When the underlying Claude API error message contains both the words 'context' and 'length', the provider concludes the request exceeded the model's context window and raises ContextLengthError, preserving the original exception with 'from e'.","triggerScenarios":"Calling provider.generate() where the combined prompt + history + max_tokens exceeds the Claude model's context window; the SDK raises an error whose string form contains 'context ... length'.","commonSituations":"Feeding whole documents or long transcripts into the prompt; accumulating chat history without truncation; passing a large system prompt plus a large max_tokens; using a model with a smaller window than assumed (e.g. switching from a 200k model to a smaller one).","solutions":["Reduce the prompt size: truncate or summarize conversation history before sending","Lower input.max_tokens so prompt + max_tokens fits the model window","Use a model variant with a larger context window","Count tokens client-side (e.g. a tokenizer) before calling generate and reject oversized requests early"],"exampleFix":"// before\nresp = provider.generate(LLMInput(prompt=full_transcript))\n// after\nMAX_CHARS = 100_000\nresp = provider.generate(LLMInput(prompt=full_transcript[-MAX_CHARS:]))","handlingStrategy":"try-catch","validationCode":"def fits_context(text, max_model_tokens, max_output):\n    approx_tokens = len(text) // 4  # rough estimate; use a tokenizer for accuracy\n    return approx_tokens + max_output <= max_model_tokens","typeGuard":null,"tryCatchPattern":"try:\n    resp = provider.generate(inp)\nexcept ContextLengthError as e:\n    logger.warning(\"Prompt too long for model, truncating\")\n    inp = replace(inp, prompt=inp.prompt[-len(inp.prompt)//2:])\n    resp = provider.generate(inp)","preventionTips":["Estimate or count tokens before every generate call","Trim conversation history to a rolling window","Keep max_tokens well below the model's window","Pin the model and know its exact context limit"],"tags":["llm","context-window","claude"],"backgroundTag":"context-length-exceeded","analyzedSha":"8321021c54d670126ce3b2969d5deb880b4b0c2a","analyzedAt":"2026-09-16T10:08:13.343Z","contentChangedAt":"2026-09-16T10:08:13.343Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}