Repository navigation
Responses Phase 2+: tool_choice forwarding and real partial streaming - #64
Conversation
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
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
[reopen #64] Responses Phase 2+: tool_choice forwarding and real partial streaming
Closes two of the three known limitations from PR #63 —
tool_choiceforwarding 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_choiceforwardingTChatOptionsgains aToolChoice: stringfield with the three string forms every provider can represent:"""auto""none""required"Provider mappings:
tool_choice: {type: "auto"|"any"}object.auto→auto,required→any,none→ field omitted (Anthropic's cleaner convention).tool_choiceas the bare string ("auto" / "none" / "required") — 1:1.generateContent'stool_configmapping is more involved; deferred.HandleResponsesreadsrequest.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.ChatStreamwith anOnChunkcallback that emitsresponse.output_text.deltaevents as the model produces fragments. Replaces the single-delta whole-text approach from PR #62.ChatStreamdelegates toChatand returns whole text in one shot still work — the new code feeds the whole text throughOnChunkas one synthesized chunk, keeping the event shape consistent.New module-level event helpers
Res*Evt()functions replace the previous local-inside-EmitResponsesStreamhelpers so both the single-delta path (EmitResponsesStream, used by the legacyRunToolLoopflow) and the true-streaming path (StreamResponsesViaProvider, used by passthrough) build events from the same code. All takeSeqas the first arg, all carry thesequence_numberopenai-python validators require (PR #62 review fix).TResponsesStreamStateHolds the streaming state (
Streamer,MsgItemId,Seqcounter,TextStartedflag, accumulated text,EmptyItem/EmptyPartJSON for lazy message sub-sequence open) and exposesOnChunkas a method-of-object the provider'sTStreamCallbackbinds to.Event sequence the new path emits
HandleResponsesdispatch table after this PRHasFunctionToolsWantsStreamStreamResponsesViaProvider(this PR — real streaming, Codex's normal mode)Provider.Chat()+WriteJSON(PR #63 path)RunToolLoop+EmitResponsesStream(PR #62 single-delta —RunToolLoopis synchronous, no incremental data to stream)RunToolLoop+WriteJSON(legacy)Test plan
function_callitems still stream back and Codex executes themtool_choice: "none"— model emits text only, no function_call itemscurl -N -X POST .../v1/responses -d '{"input":"hi","stream":true,"tools":[…]}'— see the event sequence with multipleresponse.output_text.deltaframes (one per provider chunk), not one big deltastream:false— JSON shape unchanged from PR Responses Phase 2: tool passthrough so Codex can drive its own tools #63curl ... -d '{"input":"hi","stream":true}'(no tools) — still usesEmitResponsesStreamsingle-delta path; behaviour unchanged from PR /v1/responses: implement SSE streaming so Codex CLI stops crashing #62tool_choicefrom a client — debug-logged "dropping tool_choice", request still succeeds with provider defaulthttps://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code