Introducing a new way to review your PRs.

Read the announcement

zipstack / unstract

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

View on GitHub

28 documents · Updated Nov 23, 2026

docs / sdk1-llm-runtime

SDK LLM runtime

The SDK LLM runtime gives integrations one interface for calling many language-model providers. It turns saved adapter settings into provider requests, keeps full and streamed calls consistent, and adds shared controls for retries, output handling, errors, and usage records. It is the model boundary used by tools and other SDK consumers rather than a provider-specific API.

Runtime role

The runtime sits between an integration and a provider adapter. An integration selects an adapter directly or by a saved adapter instance. The runtime then validates the adapter settings and sends a common chat request through the LiteLLM provider layer.

Unified LLM interface

unstract/…/llm.py exposes the LLM class as the main call boundary. It accepts either an adapter ID with metadata or an adapter instance ID resolved from a tool. This lets a test connection and a running tool use the same request path while keeping stored credentials and platform usage data outside the prompt itself.

The interface keeps provider differences behind a small set of operations:

OperationIntegration contract
completeReturn one complete response with a stable response object and the raw provider response attached
stream_completeYield response objects as text becomes available
acompleteReturn one complete response through the async provider call path
complete_visionSend pre-built text and image messages for multimodal work

Every operation reports provider errors as SDK errors with adapter context. The runtime also records token use and cost data so callers do not need a separate accounting path.

References: unstract/…/llm.py• L204-322 unstract/…/llm.py• L586-709 unstract/…/llm.py• L711-802

Integration compatibility

LLMCompat adapts the SDK interface to the small chat and completion shape expected by llama-index based integrations. It converts message lists into one prompt and delegates the actual call to the same LLM instance. This keeps provider selection, error handling, and usage records in one place.

The compatibility layer supports sync and async chat or completion calls. Its streaming compatibility methods are not implemented, so integrations that need incremental output must use LLM.stream_complete directly rather than rely on the wrapper.

References: unstract/…/llm.py• L1319-1395 unstract/…/llm.py• L1407-1487 unstract/…/llm.py• L1489-1519

Provider adapter configuration

Provider adapters define how a model endpoint is named, authenticated, and called. Their static JSON schemas form the user-facing configuration contract. The runtime treats the selected schema as input, validates it through the adapter, and passes only provider call settings to LiteLLM.

Adapter settings

The schemas cover both shared and provider-specific concerns. Shared fields include the adapter name, model, credentials or endpoint, output limit, timeout, retry count, and the streaming switch. Provider schemas then add controls such as cloud region, deployment name, local base URL, safety settings, or reasoning mode when the provider supports them.

The schemas also express dependent settings. For example, a reasoning or thinking budget appears only when the related mode is enabled. Bedrock authentication selects the required credential fields, and a guardrail requires its version. These rules keep invalid combinations out of the adapter configuration before a request starts.

References: unstract/…/openai.json• L1-119 unstract/…/bedrock.json• L1-233 unstract/…/custom_openai.json• L1-119 unstract/…/vertex_ai.json• L1-182

Configuration validation

At runtime, the selected adapter validates the stored metadata again. This is important because integrations can create an LLM without using a form, and because each provider needs a different translation from shared settings to its request format. Internal settings such as the cost model, context size, retry count, and streaming choice are used by the SDK and are not sent as ordinary provider parameters.

The adapter schemas are therefore part of a cross-system contract. A form change can alter what users save, while an adapter validator change can alter what reaches the provider. Both sides must preserve the fields that the runtime uses to choose its request path.

References: unstract/…/llm.py• L255-322 unstract/…/test_llm_schema_streaming_flag.py• L16-39 unstract/…/anthropic.json• L25-55

Streaming behavior

Streaming is the normal transport for full synchronous completions. The runtime receives provider chunks and rebuilds them into the same complete response shape that callers used before streaming became the default. This keeps long replies active on the connection while preserving the full-response contract.

Stream selection

The enable_streaming adapter setting controls the transport, not the public return type of complete. The setting defaults to true when it is missing, which keeps older saved adapters on the current behavior. An endpoint can set it to false when it cannot stream.

The setting is read from raw adapter metadata because provider validators may remove fields that they do not send to LiteLLM. It never becomes a provider completion parameter. All current LLM form schemas expose the same boolean field with a default of true.

References: unstract/…/llm.py• L506-531 unstract/…/test_anthropic_stream_complete.py• L294-329 unstract/…/test_llm_schema_streaming_flag.py• L28-39

Completion assembly

The full completion path collects stream items and rebuilds the response. The rebuilt result retains response content, finish reason, usage, and provider response data. The caller therefore receives the usual response object even though the provider used a stream.

The public stream path has a different contract. stream_complete yields text deltas and can notify a callback manager for each text chunk. Bookkeeping chunks and empty chunks do not reach the caller. A refusal before any text becomes an SDK error, while a refusal after partial text is logged as a partial result condition.

The following flow shows how the two completion forms share the provider boundary but return different views of the same stream.

flowchart LR
    A[Integration prompt] --> B[LLM adapter validation]
    B --> C[Provider stream]
    C --> D{Public operation}
    D -->|complete| E[Collect and rebuild full response]
    D -->|stream_complete| F[Yield text deltas]
    E --> G[Response and usage record]
    F --> G

References: unstract/…/llm.py• L549-584 unstract/…/llm.py• L804-884 unstract/…/test_anthropic_stream_complete.py• L92-158

Output controls

The runtime provides call-level controls for integrations that need structured or transformed text. These controls act after the provider returns content and do not change the provider adapter schema.

JSON extraction

complete accepts extract_json to select a JSON object or array from model text. It can also use a configured marker to select the part between two marker values. This is a cleanup aid for models that wrap structured output in prose; it is not a full JSON Schema validator and does not guarantee that the selected text is valid for a caller's data model.

An integration can pass process_text for its own post-processing. The callback receives the current response, the extraction flag, and the original text. If the callback fails, the runtime logs the failure and keeps the response without callback output.

References: unstract/…/llm.py• L214-217 unstract/…/llm.py• L667-683 unstract/…/llm.py• L1277-1316

Prompt and model limits

The runtime can report a model context window and a maximum usable token limit for an adapter instance. It first uses adapter or LiteLLM model information and falls back to a safe SDK limit when the provider does not expose a value. Integrations can reserve output tokens so their input stays within the model limit.

Prompt caching is opt-in and applies only when the provider and model support it. When active, a stable system prompt or caller-supplied prefix is marked for caching while request-specific text stays uncached. The model still sees the same combined prompt when caching is inactive.

References: unstract/…/llm.py• L54-71 unstract/…/llm.py• L390-504 unstract/…/llm.py• L966-1008

Retry helpers

The SDK owns retry decisions for LLM calls so provider SDK retries do not silently multiply a request. Adapter max_retries is taken from the call settings, while LiteLLM's built-in retry counts are set to zero. The shared helpers then apply one retry policy to sync calls, async calls, and streams.

Retry policy

The LLM retry predicate treats connection and timeout failures as transient. It also retries selected service responses: 408, 429, 500, 502, 503, and 504. A provider Retry-After value takes priority over local backoff. Otherwise the helper uses capped exponential backoff with optional jitter.

The retry helpers cover these integration shapes:

HelperUse
call_with_retrySynchronous one-result provider call
acall_with_retryAsync one-result provider call
iter_with_retryStream an iterable and retry only before its first yielded item
collect_with_retryDrain a stream so the runtime can rebuild a full response

The same module also provides an environment-configured decorator for requests-based platform service calls. That path uses requests and OS connection errors rather than the LiteLLM error family.

References: unstract/…/retry_utils.py• L19-61 unstract/…/retry_utils.py• L90-186 unstract/…/retry_utils.py• L189-275 unstract/…/retry_utils.py• L443-569

Stream retry boundary

A stream can emit bookkeeping items before it emits model text. The collection helper retries a failed request when no content has arrived, and it discards items from that failed attempt. Once content has arrived, it raises the failure instead of replaying the generation. This prevents duplicate work and avoids returning a response with repeated text.

The boundary applies both when stream creation fails and when iteration fails. It also closes the failed generator before a retry so the provider connection can be released.

References: unstract/…/retry_utils.py• L237-325 unstract/…/llm.py• L549-575 unstract/…/test_collect_with_retry.py• L53-152

Runtime signals

The runtime makes provider results useful to downstream systems beyond the returned text. It attaches the raw response, tracks token and cost data, and keeps provider response IDs when available for support and billing checks. Callers can read the latest usage record or flush pending records at executor finalization.

Error and usage contract

An empty provider response becomes an LLMError. A refusal finish reason is reported as a client-facing safety error, while other empty results are reported as provider failures. Other provider exceptions are wrapped with the adapter identity and any available status code.

Usage records distinguish prompt, completion, and total tokens. They also include the provider, model, adapter instance, run context, cost, and request identifiers when the provider supplies them. This lets workflow execution account for calls without knowing which provider produced them.

References: unstract/…/llm.py• L1018-1052 unstract/…/llm.py• L1105-1193 unstract/…/llm.py• L1196-1230

The SDK runtime is one part of the wider integration boundary. See Connectors and tool ecosystem for the role of tools and connectors, Connector platform for connector packages, and Tool runtime for tool execution.

Change checklist

When these files or sections are changed, remember to consider these:

  • When an adapter schema adds, renames, or defaults a field, check the adapter validator, runtime-only field handling, and the saved configuration used by existing instances.
  • When enable_streaming changes, check both the schema default and the full-response assembly path because complete must keep its response shape in both transport modes.
  • When stream chunk handling changes, check content detection, usage recording, callback delivery, and the no-replay boundary together.
  • When retry settings or error classes change, check LiteLLM retry disabling so provider SDK retries do not run in parallel with SDK retries.
  • When response or usage fields change, check the raw response consumers and the executor path that reads or flushes pending usage records.
  • When compatibility methods change, check llama-index callers because the wrapper delegates to LLM and does not own a separate provider path.

Important failure modes

TriggerConsequenceGuard
enable_streaming is removed from a provider schema or treated as a provider parameterThe endpoint may use the wrong transport or LiteLLM may receive an unsupported settingKeep the field in each schema and resolve it from raw metadata before building provider kwargs
A stream fails before any model contentThe first request fails even though a safe retry was possiblecollect_with_retry retries retryable failures before content and drops failed-attempt items
A stream fails after content has startedReplaying the request can duplicate a long generationThe stream retry helpers raise after content and do not replay the generation
A provider rejects an adapter setting combinationThe call fails before a useful provider response is producedAdapter schemas express conditional requirements and runtime validation runs again
A caller expects LLMCompat streaming methods to workThe integration receives NotImplementedErrorUse LLM.stream_complete for incremental output or add an explicit compatibility path
A provider returns refusal or empty contentDownstream code receives no usable response textThe runtime raises LLMError with a refusal or empty-response reason

Key files

FileWhy to read it
unstract/…/llm.pyDefines the common LLM boundary, completion modes, output controls, usage records, and compatibility wrapper
unstract/…/retry_utils.pyDefines provider error classification, backoff, sync and async retries, and stream retry boundaries
unstract/…/openai.jsonShows the common provider form shape and conditional reasoning controls
unstract/…/bedrock.jsonShows cloud authentication choices, model-specific controls, guardrails, and streaming configuration
unstract/…/custom_openai.jsonShows the configuration contract for OpenAI-compatible gateways
unstract/…/test_anthropic_stream_complete.pyVerifies default streaming, response rebuilding, opt-out behavior, and retry behavior
unstract/…/test_llm_schema_streaming_flag.pyVerifies that every LLM adapter schema exposes the streaming control
unstract/…/test_collect_with_retry.pyVerifies the retry boundary before and after stream content