Skip to main content
Back to all articles
AI Engineering 14 min readUpdated November 1, 2026

Reasoning State Is Not a Transcript: Build a Safe Continuation Boundary

A production architecture for opaque reasoning state: preserve provider-specific tool continuity without leaking internal payloads, breaking retries, or miscounting tokens.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Engineering#Reasoning Models#Agent Infrastructure#TypeScript#Python#Security#Observability
On this page

A production AI application usually has three consumers of a model response: the user interface, the tool executor, and the observability pipeline. They should not all receive the same object.

That distinction becomes operationally important with reasoning-capable models. A response may include ordinary text, tool calls, usage counters, and provider-specific state needed to continue a tool-using turn. Some providers expose a form of thinking content or a summary; others retain raw reasoning privately and expose opaque continuation items. Treating those representations as one generic string breaks the contract in both directions: a logger may retain material it has no business seeing, while a tool runner may discard state the provider needs for the next call.

I would design the gateway around three different artifacts: a public response projection, an authorized execution plan, and a sealed provider continuation. The point is not to inspect private reasoning. It is to preserve protocol integrity while limiting who can access each artifact.

This article focuses on the response-to-tool-to-response boundary. It complements my earlier posts on reasoning effort selection, telemetry content controls, and required evidence when effort changes, without replacing those subjects.

The mistake is confusing explanation, execution, and continuation

Consider a fictional procurement assistant reviewing a software renewal. It has already received a user's request and proposes calling an internal contract-search tool. The orchestration service needs to know that a tool call is pending, which tool was requested, and how to pass the result back. The customer dashboard needs a human-readable progress state and, eventually, the answer. Monitoring needs timings, token counts, and error categories.

None of those downstream consumers needs unrestricted access to the provider's entire raw response.

In particular, reasoning state is not an audit record. Even when a provider supplies human-readable summaries, they are not proof of the model's internal decision process, the authorization of a tool call, or the accuracy of the result. Audit evidence should come from application-owned policy evaluations and observed actions.

The contract is easier to review when the paths are drawn explicitly:

~~~text [Authenticated application request] | [Provider adapter + model] | [Trusted response classifier] / | \ / | \ [Public projection] [Tool plan] [Sealed continuation] | | | UI / streaming Policy gateway Restricted state vault | | Authorized tool | | | Tool result -----------+ | [Provider adapter] | Next response

Metrics come from an allowlisted projection, never a raw-response dump. ~~~

The sealed continuation may be an API response identifier, a sequence of opaque reasoning items, or provider-specific signed blocks, depending on the API and mode. It is not a portable chain-of-thought format.

Compare provider contracts before designing storage

Two documented API designs show why this cannot be implemented with one casual “keep the thinking text” rule.

BoundaryOpenAI Responses APIAnthropic Messages API
Reasoning representationReasoning items, opaque state, and optional summaries; raw reasoning tokens are not exposed as ordinary textProvider-specific thinking blocks, signatures, and configurable display behavior
Continuation optionsStored response linkage (for example, previous_response_id), or retained output items and encrypted reasoning for stateless flowsPreserve the required assistant content blocks, including signed thinking, during tool interactions
Tool-turn correctnessForward the relevant reasoning and function-call items alongside tool outputs as documentedReturn provider-origin thinking/tool content unchanged where the tool workflow requires it
User-facing displayProject assistant answer content explicitlyProject intended text; do not treat thinking blocks as chat text
UsageProvider-reported input, output, and (where available) reasoning breakdownProvider-reported input/output usage, with thinking consumption incorporated into output usage

The OpenAI reasoning guide recommends preserving relevant reasoning items in tool-calling workflows; its exact multi-turn behavior also depends on model family and reasoning-context settings. The OpenAI conversation-state guide describes stateful continuation and request-history patterns.

Anthropic's thinking documentation documents signed blocks, tool-use continuity, and model-dependent preservation rules. Its streaming specification describes how a signature can arrive near the end of a thinking block, which matters if a stream is interrupted.

A useful rule follows: the provider adapter owns continuation semantics. Generic application code should ask whether continuation is valid and available, not infer it from the presence or absence of a readable reasoning string.

Do not assume a summary, signature, and encrypted reasoning payload are equivalent or interchangeable. They are different interface elements with different purposes.

Make the gateway carry a sealed turn, not a raw chat log

A provider-neutral application contract can contain metadata without attempting to normalize the provider's private state. For example:

~~~typescript type Provider = "openai" | "anthropic";

type ContinuationRef = Readonly<{ vaultKey: string; // Server-generated opaque locator provider: Provider; modelRevision: string; tenantScope: string; // Derived from authenticated context turnId: string; expiresAtMs: number; // Application retention deadline }>;

type PublicEvent = | Readonly<{ kind: "answer"; text: string }> | Readonly<{ kind: "tool_progress"; label: string }> | Readonly<{ kind: "complete" }>;

type ToolRequest = Readonly<{ callId: string; name: string; arguments: unknown; }>;

type ClassifiedTurn = Readonly<{ publicEvents: readonly PublicEvent[]; proposedTools: readonly ToolRequest[]; continuation?: ContinuationRef; finishReason: "complete" | "tool_pending" | "incomplete"; }>;

// This gate protects application routing. It does not validate a // provider's cryptographic signatures or authenticate the caller. function eligibleContinuation( ref: ContinuationRef, expected: { provider: Provider; modelRevision: string; tenantScope: string; turnId: string; }, nowMs: number, ): boolean { return Number.isFinite(nowMs) && ref.expiresAtMs > nowMs && ref.provider === expected.provider && ref.modelRevision === expected.modelRevision && ref.tenantScope === expected.tenantScope && ref.turnId === expected.turnId && ref.vaultKey.length > 0; }

function publicProjection(turn: ClassifiedTurn): PublicEvent[] { // Only approved event variants can cross the client boundary. return turn.publicEvents.map((event) => { if (event.kind === "answer") { return { kind: "answer", text: event.text }; } if (event.kind === "tool_progress") { return { kind: "tool_progress", label: event.label }; } return { kind: "complete" }; }); } ~~~

This is a typed boundary sketch, not a complete SDK integration. The trusted adapter still has to validate provider payloads, construct safe progress labels, and ensure unknown content types fail closed. In particular, this public projector must never be fed arbitrary model-generated events that have not passed the classifier.

The vault key is not an authorization credential. A caller must be authenticated and authorized to the current run before the backend retrieves sealed state; the tenant scope is checked again against trusted run metadata. An attacker supplying someone else's key should not gain access.

What goes inside the vault?

The minimal provider payload needed to continue according to that provider's documented API contract, bound to an application run and an exact model/adapter version. Depending on the mode, that could be a response ID or a collection of provider-origin content items and their signatures.

Encrypt stored material, restrict access to the execution service, and set a bounded application retention and deletion policy. Avoid writing the sealed payload to traces, crash logs, analytics events, dead-letter queue bodies, or routine customer-support exports. The same rules apply to provider responses that have no readable reasoning at all: opaque does not mean harmless to leak.

Where a provider stores state remotely, review its data-retention and deletion options separately. Deleting a local locator does not necessarily delete provider-held state.

The continuation is bound to one execution history

A continuation cannot safely be reused just because it has the same prompt or user.

I would bind it to the run identity, provider, compatible model revision, ordered tool-call history, tool schema version, and application policy generation. If a worker recovers after a crash, it should reconstruct those trusted facts before sending another provider request.

For every tool request, the execution layer must separately establish authorization. Preserving a valid continuation is not permission to run a tool. See the tool authorization boundary for the policy layer.

Model switching deserves special treatment. An OpenAI continuation handle should not be sent to a different provider as though it were portable history. A failover adapter may create a new request from a carefully selected, authorized public conversation and authoritative tool results, but that is a new reasoning episode, not an exact continuation. It must re-check outstanding tool effects and document the loss of private model state. This is especially important after an uncertain external write.

Crash consistency: do not acknowledge what has not been persisted

A worker can fail at several inconvenient points:

Crash or interruptionRecovery rule
After provider response, before saving its continuationDo not pretend the turn is resumable; retry within provider and application idempotency rules
After saving a pending tool request, before running itRecover the durable request and recheck authorization and policy
After a tool commits a side effect, before its result is recordedReconcile against the destination system; avoid blindly executing the same action again
During streamed thinking or a partially received tool callTreat it as incomplete; do not fabricate a signature, tool arguments, or a final answer
After tool results are recorded but before model continuationResume with the exact provider-required sequence where still valid

Use a transaction or durable outbox to connect the application-owned tool request, its execution status, and its result reference. The provider's private reasoning state should remain separate from the business-action idempotency key.

If the continuation is lost, the application should surface an explicit recovery state. It should not convert “provider state unavailable” into a misleading “tool succeeded” or “model refused” result. For the broader checkpointing design, see durable AI agent execution and clean retry forks.

Streaming: completion boundaries are more important than token boundaries

Most chat UIs can display partial text as it arrives. The execution layer has a stricter job: it must know when a provider-origin content block and the encompassing response are complete.

Anthropic's documented streaming format has block-start, delta, and block-stop events; a thinking signature can arrive at the end of a block. OpenAI's Responses API has its own typed streaming events and response lifecycle. Neither should be treated as an unstructured stream of strings.

A safe streaming adapter should:

  1. Assemble provider events using the provider's documented event grammar.
  2. Validate the completed message or block before considering it resumable.
  3. Publish only allowlisted display events to the UI.
  4. Record an incomplete-stream status if transport ends before the necessary completion event.
  5. Execute tools only after the required arguments, IDs, and authorization checks are complete.

Do not assemble a continuation by concatenating text deltas. That throws away ordering, type tags, and potentially integrity material. Nor should a disconnected browser force cancellation of a durable backend task unless that is the product's explicit cancellation policy.

Python: reconcile usage without inventing reasoning tokens

Reasoning tokens can make cost accounting unintuitive, particularly when the user sees a short answer. A correct meter should start with actual provider usage, not a character count or a guess from the length of a displayed summary.

Here is a small settlement model. It deliberately keeps provider output usage inclusive of any reasoning tokens already counted there; otherwise the ledger would charge twice.

~~~python from dataclasses import dataclass from decimal import Decimal

@dataclass(frozen=True) class Usage: input_tokens: int output_tokens: int reasoning_tokens: int | None = None

@dataclass(frozen=True) class Rates: input_per_million: Decimal output_per_million: Decimal

def settle(usage: Usage, rates: Rates) -> dict[str, Decimal | int | None]: if ( usage.input_tokens < 0 or usage.output_tokens < 0 or (usage.reasoning_tokens is not None and ( usage.reasoning_tokens < 0 or usage.reasoning_tokens > usage.output_tokens )) or rates.input_per_million < 0 or rates.output_per_million < 0 ): raise ValueError("invalid reported usage or configured rates")

million = Decimal(1_000_000) cost = ( Decimal(usage.input_tokens) * rates.input_per_million + Decimal(usage.output_tokens) * rates.output_per_million ) / million

return { "input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens, "reasoning_tokens": usage.reasoning_tokens, "estimated_cost": cost, }

Illustrative accounting inputs, not actual provider prices.

usage = Usage(input_tokens=1200, output_tokens=600, reasoning_tokens=450) rates = Rates(Decimal("1"), Decimal("4")) result = settle(usage, rates) assert result["estimated_cost"] == Decimal("0.0036") ~~~

In practice, a provider adapter should map the actual usage fields and pricing contract, including cached input, batch discounts, or other rate classes when supported. A missing reasoning breakdown must remain unknown, not silently become zero. Reserve budget before dispatch using an explicit admission policy; reconcile the final amount when the provider reports usage. See tenant AI budgets and reservations.

Tokens spent reasoning are not the only economic consideration. Returning large intermediate artifacts, retaining state, retrying tool loops, and moving between providers can change input and output usage. Measure cost per *completed workflow* as well as per model invocation.

Observe the protocol without observing private content

A useful operational trace is a record of application-controlled facts, not a serialized copy of the model response.

I would emit, for each model step, a small allowlisted span: provider family, model revision, workflow stage, outcome, whether a tool continuation was required, whether continuation validation passed, the number of requested and authorized tools, reported input/output tokens, reasoning-token breakdown if available, and retry or cancellation category.

The OpenTelemetry GenAI conventions warn that prompt, response, and tool-content fields can contain sensitive information. Treat automatic content capture as an explicit, separately governed feature. See my telemetry data-boundary design for an approach based on positive projections.

Useful metrics for a rollout include:

  • Continuation rejection rate, broken down by reason: expired state, mismatched run, model revision, bad sequence, or unsupported provider capability.
  • Tool-turn recovery success, including state-vault retrieval, uncertain side-effect reconciliation, and completed results after restarts.
  • Public-output leak tests, measuring whether reasoning-only or opaque state fields reach the browser, exporter, or error handler in synthetic fixtures.
  • Reasoning/output token share, only for providers and models that report a meaningful breakdown, segmented by task class.
  • Workflow latency and cost, measured through final, valid outcomes rather than only the first response token.

Alert on increased invalid continuations and tool-result mismatches, not just model HTTP errors. Use bounded-cardinality metric labels; run identifiers, tenant identities, and opaque payload locators belong in restricted records, not public dashboards.

One operational trade-off is deliberate loss of debugging visibility. If you never retain private reasoning, you cannot later inspect its full contents. The replacement should be richer external evidence: tool call IDs, validated arguments, source versions, policy decisions, returned statuses, and replayable nonsecret fixtures. This is often more useful for diagnosing a real contract failure than a speculative explanation.

Test the separation with hostile and interrupted responses

Before rollout, I would exercise the adapter with synthetic provider fixtures. These are proposed tests, not results from a deployed system:

TestExpected outcome
A response includes ordinary text alongside an opaque reasoning itemUI shows the answer; state item remains sealed
An unexpected block type appearsClassifier rejects or quarantines it under a versioned policy
A tool turn requires signed content, but the stream ends before signature completionMark incomplete; do not send a forged continuation
A worker tries another tenant's continuation locatorDeny access independently of the locator format
Tool arguments change after approvalReject execution and require a new policy decision
A model/provider switch occurs mid-turnStart a documented fresh episode; never replay incompatible private state
Usage lacks a reasoning-token breakdownMeter known total usage; leave reasoning share unknown
Logger, APM agent, or exception serializer receives the raw responseTest that allowlist projection blocks unexpected content
Worker crashes after an external writeReconcile outcome using the action identity before retry

Include ordinary happy-path tests, too: multiple tool calls, an empty result, a refusal, cancellation, long-running execution, and a clean completed turn. Integration-test the exact SDK and model revisions you deploy, because reasoning and streaming behavior are versioned capabilities rather than timeless properties.

For a useful release gate, compare an adapter update against fixtures produced by the supported provider schemas. A generic JSON schema check cannot establish that signed continuation items remain valid after round-trip serialization.

Trade-offs and the boundary I would keep

A sealed-state vault adds storage, encryption, lifecycle cleanup, version negotiation, and recovery complexity. A fully stateless service with provider-encrypted continuation items has different retention and storage trade-offs from a service that relies on provider-stored response IDs. Neither architecture exempts the application from tenant authorization, side-effect safety, or observability design.

For a simple answer-only chatbot, the right answer may be to use the SDK's normal state handling and keep content logging off. For a multi-tenant tool-using assistant with retries, cross-worker recovery, and provider failover, I would make the separation between display, execution, and continuation an explicit typed contract.

The important question is not “can we see what the model thought?” It is whether we can preserve exactly the state the provider requires, expose only the content the user is meant to receive, and still prove what our own application did.

Primary references

Topic provenance: This article was independently developed after identifying the subject of Viral Ruparel's August 28, 2026 essay on extended thinking in production. Its scenario, continuation-vault architecture, control contracts, examples, test cases, and framing are original.

KEEP READING

Related engineering notes