Skip to main content

enterprise_ai.llm.context

Source: sdks/python/src/enterprise_ai/llm/context/__init__.py. Back to the Python SDK reference index.

note

This page is generated by tools/docs/gen_sdk_reference.py from the SDK sources and the OpenAPI text folders. Do not edit it by hand: change the source and regenerate.

Model ContextBudget​

Token budget of one model call.

Fields:

NameTypeRequiredDescription
windowintyesContext window of the model, in tokens.
output_reservedintnoTokens reserved for the model output.
reasoning_reservedintnoTokens reserved for the model reasoning.
safety_marginintnoTokens kept free as a safety margin.

Attributes:

NameTypeRequiredDescription
context_budgetintyesTokens available for input context.

ContextBudget.check​

check() -> ContextBudget

Raise :class:ContextOverflow when the reservations exceed the window.

This element takes no parameter.

Returns: ContextBudget. A ContextBudget: Token budget of one model call.

Raises: ContextOverflow.

ContextBudget.for_model​

for_model(model: dict[str, Any], effort: str | Effort | None = None, max_output_tokens: int | None = None, safety_ratio: float = 0.02, min_safety: int = 256) -> ContextBudget

Budget derived from a Model Manifest / registry entry and the requested effort.

NameTypeDefaultRequiredDescription
modeldict[str, Any]yesModel Manifest or registry entry; its spec.context_window gives the window.
effortstr | Effort | NoneNonenoRequested reasoning effort, used to size the reasoning reservation.
max_output_tokensint | NoneNonenoTokens reserved for the output; defaults to the model max_output_tokens capped at 4096.
safety_ratiofloat0.02noShare of the window kept as safety margin (default 0.02), at least min_safety.
min_safetyint256noMinimum safety margin in tokens (default 256).

Returns: ContextBudget. A ContextBudget: Token budget of one model call.

ContextBudget.to_dict​

to_dict(used: int = 0, estimator: str = 'heuristic:chars/4') -> dict[str, Any]

Budget as the budget block of the Context Contract.

NameTypeDefaultRequiredDescription
usedint0noTokens actually used by the context (default 0).
estimatorstr'heuristic:chars/4'noName of the token estimator recorded in the block (default heuristic:chars/4).

Returns: dict[str, Any]. Dict with window, output_reserved, reasoning_reserved, safety_margin, context_budget, used and estimator.

Model Segment​

One piece of context with its priority (0-100), classification and provenance.

Fields:

NameTypeRequiredDescription
contentstryesOriginal text of the segment.
typestrnoSegment type, such as system, prompt (default), history, tool_result or rag_document.
rolestrnoChat role of the message built from the segment (default user).
priorityintnoPriority of the segment from 0 to 100 (default 50): the higher ones are kept first when the budget is short.
classificationstrnoData classification, from public to secret (default internal).
provenancedict[str, Any] | NonenoSigned in-toto Statement v1 with a SLSA v1 predicate: {statement, signature: {value, signer}}.
segment_idstrnoIdentifier of the segment, 12 random hexadecimal characters by default.
compressibleboolnoSegment may be truncated, summarized or dropped when the budget is short.
cacheableboolnoSegment is part of the cacheable prompt prefix.
tokensintnoTokens counted for the segment after build (0 when dropped).
original_tokensintnoEstimated tokens of the original text.
includedboolnoSegment is kept in the built context.
compressionstrnoWhat build did to the segment: none, truncated, summarized or dropped.
content_outstrnoText sent to the model after build (original, truncated or summarized).

Model BuiltContext​

Output of :meth:ContextBuilder.build.

Fields:

NameTypeRequiredDescription
messageslist[dict[str, Any]]yesChat messages {role, content} of the included segments, in the order they were added.
contractdict[str, Any]yesContext Contract document: budget, segments with provenance, highest classification, compression actions and cache prefix.
segmentslist[Segment]yesEvery segment of the builder, with its final tokens, inclusion and compression mode.
usedintyesTokens used by the included segments, within the context budget.
budgetContextBudgetyesToken budget of one model call.

Class ContextBuilder​

Assemble a context within a :class:ContextBudget.

Attributes:

NameTypeRequiredDescription
budgetyesToken budget the context must fit in.
min_segment_tokensyesSmallest remaining budget, in tokens, worth compressing a segment into.
model_idyesModel identifier written in the Context Contract.
segmentslist[Segment]yesSegments added so far, in insertion order.
summarizeryesSummary function used instead of truncation, or None.
tenant_idyesTenant written in the Context Contract.

Constructor ContextBuilder​

ContextBuilder(budget: ContextBudget, model_id: str = 'unknown', tenant_id: str = 'local', summarizer: Callable[[str, int], str] | None = None, min_segment_tokens: int = 32) -> None

Create an empty builder for one model call within budget.

NameTypeDefaultRequiredDescription
budgetContextBudgetyesToken budget the context must fit in.
model_idstr'unknown'noModel identifier written in the Context Contract (default unknown).
tenant_idstr'local'noTenant written in the Context Contract (default local).
summarizerCallable[[str, int], str] | NoneNonenoFunction (text, target_tokens) -> str used to summarize a segment instead of truncating it.
min_segment_tokensint32noSmallest remaining budget, in tokens, worth compressing a segment into; below it the segment is dropped (default 32).

ContextBuilder.add​

add(content: str, type: str = 'prompt', role: str = 'user', priority: int = 50, classification: str = 'internal', source_type: str = 'user_input', source_id: str | None = None, compressible: bool = True, cacheable: bool = False, **provenance: Any) -> Segment

Add a segment and return it.

NameTypeDefaultRequiredDescription
contentstryesText of the segment.
typestr'prompt'noSegment type: system, prompt (default), history, tool_result, rag_document, memory, image, audio, video or file.
rolestr'user'noChat role of the message built from the segment (default user).
priorityint50noPriority from 0 to 100 (default 50); higher segments are kept first.
classificationstr'internal'noData classification: public, internal (default), confidential, restricted or secret.
source_typestr'user_input'noKind of source recorded in the provenance (default user_input).
source_idstr | NoneNonenoIdentifier of the source; defaults to <type>:<index>.
compressibleboolTruenoSegment may be truncated, summarized or dropped when the budget is short (default True).
cacheableboolFalsenoSegment is part of the cacheable prefix of the prompt (default False).
**provenanceAnynoExtra provenance fields stored with source_type and source_id.

Returns: Segment. A Segment: One piece of context with its priority (0-100), classification and provenance.

ContextBuilder.build​

build() -> BuiltContext

Select, compress and order the segments; raise :class:ContextOverflow if mandatory content overflows.

This element takes no parameter.

Returns: BuiltContext. A BuiltContext: Output of :meth:ContextBuilder.build.

Raises: ContextOverflow.

ContextBuilder.system​

system(content: str, **kw: Any) -> Segment

Add the system prompt (priority 100, never compressed, cacheable).

NameTypeDefaultRequiredDescription
contentstryesText of the system prompt.
**kwAnynoOther add options (classification, source_id, provenance); source_type defaults to system.

Returns: Segment. A Segment: One piece of context with its priority (0-100), classification and provenance.

Class ContextClient​

/v1/context/plan: server side budget and compression plan.

Resource

ContextClient.plan​

plan(window: int, output: int, reasoning: int = 0, safety: int = 0, segments: list[dict[str, Any]] | None = None, **extra: Any) -> Any

Plan the context window. Context Manager dry run: computes the token budget of a model window (output, reasoning and safety reserves) and which segments are kept, compressed or dropped by priority. With model, the window and output reserve come from the registry. A window that is not a positive integer answers 422 parameter_invalid; segments that cannot fit answer 422 context_overflow. Requires a reader role.

Route: /v1/context/plan (POST).

NameTypeDefaultRequiredDescription
windowintyesContext window of the model, in tokens.
outputintyesOutput of the operation (transcript, image references...).
reasoningint0noTokens reserved for reasoning (default 0).
safetyint0noTokens kept as safety margin (default 0).
segmentslist[dict[str, Any]] | NoneNonenoSegments to plan, as dicts; empty list by default.
**extraAnynoExtra fields merged into the request body.

Returns: Any. Decoded JSON answer of the operation "Plan the context window".

Raises: the typed errors of the transport (Errors).

Functions​

estimate_tokens​

estimate_tokens(text: str) -> int

Heuristic token estimate (chars/4, at least 1 for non empty text).

NameTypeDefaultRequiredDescription
textstryesText to measure.

Returns: int. Estimated number of tokens, 0 for an empty text.

truncate​

truncate(text: str, tokens: int) -> str

Keep the head of text within tokens (heuristic estimator).

NameTypeDefaultRequiredDescription
textstryesText to shorten.
tokensintyesMaximum number of tokens to keep (4 characters per token).

Returns: str. The text unchanged when it fits, otherwise its head ending with ...; empty when tokens is 0 or less.