Repository navigation
[reopen #64] Responses Phase 2+: tool_choice forwarding and real partial streaming - #67
Conversation
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_use blocks while streaming
When /v1/responses streams through the Anthropic provider with client tools, this new path relies on ChatStream to return final Resp.ToolCalls, but HandleAnthropicSSE only accumulates text/usage and never records tool_use content blocks. A tool-call-only Claude response therefore reaches this code with empty text and no tool calls, so the stream completes without the function_call item the client needs to execute the tool; the non-streaming path still parses those tool calls from the full response.
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 tool_choice none explicitly
When a Responses client sends tool_choice: "none" together with tools, HandleResponses stores none in PassthroughOpts, but this branch omits Anthropic's tool_choice field entirely. Omitting the field with tools is Anthropic's default auto behavior, not “no tools”, so Claude may still emit tool_use blocks even though the caller explicitly disabled tool use; Anthropic's Messages API supports {"type":"none"} for this case.
Useful? React with 👍 / 👎.
| CompletedObj := BuildResponsesObject(RespId, Model, 'completed', | ||
| State.TextAccumulated, | ||
| Resp.ToolCalls, ToolsRawJSON, | ||
| Resp.Usage); |
There was a problem hiding this comment.
Report streaming provider failures as failed responses
If Provider.ChatStream raises after the SSE headers have been sent (for example an upstream 4xx/timeout), the exception handler sets FinishReason := 'error', but the code below still emits response.completed with status completed and empty output/usage. Streaming clients will treat provider failures as successful empty responses instead of surfacing an error, making transient or auth failures very hard to detect.
Useful? React with 👍 / 👎.
7dd8bdd to
5c64186
Compare
89ab29f to
8afb8b6
Compare
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
8afb8b6 to
1b33c6c
Compare
…_use, tool_choice none, response.failed Addresses Codex review feedback on PR #66 (now in main) and the open PR #67. 1. Group parallel function_call inputs into one assistant turn (PR #66) When Codex sends multiple function_call items in a single Responses API turn (parallel tool use), AppendAssistantToolCall previously created one TMessage per call. Anthropic rejects request shapes that split a single assistant turn into multiple consecutive assistant messages with tool_use blocks. The helper now appends to the previous message when it is an empty-content assistant with tool_calls, coalescing the parallel turn into one message while still creating a new message after any non-assistant boundary (function_call_output / message). Matching with function_call_output is unaffected since it keys by call_id. 2. Anthropic SSE: accumulate tool_use blocks (PR #67, P1) HandleAnthropicSSE was only tracking text_delta / message_delta / message_start / message_stop. Tool-call-only assistant turns streamed back with no ToolCalls, so the gateway never emitted the function_call output items and Codex couldn't execute the tools. Added handling for the three events that bracket a tool_use block: content_block_start (type=tool_use) -> capture id+name, start buffer content_block_delta (type=input_json_delta) -> append partial_json content_block_stop -> flush accumulated TToolCall to GStreamLast ChatStream now propagates GStreamLast.ToolCalls into Result. Also clears the tool-block state and Finalizes GStreamLast on entry so the previous call's managed fields don't leak refcounts under the subsequent FillChar zero. 3. Anthropic: emit tool_choice {type: "none"} explicitly (PR #67, P2) Anthropic supports {"type":"none"} to forbid tool calls; omitting tool_choice when tools are present still allows the model to call them. BuildRequest now emits the explicit form when ToolChoice = "none" so the client's intent reaches the API. 4. Streaming failures emit response.failed (PR #67, P2) StreamResponsesViaProvider used to emit response.completed with status "completed" and empty output even when the provider raised or returned FinishReason="error" after SSE headers were sent. Streaming clients (openai-python, Codex) treat that as a successful empty response, hiding real errors. Added a ResFailedEvt helper and a Failed flag in StreamResponsesViaProvider. When the ChatStream call raises or the response carries FinishReason="error", capture the error string, suppress the fake-text-chunk fallback, and emit response.failed with the response object's status set to "failed" and an {code:"server_error", message:<err>} error block — matching the non-streaming HandleResponses' error shape. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Re-opening PR #64 which got stranded — was merged into PR #63's branch but never propagated to main. Stacked on new PR #66 (the reopen of #63). When #65 and #66 land in order, retarget this to
mainand the diff collapses to just the Phase 2+ commit.Original PR #64 description follows
Closes two of the three known limitations from PR #63 —
tool_choiceforwarding and real partial streaming. The third (custom-type grammar tools like Codex'sapply_patch) stays documented future work — neither Anthropic Messages nor OpenAI Chat-Completions natively support Lark-grammar output constraints.1.
tool_choiceforwardingTChatOptionsgains aToolChoice: stringfield with three string forms:"""auto""none""required"tool_choice: {type: "auto"|"any"};none→ field omittedObject form (
{type:"function","function":{"name":"..."}}) logged + dropped.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.Module-level event helpers (
Res*Evt)Hoisted from inside
EmitResponsesStreamto module scope so both the single-delta path (EmitResponsesStream, used by legacyRunToolLoop) and the true-streaming path (StreamResponsesViaProvider, used by passthrough) build events from the same code.TResponsesStreamStateHolds streaming state and exposes
OnChunkas a method-of-object the provider'sTStreamCallbackbinds to.HandleResponsesdispatch matrixHasFunctionToolsWantsStreamStreamResponsesViaProvider(real streaming, Codex's normal mode)Provider.Chat()+WriteJSONRunToolLoop+EmitResponsesStream(single-delta)RunToolLoop+WriteJSONhttps://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code