Exceptions and Warnings#
Module exposing the exceptions that the framework raises to the calling code, the exception that a tool function raises for the LLM, and the category of the warnings that the framework issues.
The exceptions are the classes that the framework itself raises, so they can be
used in except clauses: from contextgem import ModelAPIError, or
ContextGemError, their base class, to catch any of them. ToolCallError is
raised by a tool function, to send its message to the LLM in a chat. Likewise,
the warning category is the one of the warnings that the framework issues, so it
can be used in warning filters: from contextgem import ContextGemWarning, or
UnknownPricesWarning, its subclass, for the warning on a model whose costs
cannot be calculated.
- exception contextgem.public.exceptions.ContextGemError(message, retry_count=None, original_error=None)[source]#
Bases:
ExceptionBase class of the exceptions that the framework raises when a run fails, i.e. of
ModelAPIError,ModelExtractionError(with its subclassModelRefusalError) andLLMToolLoopLimitError. Catch it to handle any of them in one clause, e.g.except ContextGemError.An error in the calling code, e.g. an invalid argument or an object that cannot be used where it is passed, is raised as
ValueErrororTypeErrorinstead, which includes theValidationErrorof pydantic, a subclass ofValueError. A file that cannot be read or written, e.g. byfrom_disk()orto_disk(), raisesOSError.Can be imported from
contextgem.- Variables:
- Parameters:
Initialize the exception.
- exception contextgem.public.exceptions.ModelAPIError(message, retry_count=None, original_error=None)[source]#
Bases:
contextgem.internal.exceptions.ContextGemErrorException raised when a request to a model fails for good, and there is no fallback model left to try.
This is the case when:
the request fails with a non-transient error, e.g. an invalid request or a failed authentication;
the request fails with a transient error (request timeout, rate limit, server or connection error), also after
num_retries_failed_requestretries;the response of an LLM is cut off at the max output tokens during extraction, which is not requested again, or is empty in a chat, also after the request was sent again
max_retries_invalid_datatimes.
A request that the provider blocks for its content, or whose answer it blocks, is a refusal, which raises
ModelRefusalError.During extraction, if
raise_exception_on_extraction_error=Falseis passed to the extraction method, a warning is logged instead.Can be imported from
contextgem.- Variables:
message (str) – Human-readable error description
retry_count (int or None) – Number of retries attempted for the failed request, or, for an empty response in a chat, the number of times that the request was sent again. None for a response cut off at the max output tokens during extraction, which is not requested again.
original_error (Exception or None) – The underlying exception that caused the failure, of
litellmfor a failed request. None for a response that is cut off or empty, which the message describes.
- Parameters:
Initialize the exception.
- exception contextgem.public.exceptions.ModelExtractionError(message, retry_count=None, original_error=None)[source]#
Bases:
contextgem.internal.exceptions.ContextGemErrorException raised by the extraction methods when a model returns data that cannot be used, and there is no fallback model left to try.
This is the case when:
the response of an LLM cannot be parsed or validated, also after the LLM was asked again
max_retries_invalid_datatimes;the response of a decision model cannot be used, e.g. an answer without valid probabilities, also after the requests whose answers cannot be used were sent again
max_retries_invalid_datatimes;the model or its provider declined to answer, also after the retries and the fallback models: then the subclass
ModelRefusalErroris raised.
If
raise_exception_on_extraction_error=Falseis passed to the extraction method, a warning is logged instead.Can be imported from
contextgem.- Variables:
message (str) – Human-readable error description
retry_count (int or None) – Number of times that the model the error is for, i.e. the last model that was tried, was called again after it returned invalid data. The first call of the model, also of a fallback model, is not counted.
original_error (Exception or None) – The underlying exception that caused the failure
- Parameters:
Initialize the exception.
- exception contextgem.public.exceptions.ModelRefusalError(message, retry_count=None, original_error=None)[source]#
Bases:
contextgem.internal.exceptions.ModelExtractionErrorException raised when a model or its provider declined to answer, in extraction and in chat, and there is no retry and no fallback model left to try:
the model refused to answer, e.g. an LLM of OpenAI with its
refusalfield, or a decision model with a refused answer to a question of a concept, or to the question of an aspect on every paragraph;the content filter of the provider stopped the answer, which litellm reports with the
content_filterfinish reason for all the providers, e.g. for a refusal of a Claude model, the safety filters of Gemini and of Azure OpenAI, and the guardrails of Amazon Bedrock;the provider blocked the request or its answer for their content, which litellm raises as
litellm.ContentPolicyViolationErrorfor both, e.g. the content filter of Azure OpenAI on a prompt, or a blocked answer of a Gemini or a Claude model on Vertex AI.
litellm reports a model’s refusal and a content filter with the same finish reason, i.e. the message cannot always tell them apart. It also reports a question that a decision model left unanswered as a refused answer.
The answer of a refused request is not used, also if it is valid JSON. A refusal is asked for again as invalid data is, up to
max_retries_invalid_datatimes, as the verdict of a model or of a content filter can differ on another request, and then from the fallback models, each with its own retries. In a chat, a refused answer that has a text is returned as it is, with a warning logged, while a refused answer without a text, or a blocked request, is asked for again as an empty answer is, and then from the next fallback LLM.As a subclass of
ModelExtractionError, it is caught byexcept ModelExtractionErrorandexcept ContextGemError. Ifraise_exception_on_extraction_error=Falseis passed to the extraction method, a warning is logged instead, and the aspects or concepts of the call get no items.The message names the model and what declined the answer. It never has the answer of the model or the text of the document.
Can be imported from
contextgem.- Variables:
message (str) – Human-readable error description
retry_count (int or None) – Number of times that the model the error is for, i.e. the last model that was tried, was called again, as for
ModelExtractionError. In a chat, the number of times that the request was sent again.original_error (Exception or None) – The exception of litellm for a request or an answer that the provider blocked (
litellm.ContentPolicyViolationError), of the last request that was sent, None otherwise
- Parameters:
Initialize the exception.
- exception contextgem.public.exceptions.LLMToolLoopLimitError(message, retry_count=None, original_error=None)[source]#
Bases:
contextgem.internal.exceptions.ContextGemErrorException raised from a chat when the tool-calling loop reaches the configured
tool_max_roundslimit and the LLM continues requesting tools.Typically indicates that the LLM is stuck in a loop or needs more rounds to complete the workflow. Consider increasing
tool_max_roundsor adjusting the tool instructions or the tool choice.Can be imported from
contextgem.Initialize the exception.
- exception contextgem.public.exceptions.ToolCallError[source]#
Bases:
ExceptionException that a tool function raises to tell the LLM why its call failed, e.g. that no record has the ID that the LLM passed. The chat goes on: the message of the exception is sent to the LLM in the result of the tool call,
{"error": "ToolCallError", "message": "<the message>"}, and the LLM can call the tool again in the next round.Any other exception that a tool function raises is an error in the function, e.g. a bug, and is raised from
chat()as it is, with a note that names the tool: its message is not sent to the LLM, no further requests are sent, and no fallback LLM is tried.The message is sent unchanged: write it for the LLM, and keep out of it what the LLM should not receive.
Not a subclass of
ContextGemError, which is the base of the errors that the framework raises: the framework does not raise this one, but sends its message to the LLM.Can be imported from
contextgem.
- exception contextgem.public.exceptions.ContextGemWarning[source]#
Bases:
UserWarningCategory of the warnings that the framework issues for something in the calling code that will not have the expected effect, e.g. tools set on an LLM that is used for extraction, or an output language set together with a custom system message. Such a warning is attributed to the line of the calling code that caused it, where possible.
The warnings are Python warnings, not log messages, i.e. the logging level does not affect them. To filter them, use this category, e.g.
warnings.filterwarnings("ignore", category=ContextGemWarning), or make them errors, e.g. in the tests of the calling code: a filter by the module of the framework does not match a warning attributed to the calling code. What happens while the framework runs, e.g. an extraction that fails whenraise_exception_on_extraction_error=Falseis passed to the extraction method, is logged instead.Can be imported from
contextgem.
- exception contextgem.public.exceptions.UnknownPricesWarning[source]#
Bases:
contextgem.internal.exceptions.ContextGemWarningCategory of the warning that the framework issues for a model whose costs it cannot calculate: a model with
auto_pricing=Truethatgenai-priceshas no prices for. The warning is issued when such a model is created, or when itsmodelorauto_pricingis assigned, and again when the usage of its calls is recorded. The costs of the model stay at zero.To keep such a model from running, e.g. where its costs count against a budget of your own, make the warning an error:
warnings.filterwarnings("error", category=UnknownPricesWarning). The model then raises where it is created, and a model created before the filter is set stops the extraction method after the usage of the call is recorded. A subclass ofContextGemWarning, which a filter on that category matches as well.Can be imported from
contextgem.