UltraGPT: A Provider-Agnostic Reasoning, Resilience, and Orchestration Layer for Production LLM Applications
2026
UltraGPT is a production language-model layer that gives application code one interface to every model through OpenRouter while absorbing the recurring failure modes of real LLM integration: incompatible message formats, orphaned tool calls, context-window overflow, provider-specific structured-output quirks, rate limits, and model outages. It normalizes any history to a single representation, repairs orphaned tool calls, and truncates against a per-model token map using atomic tool-call grouping and a configurable reserve ratio. On top of plain chat, UltraGPT provides code-level deliberate inference. A reasoning pipeline produces canonicalized, de-duplicated thoughts; a steps pipeline decomposes a task, executes each step against an accumulating memory, and synthesizes a conclusion, with honest token accounting throughout. It detects models with native thinking and disables emulation for them, carries reasoning effort via a virtual model suffix, and preserves reasoning details across LangChain's serialization through carefully scoped import-time monkeypatches — the mechanism that makes reasoning models usable for multi-turn tool calling. Structured output is driven by Pydantic with strict-mode preparation and a tool-based fallback, tools are wrapped and validated uniformly, and every call is protected by rate-limit retry with exponential backoff and ordered model fallback. These same reasoning and steps pipelines are what our production systems expose as their deepthink and overdrive controls.
Introduction
We built UltraGPT to be the language-model layer we never want to write twice. Every serious LLM application re-implements the same unglamorous plumbing — message-format conversion, history sanitization, token-limit handling, structured output, retries, fallback — and re-implements it *per provider*. UltraGPT collapses that work into one library: a single facade that accepts any message format, reaches any model through OpenRouter, and layers higher-order inference modes, resilience, and schema discipline on top of a plain chat call.
This is explicitly **not** a thin SDK wrapper. UltraGPT carries opinionated machinery that earns its place: import-time monkeypatches that keep reasoning tokens intact across LangChain's serialization, a per-model context map that makes truncation a safeguard rather than an afterthought, code-level reasoning and step-decomposition pipelines, Pydantic-driven strict structured output, a wrapped tool layer, and rate-limit retry with ordered model fallback. It is the foundation beneath our production systems, which is why its reasoning and steps pipelines surface directly as the `deepthink` and `overdrive` controls those systems expose.
UltraGPT's internal decomposition. A thin facade exposes ChatFlow, PipelineRunner, and ToolManager; all model traffic converges on a ProviderManager and a single OpenRouterProvider, while import-time LangChain monkeypatches keep reasoning details intact across the serialization boundary.
This paper describes UltraGPT as of the 7.x line. We walk the system from the outside in: the unified call surface, message and token handling, the reasoning and steps pipelines, native-thinking detection and the virtual effort suffix, the LangChain monkeypatches, structured output, tools, resilience, and the design decisions that shaped each.
Design Goals
We designed UltraGPT against five goals, in priority order. **Write once, run everywhere**: the same call must work across model families without per-vendor branches in application code. **Fail by construction, not at runtime**: the common integration mistakes — orphaned tool calls, context overflow, schema drift — should be impossible to make, not merely caught. **Deliberate inference as a first-class feature**: reasoning and step decomposition must be reusable modes with honest token accounting, not ad-hoc prompt tricks. **Resilience by default**: rate limits and transient model failures must not surface to the caller. **Forward compatibility**: new models and provider quirks should be a configuration change, not a rewrite.
A library that looks right but loses reasoning tokens on a tool-call round trip has learned to call an API, not to run an agent.
The Unified Call Surface
Everything funnels through one method. `chat` accepts messages, an optional Pydantic `schema`, a `model`, tools, the `reasoning_pipeline` and `steps_pipeline` flags, optional `reasoning_model` / `steps_model` overrides, token controls, and `fallback_models`. It always returns the same triple — the answer (text or parsed schema), a total token count, and a details dictionary — so callers never special-case a mode: ```python answer, total_tokens, details = ultra.chat( messages, schema=MyModel, # optional Pydantic model for structured output model='gpt-5', reasoning_pipeline=True, # deepthink steps_pipeline=False, # overdrive tools=['calculator'], fallback_models=['anthropic/claude-sonnet-4.5'], ) ```
The facade itself is small: it constructs a `LangChainTokenLimiter`, a `ProviderManager` holding a single `OpenRouterProvider`, a `ToolManager`, a `ChatFlow`, and a `PipelineRunner`, then delegates. Configuration defaults are conservative and centralized — the default model, an `AUTO` input-truncation mode, and a 0.65 reserve ratio that intentionally leaves 35% context headroom to reduce the hallucination that tight context packing tends to cause.
The `chat` decision path. UltraGPT detects native thinking and avoids redundant emulation, optionally runs the reasoning and steps pipelines in parallel, then performs a final, token-bounded provider call with retry and model fallback. Every call returns a uniform (answer, tokens, details) triple.
Universal Model Access via OpenRouter
We route every call through OpenRouter, so one key reaches GPT, Claude, Gemini, Llama, Mistral, Grok, Qwen, GLM, and more behind a single interface, with BYOK supported in the OpenRouter dashboard. The provider layer was deliberately refactored to a `BaseOpenAICompatibleProvider` with `OpenRouterProvider` on top, and we removed the older per-vendor OpenAI and Claude providers entirely: maintaining one OpenAI-compatible path is far less error-prone than keeping several vendor SDKs in step. Switching models is a parameter, not a code path.
Message and History Normalization
Histories arrive in every shape — provider dicts, LangChain objects, raw strings, multimodal content blocks. We normalize all of them to LangChain messages up front, preserving supported multimodal user blocks while flattening text-only payloads, so the rest of the system reasons about exactly one representation.
The failure we guard hardest against is the **orphaned tool call**: an assistant message that references a tool result missing from the history (or vice versa). Most providers reject such a history outright with a 400. We expose and apply explicit helpers — `remove_orphaned_tool_results_lc` and `validate_tool_call_pairing_lc` — so a partially truncated or hand-assembled history is repaired before it ever reaches the API. We also drop empty messages, which some providers reject.
Auto-truncation. UltraGPT normalizes any history, removes orphaned tool results, groups each tool-call with its results, and drops oldest groups *atomically* until the conversation fits a per-model budget scaled by the reserve ratio.
Per-Model Auto-Truncation Safeguards
Token overflow is a constraint to manage, not an exception to catch. UltraGPT carries a per-model map of input and output limits and falls back to a conservative `default` for unknown models, so truncation is always informed by the *actual* window of the model in play: ```python LIMITS = { 'default': {'max_input_tokens': 128000, 'max_output_tokens': 4096}, 'gpt-5': {'max_input_tokens': 400000, 'max_output_tokens': 128000}, 'gpt-5.4': {'max_input_tokens': 1_050_000, 'max_output_tokens': 128000}, 'claude-sonnet-4.5': {'max_input_tokens': 1_000_000, 'max_output_tokens': 64000}, 'claude-opus-4.5': {'max_input_tokens': 200000, 'max_output_tokens': 32000}, # ... GPT, Claude, Gemini, Llama, Grok, Qwen, GLM families ... } ```
Input truncation runs in one of three modes — `AUTO` (default), `OFF`, or an explicit token number. In `AUTO`, the limiter computes a budget as the model's `max_input_tokens` scaled by the reserve ratio, then trims to fit. Crucially, trimming is **atomic over tool-call groups**: we group each assistant tool call with its tool results and drop oldest *whole* groups, never splitting a group — because a half-dropped group is exactly the orphan that breaks the next call. The budget is:
B_{\mathrm{input}} = \left\lfloor \mathrm{max\_input\_tokens}(m)\; \times\; r_{\mathrm{reserve}} \right\rfloor
with the reserve ratio `r` defaulting to 0.65. Token counts are estimated over a serialization that compacts long media references and multimodal blocks so counting stays cheap and stable. The result is that an over-long history degrades gracefully into a coherent, still-valid conversation instead of a 400.
A sample of the per-model input-context windows UltraGPT tracks. The token limiter scales each model's `max_input_tokens` by the reserve ratio to decide how much history fits, with a conservative `default` for unknown models.
Code-Level Deep Thinking
The deep-thinking layer is where the wrapper does the most work. It turns an ordinary model call into a multi-step reasoning process and keeps that reasoning coherent across providers. The subsections below walk through each part of that pipeline.
The Reasoning Pipeline
`deepthink` is not a prompt suffix; it is a code-level pipeline. The reasoning pipeline asks the model to produce a set of thoughts before committing to an answer, then **canonicalizes and de-duplicates** them so the model reasons over distinct points rather than paraphrasing one idea repeatedly: ```python def _canonicalize_thought(text): raw = str(text).strip() # strip enumerations like 'Thought 3:' / 'thought 1)' etc. stripped = re.sub(r'^thought\s*\d+\s*[:.\-\)\]]\s*', '', raw, flags=re.IGNORECASE) return stripped.lower(), stripped # (dedupe key, cleaned text) ```
The reasoning pipeline (`deepthink`). Generated thoughts are canonicalized — lowercased, trimmed, and stripped of enumerations like 'Thought 3:' — and de-duplicated, so the model reasons over genuinely distinct points rather than restating the same idea.
The Steps Pipeline
`overdrive` is the decomposition mode. The steps pipeline first asks the model to break the task into an ordered list of steps, then executes each step in turn against a growing **memory** of every prior step and its answer, and finally synthesizes a conclusion from the full memory: ```python memory = [] for step in steps: answer, tokens, details = chat_with_ai_sync( messages + [SystemMessage(each_step_prompt(memory, step))], model=active_model, tools=tools, deepthink=deepthink) memory.append({'step': step, 'answer': answer}) conclusion, _, _ = chat_with_ai_sync( messages + [SystemMessage(generate_conclusion_prompt(memory))]) ```
Throughout, we aggregate input, output, and provider-reported reasoning tokens and collect every tool used, so a multi-step run reports a single honest accounting of what it cost. A separate `steps_model` can drive the planning call while the cheaper main model executes each step. When both pipelines are requested, UltraGPT runs them concurrently in a small thread pool and folds their output into the final call's context: ```python with ThreadPoolExecutor(max_workers=2) as executor: if reasoning_pipeline: futures.append(('reasoning', executor.submit(run_reasoning_pipeline, ...))) if steps_pipeline: futures.append(('steps', executor.submit(run_steps_pipeline, ...))) ```
The steps pipeline (`overdrive`). The task is decomposed into ordered steps; each step executes against a running memory of prior answers, and a final pass synthesizes a conclusion. Input, output, and provider-reported reasoning tokens are aggregated across every call.
Native Thinking Detection and the Virtual Effort Suffix
Emulating reasoning on a model that already reasons natively is wasted tokens. Before running the reasoning pipeline, UltraGPT asks the provider whether the target model supports native thinking; if it does, it **disables the emulated pipeline** and instead enables native reasoning on the final call: ```python native = provider_manager.does_support_thinking(model) if native and reasoning_pipeline: reasoning_pipeline = False # don't fake what the model does for real use_native_thinking = True ```
Reasoning effort is carried by a lightweight **virtual `::suffix`** on the model string, so a caller can request effort without a separate parameter and without polluting the real model id sent to the API. The suffix is parsed off, validated against the allowed levels, optionally remapped per model family, and turned into the provider's `extra_body` reasoning payload: ```python VALID_EFFORT_LEVELS = {'none','minimal','low','medium','high','xhigh'} # 'openai/gpt-5.4::high' -> base model 'openai/gpt-5.4', effort 'high' def _build_extra_body(model, max_tokens, deepthink): if not deepthink or not _does_support_thinking(model): return None effort = deepthink if isinstance(deepthink, str) else 'high' return {'reasoning': {'effort': effort}} ``` Per-model effort aliases let one family's `minimal` map to another's `low`, so the same effort vocabulary behaves sensibly across providers.
Monkeypatching LangChain for Reasoning Continuity
This is the most opinionated part of UltraGPT, and the one that makes reasoning models usable for tool calling at all. Reasoning models return `reasoning_details` alongside their output, and providers require those details to be **sent back** on subsequent calls to preserve tool-call continuity. LangChain's OpenAI message converters drop unknown fields, so by default the reasoning trail is lost on the round trip. We patch the three private converters at import time, always calling the original first and then augmenting the result: ```python from langchain_openai.chat_models import base as lc_base lc_base._convert_message_to_dict = patch_serialize(lc_base._convert_message_to_dict) lc_base._convert_dict_to_message = patch_capture(lc_base._convert_dict_to_message) lc_base._convert_delta_to_message_chunk = patch_capture_stream(lc_base._convert_delta_to_message_chunk) ```
On serialization we copy a curated set of fields out of `additional_kwargs` — `reasoning_details`, `reasoning`, `refusal`, `thinking`, provider metadata, audio — into the outgoing assistant message. On response (both non-streaming and streaming) we capture the same fields back into `additional_kwargs`. The patches are designed to be safe and version-tolerant: they wrap rather than replace, never overwrite a field LangChain already set, and degrade to a logged warning if the private symbols move.
One subtlety required real care. Some reasoning models return an ephemeral server-side `id` (commonly `rs_...`) together with portable encrypted `data`. Sending that `id` back under `store=false` makes the server try to look up an item it never persisted and fail. So when portable data is present we strip only the ephemeral `rs_` id, while preserving non-`rs_` ids that some providers (e.g. Gemini) use to link encrypted thought signatures to specific tool calls: ```python def strip_id_if_data(item): if item.get('data') is None or 'id' not in item: return item if not str(item['id']).startswith('rs_'): return item # keep ids that carry tool-call continuity item = dict(item); item.pop('id', None) return item ```
Reasoning-detail continuity via monkeypatching. UltraGPT wraps LangChain's private message converters so reasoning tokens survive the round trip — required for tool-call continuity with reasoning models — and strips only the ephemeral server-side ids that would otherwise fail under `store=false`.
Universal Structured Output
Structured output is where provider differences bite hardest: strict JSON-schema modes, tool-based schemas, and models that ignore a schema all coexist. UltraGPT accepts a Pydantic model and prepares its schema for the target provider. Two transforms matter most. First, Pydantic v2 emits `Optional` fields as an `anyOf` of `[type, null]`, which OpenAI strict mode rejects; we normalize those. Second, strict mode requires `additionalProperties: false` and complete `required` arrays on every object, applied recursively: ```python schema = prepare_schema_for_openai(MyModel.model_json_schema()) # -> normalize_pydantic_optional_fields(...) # flatten anyOf [T, null] # -> ensure_openai_strict_compliance(...) # additionalProperties=false, required[] ``` For models without native strict mode, the same Pydantic model is offered through a tool-based fallback, so a typed call returns the same validated object regardless of the model behind it.
Tools and Wrapping
UltraGPT ships built-in tools — a calculator, math operations, and web search — and a `ToolManager` that wraps and dispatches both built-in and user tools. User tools are declared as `UserTool` / `ExpertTool` objects whose parameter schema is a Pydantic model; the manager normalizes that schema (the same Optional-field flattening as for structured output) and converts it to each provider's native tool format. Built-in tools are auto-discovered as Pydantic models and executed with validated parameters, so a tool call that the model emits is checked against its schema before the tool ever runs.
The tool layer is intentionally uniform: whether a tool is built in or user supplied, it is described to the model the same way, validated the same way, and executed through one path. That uniformity is what lets our higher systems register dozens of domain tools without touching UltraGPT itself.
Resilience: Retry and Model Fallback
Every provider call is wrapped in rate-limit retry. We retry up to five times, preferring a server-supplied `Retry-After` header and otherwise using exponential backoff with jitter, capped at a maximum delay: ```python RATE_LIMIT_RETRIES = 5; BASE_DELAY = 10; MAX_DELAY = 60; MULTIPLIER = 2 delay = min(BASE_DELAY * (MULTIPLIER ** attempt), MAX_DELAY) total_delay = retry_after_header or (delay + random.uniform(0.1, 0.3) * delay) ```
Beyond retrying a single model, UltraGPT walks an ordered list of fallback models. The primary model is tried first; on a fallback-worthy error it advances to the next candidate, and it records which model actually served the request along with the failures it skipped past. If every model fails it raises a single `ModelFallbackError` carrying the per-model attempts, so debugging a degraded call is a matter of reading one structured error: ```python details['selected_model'] = candidate details['fallback_used'] = idx > 0 details['attempted_models'] = models[: idx + 1] ``` Fallback models can be set once at construction and overridden per call.
Resilience. Each model is retried on rate limits with exponential backoff plus jitter (or a server `Retry-After`), and if a model fails in a fallback-worthy way the call walks an ordered fallback list, recording which model finally served the request.
Prompt Caching and Stream Hygiene
UltraGPT separates three mechanisms that are often conflated. A stable per-conversation `session_id` gives OpenRouter sticky routing and improves provider-cache locality without globally pinning traffic. Provider prompt caching uses automatic top-level cache control or explicit stable-prefix breakpoints, with the lower-cost five-minute TTL as the default and one-hour writes only when requested. OpenRouter response caching is a separate exact-response mechanism and remains opt-in. Streams and underlying responses are closed explicitly so the connection pool cannot be exhausted.
Cost Accounting Without Hot-Path Requests
Every inference call returns cost metadata without an additional API request. UltraGPT parses OpenRouter's final streamed usage record, exposing actual cost, cost details, cache reads and writes, and cache discounts. Provider-reported cost is authoritative because it reflects routing, fallback, and upstream cache pricing. If a provider omits cost, a local cache-aware estimator supplies an estimated cost and labels the source explicitly. An optional pricing refresh reads OpenRouter's model catalog only when called by an operator; it never runs on the inference hot path.
Pipeline aggregation carries cost and cache fields across reasoning, steps, and final generation instead of reporting only the last call. A committed offline pytest suite covers pricing calculations, provider-cost precedence, dynamic pricing parsing, exact model aliases, sticky session controls, and response-cache defaults.
Development Process and Evolution
UltraGPT reached its 7.x line through steady, model-driven iteration. The defining architectural move was consolidating onto a single OpenAI-compatible provider: we introduced `BaseOpenAICompatibleProvider` with `OpenRouterProvider` on top and removed the legacy per-vendor OpenAI and Claude providers, trading multi-SDK breadth for one well-tested path. Much of the subsequent history is the unglamorous, essential work of keeping a universal layer current.
The recurring themes in that history map directly onto the mechanisms in this paper: | Theme | What changed over the 7.x line | |---|---| | Model coverage | Added Gemini 3 / 3.1 Pro, Claude Opus 4.x, Grok 4.1 Fast, Qwen, Z.AI GLM-5, GPT-5.x to the limits + thinking maps | | Reasoning effort | Introduced the virtual `::suffix` effort system and per-model effort aliases | | Reasoning continuity | Preserved non-ephemeral reasoning ids for tool-call continuity; sanitized `rs_` ids for `store=false` | | Resilience | Added model fallback handling and structured fallback errors | | Caching | Added explicit `cache_control` for models that need it, auto for those that do not | | Token accounting | Tightened usage tracking and reserve ratio for safer truncation | | Message hygiene | Hardened normalization, empty-message dropping, and tool-call pairing |
Two reverts in the history are themselves informative: simplifications to debug messaging and a `.gitignore` change were rolled back rather than kept, reflecting a bias toward keeping diagnostic signal and a stable environment over cosmetic cleanup. The system grew by adding models and hardening the same few mechanisms, not by accreting new abstractions.
Why This Layer Matters
The payoff is leverage. Because UltraGPT absorbs format conversion, orphan repair, per-model truncation, structured output, tool wrapping, retry, fallback, caching, stream hygiene, and reasoning/steps orchestration, the systems above it stay focused on their own domain. They describe a task; they do not re-implement the LLM plumbing, and they inherit the same disciplined behavior — including the `deepthink` and `overdrive` modes that map straight onto UltraGPT's reasoning and steps pipelines, and the native-thinking detection that keeps those modes from wasting tokens on models that already reason.
Conclusion
UltraGPT is the write-once LLM layer: one interface to every model through OpenRouter, the common integration failures made impossible by construction, deliberate inference turned into reusable and measurable modes, and resilience that keeps rate limits and model failures off the caller's desk. Its most distinctive machinery — import-time monkeypatches that preserve reasoning continuity, a per-model truncation safeguard, the virtual effort suffix, and ordered model fallback — exists because real production LLM use demands it. The hard parts of talking to models live in one place, done once, for everything built on top.
Tags: large language models, LLM orchestration, OpenRouter, reasoning pipelines, structured output, token management, tool calling, provider abstraction, monkeypatching, rate-limit retry, model fallback, prompt caching, cost accounting, sticky provider routing, pytest, Ranit Bhowmick, Sayanti Chatterjee
Canonical URL: https://ranitbhowmick.com/research/ultragpt-provider-agnostic-reasoning-resilience-orchestration-layer