B2BB2B LLM
Аналитика для бизнеса

Как отладить усеченные потоковые ответы в API-интерфейсах LLM с несколькими поставщиками

Практическое руководство по диагностике усеченных потоков LLM между поставщиками путем рассмотрения завершения как конечного автомата протокола, а не как прибытия последнего фрагмента текста. Узнайте, как классифицировать сбои транспорта, ошибки поставщиков, неполные генерации, отмены клиентов, пробелы в использовании и условия безопасного повтора.

A streamed LLM response can return HTTP 200, emit several convincing paragraphs, and still be a failed request.

The failure usually appears when an application treats the last text chunk as proof of completion. A proxy may close an idle connection, a provider may send an in-stream error, a client may disconnect, or a tool call may stop midway through its arguments. The visible output looks plausible, but the request has not produced a trustworthy final result.

The reliable approach is to treat streaming as a protocol state machine. Text deltas are progress events. A separate terminal event—or a documented equivalent—is the evidence that the response completed.

Why HTTP 200 does not prove a successful LLM stream

HTTP status describes the initial request and response setup. It does not necessarily describe everything that happens while the body is being streamed. Once the server has accepted the request and opened the connection, later failures can arrive inside the event stream or appear as a connection close.

That distinction matters for at least five reasons:

  • A partial answer can be mistaken for a complete answer.
  • Usage data may never arrive, leaving cost and token records provisional.
  • Automatic retries can generate duplicate text, tool calls, or charges.
  • Structured-output consumers may parse an incomplete object as if it were valid.
  • Operations teams may record a successful request even though the provider or network terminated it abnormally.

SSE itself does not define business success. It defines how events are framed and delivered. Messages are separated by blank lines, and a connection closing is distinct from an application-level completion signal. Some clients may also attempt to reconnect unless the application explicitly closes or disables that behavior.

Model the stream as a state machine

Start by defining a provider-neutral set of states. The exact names are an implementation choice, but the distinctions should remain visible in storage and telemetry.

accepted
  -> started
  -> emitting
  -> provider_completed
  -> provider_incomplete
  -> provider_failed
  -> client_cancelled
  -> transport_lost
  -> protocol_error
  -> timed_out

Not every request passes through every state. A provider failure may occur immediately after started. A client cancellation may occur after many deltas. A transport close before any terminal event should never silently become provider_completed.

Persist the following with the request record:

  • Current and previous state.
  • Provider request ID and model identifier.
  • Time of connection open, first byte, first model delta, and final observation.
  • Number of events, bytes, and tokens emitted when available.
  • Last accepted sequence or event number, if the provider supplies one.
  • Upstream terminal event, error type, stop reason, and raw provider status.
  • Whether usage was finalized, estimated, or unavailable.
  • Whether any output was delivered to the downstream client.
  • Whether a retry is recommended by policy.

Make terminal transitions idempotent. A duplicate completion event, a delayed error, or a reconnecting client must not rewrite a settled result without an explicit reconciliation process.

Define terminal proof by provider

Provider protocols use different event names. Your adapter should translate them into a common contract while retaining the original event for diagnostics.

  • OpenAI Responses streaming documents lifecycle events such as response.completed, response.failed, response.incomplete, and error. An incomplete response can include a reason such as an output-token limit.
  • Anthropic Messages streaming uses events including message_start, content_block_delta, message_delta, message_stop, and error. The message-delta event can carry a stop reason and usage information.
  • Gemini streaming returns a sequence of response objects. Its Interactions streaming model defines events such as step.start, step.delta, step.stop, interaction.completed, and error.

Only a documented success terminal event should map to provider_completed. For example, the last text delta is not enough; response.completed, a valid Anthropic stop event, interaction.completed, or an equivalent provider-specific envelope is the required proof.

Separate model failure from transport failure

When a stream ends unexpectedly, first classify where the failure occurred. The same visible symptom—truncated text—can have very different causes and retry implications.

Provider-declared failure

An in-stream error means the provider explicitly reported that generation failed. Anthropic documents that an overloaded_error can arrive during streaming rather than as a normal non-streaming HTTP error. OpenAI and other providers likewise expose provider-specific error events.

Record the provider error before closing the downstream stream. If the client protocol supports an error envelope after partial output, send it. Otherwise, mark the response partial and expose the failure through a separate status channel.

Incomplete generation

Incomplete does not always mean the network failed. The model may have reached a configured output limit, been stopped by a policy, or ended during a tool or reasoning step. Treat the provider's stop reason as meaningful data, not as a generic success.

For structured output, fail closed when the terminal reason does not satisfy the application's contract. A syntactically valid prefix of a JSON document is still not a valid completed document.

Transport loss or proxy timeout

A connection can close after several deltas because of an idle load-balancer timeout, a reverse-proxy buffer, a network interruption, or a provider-side connection drop. Anthropic specifically warns that some networks can drop idle connections after a variable period.

Record inter-event gaps, proxy termination details, connection duration, and the last event observed. If no provider terminal event arrived, classify the result as transport_lost or timed_out, even when the initial HTTP response was 200.

Client cancellation

A browser tab closing, an upstream request being cancelled, or an application deadline expiring should produce client_cancelled. Do not label this a provider failure unless the provider also reports one. Cancellation still has billing and retry consequences: the provider may already have generated and charged for part of the response.

Protocol or parsing error

Malformed SSE framing, invalid UTF-8 handling, an unexpected event order, duplicate sequence numbers, or an unknown required event should produce protocol_error. Preserve the last raw frame and parser diagnostic in a protected trace so the adapter can be fixed without guessing from application logs.

Use a provider-neutral response envelope

A gateway should expose completion metadata separately from text. One practical envelope looks like this:

{
  "completion_status": "partial",
  "completion_reason": "transport_lost",
  "partial_output": true,
  "provider_request_id": "redacted-or-provider-id",
  "upstream_terminal_event": null,
  "usage_finalized": false,
  "retry_recommended": false
}

The names can differ, but clients need to know whether the text is complete, why it stopped, and whether usage is final. Keep provider-specific stop reasons and event names in diagnostic metadata rather than discarding them during normalization.

Interactive chat may display partial output with a visible “response interrupted” state. Transactional workflows, structured extraction, and tool-using automation should generally fail closed. They can retain the partial text for debugging without presenting it as an approved result.

Do not finalize usage when text stops

Text delivery and usage accounting are separate lifecycles. The last text delta may arrive before final token counts, cached-token details, tool usage, or a terminal usage envelope. Conversely, a stream can terminate before final usage is available.

Use at least three usage states:

  • Finalized: provider usage arrived with a valid terminal outcome.
  • Provisional: the gateway has an estimate or partial count but the stream did not complete cleanly.
  • Unavailable: no reliable usage record was received.

Send provisional records to a reconciliation path where the provider supports post-request lookup or billing exports. This avoids silently undercounting interrupted generations and gives finance and engineering teams a defensible explanation for dashboard differences.

Make retries depend on state and emitted output

A retry is not automatically safe just because the client did not receive a final answer. The provider may have accepted the request, generated output, invoked a tool, or charged tokens before the connection failed.

A conservative policy is:

  • Retry before output when the request is known not to have been accepted or generated, subject to normal rate-limit and timeout rules.
  • Consider retrying a provider-declared transient failure before any output is emitted.
  • Do not automatically retry after partial output unless the application can tolerate duplicate generation and duplicate charges.
  • Require idempotency or application-level deduplication before retrying workflows that can create side effects through tools.
  • For structured or transactional results, store the partial attempt and start a new attempt with a distinct attempt ID.

Retries after a partial answer are especially risky when the model has already emitted a tool-call name or arguments. Replaying the request can execute the same action twice unless the tool layer has its own idempotency key and effect ledger.

Test the failure paths deliberately

Successful-stream tests do not validate completion correctness. Add fault injection around the adapter and gateway:

  • Close the connection before the first delta.
  • Close it during a multibyte UTF-8 character.
  • Close it after text but immediately before the terminal event.
  • Inject a provider error after several deltas.
  • Stop during tool-call argument streaming.
  • Delay an event beyond the inter-event idle timeout.
  • Cancel the downstream client while the provider continues generating.
  • Deliver duplicate, reordered, malformed, or unknown events.
  • End after usage metadata but before the documented completion event.

For each test, assert the final state, downstream response, retry decision, usage state, billing record, and audit event. A stream test passes only when all of those outputs agree.

Operational checklist

When debugging a truncated response, answer these questions in order:

  1. Did the gateway receive a documented provider terminal event?
  2. What was the last provider event and its sequence number?
  3. Did the provider send an error or incomplete stop reason?
  4. Was the connection closed by the provider, proxy, gateway, or client?
  5. How long was the largest inter-event gap?
  6. Was any output, tool-call data, or structured content delivered?
  7. Was usage finalized or merely estimated?
  8. Would a retry duplicate output, charges, or side effects?

For a broader telemetry design, connect these records to provider-neutral LLM observability so stream states, latency gaps, terminal events, and usage status can be queried consistently across providers.

Conclusion

The practical fix for truncated LLM streams is not another string-concatenation check. It is an explicit completion contract.

Emit text as soon as it arrives, but classify success only after terminal proof. Store transport and provider diagnostics separately. Preserve partial output without calling it complete. Finalize usage independently from text delivery. Finally, make retry behavior depend on whether output or side effects may already exist.

As multi-provider gateways add more streaming features, tool calls, and workload-specific timeouts, this state-machine approach is likely to become a baseline correctness requirement. Teams that implement it early will have clearer failure metrics, safer automation, and fewer disputes over whether an interrupted response was actually successful.

FAQ

Часто задаваемые вопросы

Is an HTTP 200 response enough to mark a streamed LLM request successful?
Номер HTTP 200 подтверждает начальную настройку ответа, а не успешное завершение потока. Требовать событие успеха терминала, зависящее от поставщика, или эквивалентный конверт завершения.
Должен ли шлюз возвращать частичный вывод при прерывании потока?
Это возможно для интерактивного взаимодействия, но вывод должен быть помечен как частичный или прерванный. Структурированные, транзакционные и автоматизированные рабочие процессы обычно не закрываются и сохраняют частичный результат только для диагностики.
Безопасно ли повторять попытку после получения нескольких фрагментов текста?
Обычно не по умолчанию. Возможно, поставщик сгенерировал частичный ответ и взимал плату за него, а повторная попытка может привести к дублированию текста, вызовам инструментов или побочным эффектам. Прежде чем включать такие повторы, используйте идемпотентность и дедупликацию на уровне приложения.
Когда следует завершить использование запроса потоковой передачи?
Завершите использование после того, как станут доступны надежные метаданные об использовании поставщика и конечный результат. Если поток заканчивается первым, отметьте использование как временное или недоступное и согласуйте его позже, когда поставщик поддержит этот путь.