Skip to content

Responses Phase 2+: tool_choice forwarding and real partial streaming - #64

Merged
FMXExpress merged 1 commit into
claude/pr63-responses-tools-passthroughfrom
claude/pr64-responses-limitations
May 28, 2026
Merged

FMXExpress merged 1 commit into
claude/pr63-responses-tools-passthroughfrom
claude/pr64-responses-limitations

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Closes two of the three known limitations from PR #63 — tool_choice forwarding and real partial streaming. Stacked on PR #63; rebase target collapses when #63 merges.

The third limitation (custom-type grammar tools like Codex's apply_patch) stays documented future work — it needs provider-side support for Lark-grammar output constraints that neither Anthropic Messages nor OpenAI Chat-Completions natively expose.

1. tool_choice forwarding

TChatOptions gains a ToolChoice: string field with the three string forms every provider can represent:

Value Behaviour
"" Emit nothing — provider default (typically "auto" when tools are present)
"auto" Model decides
"none" Model must not call any tool
"required" Model must call one of the tools

Provider mappings:

Provider Implementation
Anthropic Messages Emits tool_choice: {type: "auto"|"any"} object. auto → auto, required → any, none → field omitted (Anthropic's cleaner convention).
OpenAI Chat Completions Emits tool_choice as the bare string ("auto" / "none" / "required") — 1:1.
Gemini Skipped. generateContent's tool_config mapping is more involved; deferred.

HandleResponses reads request.tool_choice. Only the three string forms are accepted; the object form (force a specific function by name) is logged at debug and dropped — that needs per-provider translation substantial enough to be its own PR.

2. Real partial streaming

The passthrough+stream path now uses Provider.ChatStream with an OnChunk callback that emits response.output_text.delta events as the model produces fragments. Replaces the single-delta whole-text approach from PR #62.

  • First-byte-time improves dramatically for streaming-capable providers — Anthropic streams natively, so Codex starts rendering text as the model thinks.
  • OpenAI-compat providers whose ChatStream delegates to Chat and returns whole text in one shot still work — the new code feeds the whole text through OnChunk as one synthesized chunk, keeping the event shape consistent.

New module-level event helpers

Res*Evt() functions replace the previous local-inside-EmitResponsesStream helpers so both the single-delta path (EmitResponsesStream, used by the legacy RunToolLoop flow) and the true-streaming path (StreamResponsesViaProvider, used by passthrough) build events from the same code. All take Seq as the first arg, all carry the sequence_number openai-python validators require (PR #62 review fix).

TResponsesStreamState

Holds the streaming state (Streamer, MsgItemId, Seq counter, TextStarted flag, accumulated text, EmptyItem/EmptyPart JSON for lazy message sub-sequence open) and exposes OnChunk as a method-of-object the provider's TStreamCallback binds to.

Event sequence the new path emits

response.created                          { in_progress, empty output }
response.in_progress

[ on first text chunk — lazy open ]
  response.output_item.added              { message in_progress }
  response.content_part.added             { empty output_text part }

[ per text chunk ]
  response.output_text.delta              { just-this-fragment }

[ after ChatStream returns, if any text was emitted ]
  response.output_text.done               { accumulated text }
  response.content_part.done              { full part }
  response.output_item.done               { message completed }

[ per tool call in Resp.ToolCalls ]
  response.output_item.added              { function_call in_progress }
  response.function_call_arguments.delta  { full args, one delta }
  response.function_call_arguments.done
  response.output_item.done               { function_call completed }

response.completed                        { full output, usage }

HandleResponses dispatch table after this PR

HasFunctionTools WantsStream Path
✓ ✓ StreamResponsesViaProvider (this PR — real streaming, Codex's normal mode)
✓ ✗ Provider.Chat() + WriteJSON (PR #63 path)
✗ ✓ RunToolLoop + EmitResponsesStream (PR #62 single-delta — RunToolLoop is synchronous, no incremental data to stream)
✗ ✗ RunToolLoop + WriteJSON (legacy)

Test plan

  • Codex CLI streaming agentic task → text renders incrementally as the model produces it; function_call items still stream back and Codex executes them
  • Codex CLI with tool_choice: "none" — model emits text only, no function_call items
  • curl -N -X POST .../v1/responses -d '{"input":"hi","stream":true,"tools":[…]}' — see the event sequence with multiple response.output_text.delta frames (one per provider chunk), not one big delta
  • Same with stream:false — JSON shape unchanged from PR Responses Phase 2: tool passthrough so Codex can drive its own tools #63
  • Legacy curl ... -d '{"input":"hi","stream":true}' (no tools) — still uses EmitResponsesStream single-delta path; behaviour unchanged from PR /v1/responses: implement SSE streaming so Codex CLI stops crashing #62
  • Object-shaped tool_choice from a client — debug-logged "dropping tool_choice", request still succeeds with provider default

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

Closes two of the three known limitations from PR #63's description
(custom-type grammar tools remain documented future work — that one
needs provider-side change to support Lark-grammar output
constraints that neither Anthropic nor OpenAI Chat-Completions
natively expose).

1. tool_choice forwarding
   TChatOptions gains a ToolChoice: string field, with the three
   string forms every provider can represent:

       ""         => emit nothing (provider default; typically
                     "auto" when tools are present)
       "auto"     => model decides
       "none"     => model must not call any tool
       "required" => model must call one of the tools

   Provider mappings:
     Anthropic Messages API: emits tool_choice object alongside
       tools[]. auto -> {type: "auto"}, required -> {type: "any"},
       none -> field omitted (the cleaner Anthropic convention).
     OpenAI Chat Completions: emits tool_choice as the bare string
       form ("auto" / "none" / "required") — 1:1 mapping.
     Gemini: skipped. The generateContent API has tool_config but
       the mapping is more involved; deferred until a real Gemini
       Codex-flow user shows up.

   HandleResponses reads request.tool_choice. Only the three
   string forms are accepted; the object form (force a specific
   function by name) is logged at debug and dropped — needs per-
   provider translation that's substantial enough to be its own
   PR if a client actually needs it.

2. Real partial streaming
   The passthrough+stream path now uses Provider.ChatStream with
   an OnChunk callback that emits response.output_text.delta
   events as the model produces fragments. Replaces the
   single-delta whole-text approach from PR #62. First-byte-time
   improves dramatically for streaming-capable providers
   (Anthropic streams natively; OpenAI-compat's ChatStream
   currently delegates to Chat and returns the whole text — for
   that case the new code feeds the whole text through OnChunk as
   one synthesized chunk, so the event shape stays consistent).

   New module-level event helpers Res*Evt() replace the previous
   local-inside-EmitResponsesStream helpers so both the
   single-delta (EmitResponsesStream, used by the legacy
   RunToolLoop path) and the true-streaming
   (StreamResponsesViaProvider, used by the passthrough path)
   variants build events from the same code. All take Seq as
   first arg, all carry the per-event sequence_number openai-python
   validators require (PR #62 review fix).

   TResponsesStreamState class holds the streaming state
   (Streamer, MsgItemId, Seq counter, TextStarted flag,
   accumulated text, EmptyItem/EmptyPart JSON for lazy message
   sub-sequence open) and exposes OnChunk as a method-of-object
   the provider's TStreamCallback can bind to.

   Event sequence the new path emits:

     response.created            { in_progress, empty output }
     response.in_progress
     [ on first text chunk — lazy open ]
       response.output_item.added             { message in_progress }
       response.content_part.added            { empty output_text part }
     [ per text chunk ]
       response.output_text.delta             { just-this-fragment }
     [ after ChatStream returns, if any text was emitted ]
       response.output_text.done              { accumulated text }
       response.content_part.done             { full part }
       response.output_item.done              { message completed }
     [ per tool call in Resp.ToolCalls ]
       response.output_item.added             { function_call in_progress }
       response.function_call_arguments.delta { full args, one delta }
       response.function_call_arguments.done
       response.output_item.done              { function_call completed }
     response.completed                       { full output, usage }

   The Codex flow with PR #63 + this PR works end-to-end:
   incremental text rendering during model output, function_call
   items streamed back as the model emits them, multi-turn
   agentic loop with client-side tool execution.

   HandleResponses dispatch:
     HasFunctionTools + WantsStream  -> StreamResponsesViaProvider (Exit)
     HasFunctionTools + not stream   -> Provider.Chat() + WriteJSON (PR #63 path)
     not HasFunctionTools + stream   -> RunToolLoop + EmitResponsesStream
                                         (PR #62 single-delta — RunToolLoop
                                         is synchronous so there are no
                                         incremental data to stream)
     not HasFunctionTools + not stream -> RunToolLoop + WriteJSON (legacy)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 60cb4ad into claude/pr63-responses-tools-passthrough May 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 89ab29f258

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ResInProgressEvt(State.Seq, CreatedJSON)); Inc(State.Seq);

try
Resp := Provider.ChatStream(Msgs, ToolDefs, Model, Opts, State.OnChunk);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve Anthropic tool calls in streaming passthrough

When /v1/responses is streamed with client tools, this new path now calls Provider.ChatStream and relies on the returned Resp.ToolCalls to emit function_call items. In the Anthropic provider, ChatStream only accumulates text_delta chunks and never records streamed tool_use content blocks, unlike the non-streaming Chat/ParseResponse path, so an Anthropic tool-call-only turn will complete with an empty output instead of a function call for the client to execute. Either keep the full Chat path for providers that do not accumulate tool calls in streaming, or teach Anthropic streaming to populate Resp.ToolCalls.

Useful? React with 👍 / 👎.

same as omitting tool_choice
with no model-side impact).
Empty string means "don't emit; let provider default apply". }
if (Options.ToolChoice = 'auto') or (Options.ToolChoice = 'required') then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Forward Anthropic none tool_choice explicitly

When a client sends tool_choice: "none" with a non-empty tools array, this condition deliberately omits tool_choice, but omitting the field leaves Anthropic in its default/auto behavior rather than prohibiting tool use. That means requests that explicitly disable tool calls can still receive tool_use outputs; map this case to {"type":"none"} (or remove the tools before sending) so the provider honors the client's choice.

Useful? React with 👍 / 👎.

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.

2 participants