Skip to content

feat(llm): opt-in provider-native assistant turn replay - #806

Closed
Fanzzzd wants to merge 11 commits into
alibaba:mainfrom
Fanzzzd:fix/assistant-turn-replay
Closed

Fanzzzd wants to merge 11 commits into
alibaba:mainfrom
Fanzzzd:fix/assistant-turn-replay

Conversation

@Fanzzzd

@Fanzzzd Fanzzzd commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #805.

Reworked after splitting the independent fixes out of the original diff (see #821, #822, #823 and the summary comment). This PR is now only the replay feature itself, and the feature is off by default.

Note on stacking: the first five commits here are #821 (SSE heartbeat SDK bump), #822 (stream usage opt-out), and the pre-split revision of #823 — this branch is stacked on them because the replay envelope depends on all three. #823 was since narrowed per its review to just the no-tool retry bound, with the compression-zone fixes moved to #838; the two compression commits carried here are that pre-split revision, and this branch will be restacked once #823 merges and #838 settles on a direction. Reviewing can start with the last five commits today. The branch is rebased on current main (retry_codes and the replay flag coexist in ClientConfig/config).

What it does

With assistant_replay: "native" set on a provider entry or the llm section (via ocr config set llm.assistant_replay native, a provider's assistant_replay field, or OCR_LLM_ASSISTANT_REPLAY=native), the OpenAI-compatible adapter carries the complete assistant message a provider returned back on the next tool turn — instead of rebuilding it from the normalized content/tool-call projection. That preserves reasoning_content, reasoning_details, per-tool-call vendor extensions (e.g. Gemini extra_content.google.thought_signature), and exact content presence (empty vs. null vs. absent), which the rebuild loses (#805). DeepSeek's current thinking-mode contract makes this concrete: for requests carrying tools, reasoning_content must be passed back on subsequent turns or the API returns 400 — exactly what the normalized rebuild cannot do.

Without the flag, behavior is the pre-existing normalized rebuild, byte-for-byte — pinned by TestRunPerFile_OpenAIDefaultRebuildsNormalizedAssistantHistory.

Why default-off

Echoing response fields back as input is provider-dependent territory. Rather than guess, the replay path is conservative and explicit:

  • Unknown top-level provider fields are never echoed. Only fields with a known request-side contract are replayed (reasoning_content, reasoning_details); everything else is treated as response metadata. Vendor tool-call extensions are still overlaid per-call, and audio is reduced to its request-safe {"id"} form.
  • reasoning_content replays verbatim, never stripped. An earlier revision stripped it per-provider based on the old deepseek-reasoner contract (400 when present in input); DeepSeek's current documentation inverts that (400 when missing on tool turns, ignored elsewhere), so a strip would break exactly the provider it was protecting. Endpoints whose gateways reject the field simply stay on the default rebuild.
  • Envelope validation: an envelope whose tool calls lack id/type is discarded in favor of the normalized rebuild rather than failing the whole next request; gateways that omit the tool-call type discriminator get it defaulted from the response JSON.
  • Streaming hardening: an adapter-owned accumulator handles parallel tool calls, continuation fragments without index/id, legacy function_call, negative indexes, and exact empty-vs-absent reasoning.
  • Compression: an oversized latest round only hard-stops compression when a real replay envelope would be corrupted; plain tool-call rounds keep the existing degradation path.
  • Isolation: replay state stays out of normalized JSON and persisted session logs; CloneMessages deep-copies tool calls and nested content blocks so stored records can't be mutated through aliased slices.

Anthropic signed thinking (#811) and OpenAI Responses typed reasoning items (#812) are intentionally left to their own adapters — those protocols need native envelopes and must not be flattened into this Chat Completions representation.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

Deterministic HTTP-boundary tests cover both flag states: the default state pins the exact rebuilt request (no reasoning_content echo, no vendor fields, tool calls reduced to id/type/function), and the opt-in state pins non-streaming and streaming replay — exact visible content presence, omitted/null/empty fields, extension allowlisting, the DeepSeek pass-back contract, corrupt-envelope rejection, missing tool-call type, continuation fragments without index/id, nested Gemini signatures, parallel and legacy tool calls, no-tool retry, token accounting, persistence redaction, and compression atomicity. Resolver and ocr config set tests cover the config field, env override, canonicalization, and rejection of unknown values. Total coverage stays above the repository's 90% CI threshold.

  • make test passes locally
  • Manual testing (describe below)

The built dist/opencodereview CLI completed real reviews of disposable Git repositories against a strict local OpenAI-compatible service, in all four {default, assistant_replay: "native"} × {non-streaming, streaming} combinations, with the flag resolved through the real config-file path. The service returned a round-1 assistant message carrying reasoning_content, vendor_state, a Gemini-style extra_content tool extension, and (streaming) a tool-call continuation fragment without index/id, then rejected the round-2 request with HTTP 400 unless the assistant history matched the exact expected wire shape for the active mode — replay mode additionally verified exact empty-content presence and signature preservation, default mode verified the byte-identical legacy rebuild. All four runs completed through file_read/task_done, and persisted session JSONL was checked to contain no envelope internals in either mode.

Every commit in the series builds and vets independently.

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (docs for assistant_replay deferred until the flag name/shape is settled in review — happy to add them to this PR if you'd rather ship them together)
  • I have signed the CLA

Related Issues

Fixes #805

Split-out prerequisites: #821, #822, #823

Follow-up provider adapters:

@CLAassistant

CLAassistant commented Aug 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

github-actions Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 12 issue(s) in this PR.

  • ✅ Successfully posted inline: 12 comment(s)

Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llm/client.go Resolved
Comment thread internal/llmloop/loop.go Resolved
@stay-foolish-forever

Copy link
Copy Markdown
Contributor

Thank you for the detailed analysis in #805 and for taking the time to follow it through with a complete implementation here. The problem statement is accurate, the reproduction is convincing, and the replayEnvelope seam is an elegant way to carry provider-owned continuation state without letting it leak into the normalized view or the persisted logs. We are especially grateful for the care you took around cloning, token accounting, compression, and redaction — those are precisely the seams that would otherwise have broken silently, and it is clear you thought this through well beyond the immediate fix.

If we may offer some background on why the current behavior looks the way it does: when this design was first put together, the model APIs we targeted did not require the intermediate thinking process to be replayed on subsequent turns, so treating thinking as a fallback for content was a deliberate simplification for the constraints of that time rather than an oversight. Our benchmarks under that assumption showed good performance across the large majority of models we support, and that has held up reasonably well in practice since.

With that said, we would like to be careful here, and we hope you will bear with us. Replaying native reasoning state changes the effective prompt on every affected turn, and we expect the impact to vary by model — helping some, and possibly regressing others. Beyond that, existing users have built expectations around the current behavior, and the downstream effect on their experience is genuinely difficult to predict from code review alone. Two things in particular we would rather measure than reason about: models where reasoning replay meaningfully shifts output quality, and how token accounting behaves once hidden reasoning enters the request budget.

For those reasons we would like to run a thorough internal evaluation and work through the architectural trade-offs before we commit to a direction. Please read this as caution about changing behavior that affects every user on every turn, rather than as any reservation about the quality of your work.

We will keep this PR updated as that evaluation progresses. Should it lead us toward a different design, we would be delighted to have you involved in shaping it — you clearly have a deep understanding of this part of the system, and your input would be valuable to us regardless of which implementation we ultimately land on. Thank you again for raising this and for your patience while we work through it.

@Fanzzzd

Fanzzzd commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the thoughtful reply — your caution is well placed, and as it turns out, more justified than you knew.

While you were evaluating, I ran a stricter self-review of this PR (including field-level probe tests against the SDK conversion paths) and found several problems I introduced in the PR as submitted. The three most important:

  1. For OpenAI-compatible gateways that omit the type field on tool calls (some Ollama/vLLM builds and proxies do), the SDK's response→request conversion produces "tool_calls":[null], and the replay envelope sends that as-is — the next request fails with a 400. The pre-PR code rebuilt the assistant message from the normalized structure and was immune.
  2. An assistant message with empty content and no tool calls loses its content field entirely ({"role":"assistant"}), which strictly-validating servers reject.
  3. Unrecognized provider response fields are echoed back into the next request wholesale — including reasoning_content, which some providers explicitly reject on input (DeepSeek documents exactly this). This needs to be an allowlist, not a blanket echo.

I also need to correct the PR description: "no user-facing behavior changes" was not accurate. Replay itself changes the effective prompt on every affected turn — exactly the concern you raised — and there are two more changes I failed to declare: compression now hard-fails on an oversized latest round instead of degrading, and streaming unconditionally enables stream_options.include_usage.

So I've converted this PR to a draft and split out the parts that don't depend on the replay design discussion:

Those three can be reviewed independently. I'll rework the replay core here after fixing the problems above, and put it behind a config flag that is off by default — so merging can be decoupled from behavioral evaluation, your internal evaluation can proceed at whatever pace works for you, and the flag's eventual default can follow your data rather than my assumptions. #811 and #812 stay open as tracking issues (both updated with deterministic, no-endpoint-needed reproductions), to be revisited once the direction here settles.

@Fanzzzd
Fanzzzd force-pushed the fix/assistant-turn-replay branch from ba91479 to f4c7b8f Compare August 10, 2026 11:20
@Fanzzzd Fanzzzd changed the title fix(llm): preserve assistant replay across tool turns feat(llm): opt-in provider-native assistant turn replay Aug 11, 2026
@Fanzzzd

Fanzzzd commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Update: the rework described above is now pushed. Summary of what changed since the original diff:

The PR body has been rewritten to match. No rush on this one — happy to adjust the flag name/shape to whatever fits the project's config conventions.

Fanzzzd added 11 commits August 11, 2026 12:05
…eams

openai-go v3.41.0 dispatches comment-only SSE blocks (e.g. ": keep-alive"
lines sent by proxies and OpenAI-compatible gateways) as events with empty
data. Stream.Next() then feeds the empty payload to json.Unmarshal, fails
with "unexpected end of JSON input", and aborts the response mid-stream.

Upstream fixed this in v3.43.0 ("ssestream: skip SSE blocks without
data", openai/openai-go#621, commit 114224d) by skipping blocks that
carried no data lines. Upgrade to the current v3.50.0 to pick it up.

No code changes required: the v3 API is backward compatible across this
range, and make test / make check pass unchanged.
Streaming requests currently receive token usage only when the provider
volunteers it: OpenAI-compatible servers omit usage from streams unless
stream_options.include_usage is set, so streamed reviews silently lose
token and cost accounting.

Set stream_options.include_usage=true by default when streaming. The
existing extra_body passthrough stays in control: an explicit
stream_options object replaces the default, an explicit null suppresses
the field entirely for gateways that reject stream_options, and
non-streaming requests never carry the field (mirroring the alibaba#647
treatment of the "stream" key).
…ted options

An explicit stream_options object in extra_body used to replace the
include_usage default wholesale, so configuring an unrelated stream
option silently disabled usage accounting. include_usage now stays
requested unless the config spells it out (or suppresses stream_options
with an explicit null).
Three-zone compression currently discards context it should preserve:

- partitionMessages marked the whole tail as the compress zone whenever
  every round still fit the token budget, so each soft-threshold (60%)
  background compression summarized the entire live conversation instead
  of leaving it alone. In practice the active zone never survived a
  background compression.
- The frozen zone's own tokens were not reserved against the prompt
  budget when sizing the active zone, overfilling it once the folded-in
  summary grew.
- runCompression truncated the conversation to the frozen zone when no
  compression template is configured.
- The no-tool retry path appended to the conversation without any token
  bound: a model that keeps answering without tool calls grew the
  prompt unchecked until the provider rejected it.

An empty compress zone is now represented as compressEnd == frozenEnd
and left untouched, the frozen zone reserves its tokens, a missing
template keeps the conversation, and the retry path goes through the
same append+compression helper as tool rounds (addNextMessage
generalized to appendMessagesWithCompression taking the whole update
at once).
Sync compression triggers strictly over the warning limit, but the
success return used a strict less-than: a conversation sitting exactly
at the limit was reported as a compression failure and stopped the
loop. Return the exact complement of the trigger condition.
Carry the complete assistant message a provider returned back on the next
tool turn as an opaque adapter-owned envelope, instead of rebuilding it
from the normalized projection. Off by default: the assistant_replay
config field (or OCR_LLM_ASSISTANT_REPLAY) must be set to "native";
the default path keeps the existing normalized rebuild.

- Envelope capture validates tool calls and survives gateways that omit
  the tool call type discriminator or stream continuation fragments
  without index/id.
- Unknown top-level provider fields are never echoed back; only fields
  with a known request-side contract (reasoning_details) are replayed,
  plus per-tool-call vendor extensions and request-safe audio ids.
- reasoning_content is replayed by default but stripped for providers
  that document rejecting it in input (DeepSeek).
- Message.Clone deep-copies content blocks so stored records cannot be
  mutated through aliased slices.
…ompression

Replay the adapter-owned assistant turn through the agentic loop and
compression instead of a lossy content/tool-call rebuild. Compression
only hard-stops on an oversized latest round when a real replay envelope
would be corrupted; plain tool-call rounds keep the existing degradation
path. Token accounting moves to llm.ApproxMessagesTokenCount so opaque
replay state is priced in.
…persistence

Task records clone messages via llm.CloneMessages so in-memory replay
state survives for retries while the persisted JSONL keeps only the
redacted normalized projection.
The per-provider strip list was built on the old deepseek-reasoner
contract (400 when reasoning_content appears in input). DeepSeek's
current thinking-mode documentation inverts that: for requests carrying
tools, reasoning_content must be passed back on subsequent turns (400
when missing), and it is ignored on turns without tool calls. A
provider-level strip would therefore break exactly the provider it was
protecting. Drop the policy seam and carry reasoning_content verbatim;
native replay is opt-in per endpoint, so gateways that reject the field
simply stay on the default rebuild.
llm.assistant_replay and the per-provider assistant_replay field can now
be set through ocr config set with the same normalization and validation
as the resolver, instead of requiring hand-edited JSON or the
OCR_LLM_ASSISTANT_REPLAY environment variable.
Replay-state accessors, token estimates, custom-tool overlays, audio
reduction, flag gating, and streaming delta assembly were exercised only
through llmloop wire tests, which per-package coverage does not count.
Pin their contracts in-package; total coverage clears the CI threshold
again after the replay feature's additions diluted it.
@Fanzzzd
Fanzzzd force-pushed the fix/assistant-turn-replay branch from f4c7b8f to b4c67e8 Compare August 11, 2026 04:27
@Fanzzzd

Fanzzzd commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Two updates, one of which corrects something I said earlier in this thread:

1. Correction: reasoning_content is no longer stripped for DeepSeek — the opposite of what I wrote above. The strip was based on the old deepseek-reasoner contract (400 when reasoning_content appears in input). DeepSeek's current thinking-mode documentation inverts that: for requests carrying tools, reasoning_content must be fully passed back on subsequent turns or the API returns 400, and it is ignored (not rejected) on turns without tool calls. A per-provider strip would therefore have broken exactly the provider it was meant to protect — and this contract is incidentally the strongest concrete motivation for #805/native replay, since the normalized rebuild structurally cannot satisfy it. The policy seam is gone; the envelope replays reasoning_content verbatim, pinned by TestOpenAIReplayKeepsReasoningForToolTurns.

2. Rebased on current main (the branch had gone conflicting after retry_codes landed — both features now coexist in ClientConfig and the config schema), and the flag is now settable via ocr config set llm.assistant_replay native / providers.<name>.assistant_replay instead of requiring hand-edited JSON. Full suite, the four-way {default, native} × {non-streaming, streaming} strict-server end-to-end matrix, and the 90% coverage gate all pass on the rebased branch.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

This change is too messy; it seems to involve several things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thinking state is parsed but dropped when assistant tool-call turns are replayed

4 participants