Strict Structured Output#
ContextGem builds the JSON schema of each extraction from its aspects and concepts, and checks each answer of an LLM against it: an answer that does not match is requested again (see š How Failed Requests Are Retried). With strict_structured_output=True, a DocumentLLM also sends that schema in the request of each extraction of aspects and concepts, as a strict response_format, so that the provider returns JSON that matches it:
from contextgem import DocumentLLM
llm = DocumentLLM(
model="openai/gpt-6-luna",
api_key="<your-openai-api-key>",
# The provider is asked to return JSON that matches the schema of each
# extraction, which ContextGem builds from the aspects and concepts
strict_structured_output=True,
)
The setting is off by default, and needs a model whose provider supports strict JSON schemas, through LiteLLM. It does not apply to chat().
ContextGem still checks each answer. The schema fixes the structure of the answer, the types that the values can have and the IDs of the aspects and concepts. ContextGem checks the rest as it does without the setting, e.g. that a date can be parsed, that a rating is within its range and that each reference is a paragraph or a sentence of the document. A strict schema does not make the extracted values true.
The schema is never dropped from a request.
If the provider rejects it, the request fails, and the fallback models are tried.
If litellm reports that the model does not support a sampling param, the seed or the reasoning effort, e.g. a temperature other than its default one, the request is sent again without that param and with the schema. Other params that the model does not support make the request fail.
litellmās global
drop_paramssetting would let it drop the schema, so a request with the schema raisesValueErrorwhilelitellm.drop_paramsisTrue. A LiteLLM proxy has its owndrop_paramssetting, which must be off too.
Fallback models. A fallback LLM must have the same strict_structured_output setting as the LLM it is a fallback for. A decision model can be the fallback model of an LLM with strict structured output, as it sends no JSON schema (see Decision Models).
JSON object concepts. The structure of a JsonObjectConcept is part of the schema. An optional field, e.g. str | None, is required in the schema with a type that allows null: the provider gives null for a value that the document does not give, which is None in the extracted item. A structure with arbitrary keys, e.g. dict[str, str], cannot have a strict schema: its extraction raises ValueError before the request is sent. Give such a concept fixed fields, or extract it with an LLM without strict structured output.