Repository navigation
Studio: forward standard OpenAI tools / tool_choice to llama-server - #5061
rolandtannous wants to merge 21 commits into
Conversation
Studio's /v1/chat/completions silently stripped standard OpenAI `tools`
and `tool_choice` fields, so clients using standard function calling
(opencode, Claude Code, Cursor, Continue, ...) never got structured
tool_calls back. Adds a client-side pass-through path mirroring the
existing Anthropic /v1/messages flow: when `tools` is present without
Studio's `enable_tools` shorthand, the request is forwarded to
llama-server verbatim so the client sees native id, finish_reason
("tool_calls"), delta.tool_calls, and accurate usage tokens.
Also wires Anthropic tool_choice forwarding: /v1/messages previously
accepted tool_choice on the request model but silently dropped it with
a warning. Translate the four Anthropic shapes to OpenAI format and
forward them so agentic clients can actually enforce tool use.
- ChatCompletionRequest: add tools, tool_choice, stop; extra="allow"
- ChatMessage: accept role="tool", optional tool_call_id / tool_calls /
name; content is now optional (assistant with only tool_calls)
- routes/inference.py: _openai_passthrough_stream /
_openai_passthrough_non_streaming helpers, routing branch in
openai_chat_completions, vision+tools via content-parts injection
- _build_passthrough_payload: tool_choice parameter (default "auto")
- anthropic_compat: anthropic_tool_choice_to_openai() translator
- tests/test_openai_tool_passthrough.py: Pydantic + translator unit tests
- tests/test_studio_api.py: 5 new E2E tests (non-stream, stream,
multi-turn, OpenAI SDK, Anthropic tool_choice=any regression)
When the managed llama-server subprocess crashes mid-request, the async pass-through helpers in routes/inference.py used to return a bare 500 (non-streaming) or an "An internal error occurred" SSE chunk (streaming) because _friendly_error only recognized the sync path's "Lost connection to llama-server" substring -- httpx transport failures (ConnectError / ReadError / RemoteProtocolError / ReadTimeout) stringify differently and fell through to the generic case. - _friendly_error: map any httpx.RequestError subclass to the same "Lost connection to the model server" message the sync chat path emits. Placed before the substring heuristics so the streaming path automatically picks it up via its existing except Exception catch. - _openai_passthrough_non_streaming: wrap the httpx.AsyncClient.post in a try/except httpx.RequestError and re-raise as HTTPException 502 with the friendly detail. - tests/test_openai_tool_passthrough.py: new TestFriendlyErrorHttpx class pinning the mapping for ConnectError, ReadError, RemoteProtocolError, ReadTimeout, and confirming non-httpx paths (context-size heuristic, generic fallback) are unchanged.
The httpcore asyncgen cleanup fix in 5cedd9a is incomplete on Python 3.13 + httpcore 1.0.x: it switched to manual client/response lifecycle but still used anonymous `async for raw_line in resp.aiter_lines():` patterns in all three streaming paths. Python's async for does NOT auto-close the iterator on break/return, so the aiter_lines / aiter_bytes async generator remains alive, reachable only from the surrounding coroutine frame. Once `_stream()` returns the frame is GC'd and the orphaned asyncgen is finalized on a LATER GC pass in a DIFFERENT asyncio task, where httpcore's HTTP11ConnectionByteStream.aclose() enters anyio.CancelScope.__exit__ with a mismatched task and prints "Exception ignored in: <async generator>" / "async generator ignored GeneratorExit" / "Attempted to exit cancel scope in a different task" to the server log. User observed this on /v1/messages after successful (status 200) requests, with the traceback pointing at HTTP11ConnectionByteStream .__aiter__ / .aclose inside httpcore. Fix: save resp.aiter_lines() / resp.aiter_bytes() as a variable and explicitly `await iter.aclose()` in the finally block BEFORE resp.aclose() / client.aclose(). This closes the asyncgen inside the current task's event loop, so the internal httpcore byte stream is cleaned up before Python's asyncgen GC hook has anything orphaned to finalize. Each aclose is wrapped in try/except Exception so nested anyio cleanup noise can't bubble out. Applied to all three streaming passthrough paths: - _anthropic_passthrough_stream (/v1/messages client-side tool path) - _openai_passthrough_stream (/v1/chat/completions client-side tool path, new in this PR) - openai_completions (/v1/completions bytes proxy from PR #4956)
… spec OpenAI's /v1/chat/completions spec defaults `stream` to false, so clients that omit the field (naive curl, minimal integrations) expect a single JSON response back. Studio was defaulting to true, silently switching those clients into SSE and breaking any parser that didn't also handle streaming. ResponsesRequest and AnthropicMessagesRequest already default to false correctly; only ChatCompletionRequest was wrong. Studio's own frontend always sets `stream` explicitly on every chat-adapter / chat-api / runtime-provider call site, so the flip has no UI impact. SDK users (OpenAI Python/JS SDK, opencode, Claude Code, Cursor, Continue) also always pass `stream` explicitly, so they're unaffected. The only clients feeling the change are raw-curl users who were relying on the wrong default -- those get the correct OpenAI behavior now. Added a regression test pinning the default so it can't silently flip back.
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9bd7d1ec20
ℹ️ 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".
|
proof server side tools still work fine server-side-tools-still-work.mp4openai_server_side_tools.mp4 |
|
Stale-rebase detected — auto-fix NOT applied. This PR would silently revert 120 lines across 10 files that already landed on Top reverted files:
To recover, pull main into the PR branch and push: git fetch origin && git merge origin/main --no-edit && git pushThe auto-review is still running against the unfixed tree; its findings may be unreliable until you push a clean rebase. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 09e1625e63
ℹ️ 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".
…GUFs The new tool passthrough branch runs before _extract_content_parts, skipping the existing not is_vision guard. Requests combining tools with an image on a text-only tool-capable GGUF were forwarded to llama-server, producing opaque upstream errors instead of the pre-existing clear 400. Restore the guard inline at the dispatch point, checking both legacy image_base64 and inline image_url parts.
Enforce the OpenAI spec rule that role="tool" messages must carry a tool_call_id. Without it, upstream backends cannot associate a tool result with the assistant's prior tool_calls entry and the request fails in non-obvious ways through the passthrough path. Reject at the request boundary with a 422 instead.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7a7805db6
ℹ️ 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".
| }, | ||
| } | ||
| yield f"data: {json.dumps(err)}\n\n" | ||
| return |
There was a problem hiding this comment.
Preserve upstream status codes in streaming passthrough
When llama-server rejects a streamed /v1/chat/completions request (for example invalid tool_choice or schema), this branch emits an SSE error payload but still returns HTTP 200 because the StreamingResponse has already been established. OpenAI SDK clients rely on non-2xx status codes to raise API exceptions, so this turns request failures into ambiguous stream data and breaks normal error handling compared with the non-streaming passthrough path.
Useful? React with 👍 / 👎.
| content: Optional[Union[str, list[ContentPart]]] = Field( | ||
| None, description = "Message content (string or multimodal parts)" | ||
| ) |
There was a problem hiding this comment.
Enforce role-aware content requirements in ChatMessage
This change makes content optional for every role, but only validates tool_call_id for role="tool". As a result, malformed messages like user/tool entries without content now pass request validation; downstream code either silently drops them (_extract_content_parts) or forwards invalid payloads to llama-server, causing hard-to-debug behavior. The schema should only allow content=None for assistant tool-call messages and require non-empty content for other roles.
Useful? React with 👍 / 👎.
…nai-format' into pr-5061-head # Conflicts: # studio/backend/models/inference.py # studio/backend/routes/inference.py
|
Auto-review verdict: Changes requested Reason: no verdict parsed; defaulting based on commit history |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 750f5aa132
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| else: | ||
| if self.content is None: | ||
| raise ValueError(f"{self.role} messages require content") |
There was a problem hiding this comment.
Enforce role constraints for tool-call metadata
ChatMessage._validate_role_shape only checks content for non-assistant/non-tool roles, so tool_calls, tool_call_id, and name are currently accepted on user/system messages. In this commit that becomes user-visible because openai_chat_completions now enters passthrough whenever any(m.role == "tool" or m.tool_calls), so malformed non-assistant messages with tool_calls can be forwarded to llama-server and fail upstream instead of being rejected at request validation time. Tightening role-aware validation here would prevent these opaque passthrough failures.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a545064907
ℹ️ 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".
| if _openai_tool_passthrough: | ||
| if (payload.image_base64 or _has_inline_image) and not llama_backend.is_vision: | ||
| raise HTTPException( | ||
| status_code = 400, | ||
| detail = "Image provided but current GGUF model does not support vision.", | ||
| ) |
There was a problem hiding this comment.
Enforce non-system message check before passthrough
This early _openai_tool_passthrough return runs before the existing if not chat_messages validation, so requests that include tools but only system messages (or an empty messages list) are now forwarded upstream instead of being rejected with Studio’s clear 400. That makes behavior inconsistent between tool and non-tool calls and can surface as opaque llama-server errors for an input shape the route previously rejected deterministically.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a545064907
ℹ️ 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".
| yield f"data: {json.dumps(err)}\n\n" | ||
| yield "data: [DONE]\n\n" | ||
| return |
There was a problem hiding this comment.
Propagate upstream status for streamed passthrough errors
When llama-server rejects a streamed /v1/chat/completions request, this branch emits an SSE error payload and [DONE] but returns normally, so FastAPI keeps the HTTP status at 200. In that scenario, OpenAI SDK clients (and similar wrappers) do not raise API exceptions because they key off non-2xx statuses, which turns hard request failures (invalid tool_choice, bad schema, etc.) into ambiguous in-stream data and breaks normal error handling.
Useful? React with 👍 / 👎.
…suite The 10 test_pr5061_r2_*.py files at repo root tests/ had three issues: wrong directory (studio tests live at studio/backend/tests/), PR number baked into filenames, and two files (anthropic_nonstream_502, anthropic_tool_choice_warn) duplicated coverage already in Roland's TestFriendlyErrorHttpx / TestAnthropicToolChoiceToOpenAI. A third file (nonstream_upstream_log) pinned logger-call shape, which is brittle diagnostic noise. Dropped the three low-value files and merged the rest into studio/backend/tests/test_openai_tool_passthrough.py as generic classes: - TestLlamaAuthHeaders - TestOpenAIMessagesForPassthrough - TestOpenAIChatCompletionsToolGuards - TestAnthropicEnableToolsToolChoiceConflict - TestOpenAIPassthroughNonStreaming (verbatim body + httpx 502 mapping) - TestOpenAIPassthroughStreamVerbatim - TestOpenAIPassthroughStreamErrorTermination Test count: 65 tests across 8 Test* classes. Net -316 lines.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 343a25c6e8
ℹ️ 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".
| if server_tools and payload.tool_choice is not None: | ||
| raise HTTPException( |
There was a problem hiding this comment.
Permit no-op tool_choice on enable_tools requests
This guard now rejects every enable_tools=true request whenever tool_choice is present, including the no-op {"type":"auto"} shape. In that scenario, server-side tool execution is blocked with a 400 even though auto does not request a specific tool and was previously tolerated, so Anthropic-compatible clients that include tool_choice by default can fail unexpectedly. The check should only reject incompatible choices (or ignore auto) rather than rejecting all non-null values.
Useful? React with 👍 / 👎.
| if not payload.image_base64: | ||
| return messages |
There was a problem hiding this comment.
Normalize inline image_url parts before passthrough
This early return means the passthrough path only normalizes images when legacy image_base64 is used, but leaves standard OpenAI inline image_url parts untouched. Because the GGUF path explicitly converts images to PNG for llama-server compatibility, tool passthrough requests that carry inline non-PNG data URLs can fail upstream while equivalent non-tool requests succeed. Inline image parts should go through the same normalization step.
Useful? React with 👍 / 👎.
|
superseded by #5099. closing |
Summary
Solves #4999
Studio's
/v1/chat/completionsendpoint silently stripped standard OpenAItools/tool_choicefields before forwarding to llama-server, so clients using standard function calling (opencode, Claude Code via OpenAI compat, Cursor, Continue, ...) never received structuredtool_callsback — they got plain text with raw tool-call tokens leaked intocontent. This PR adds a client-side pass-through that forwards these fields to llama-server verbatim and returns the native response. Bundles three related fixes in the same OpenAI-compat spirit. the /v1/messages endpoint worked fine and was proven to work with Claude code and openclaw.Changes
1. OpenAI function-calling pass-through on
/v1/chat/completions(primary fix for #4999)ChatMessage: acceptrole="tool"+ optionaltool_call_id/tool_calls/name; makecontentoptional (assistant with onlytool_calls)ChatCompletionRequest: addtools,tool_choice,stop; setextra="allow"_openai_passthrough_stream/_openai_passthrough_non_streaminghelpersopenai_chat_completions— triggers whentoolsis present without Studio'senable_toolsshorthand, so the existing server-side agentic loop is untouchedimage_base64spliced into the last user message as animage_urlcontent part so vision-and-tools-capable GGUFs work transparently2. Honor
tool_choiceon/v1/messages(secondary fix)Previously
tool_choicewas accepted on the request model but was set always toauto. Now translates Anthropic's four shapes to OpenAI format and forwards:{"type": "auto"}"auto"{"type": "any"}"required"{"type": "none"}"none"{"type": "tool", "name": "X"}{"type": "function", "function": {"name": "X"}}3. Hardening
_friendly_error()recognizeshttpx.RequestErrorsubclasses — surfaces "Lost connection to the model server" instead of the generic "An internal error occurred" when llama-server is unreachable502with friendly detail instead of a bare 5005cedd9a5asyncgen cleanup fix: explicitlyaclose()theaiter_lines()/aiter_bytes()iterator in thefinallyblock of all three streaming passthroughs (/v1/messages,/v1/chat/completions,/v1/completions). Fixes "async generator ignored GeneratorExit" / "Attempted to exit cancel scope in a different task" on Python 3.13 + httpcore 1.0.x4.
streamdefault correctionChatCompletionRequest.streamnow defaults toFalse, matching OpenAI's spec. Previously defaulted toTrue, silently switching naive curl clients that omit the field into SSE. Studio's own frontend always setsstreamexplicitly on every call site, so no UI impact.Test plan
studio/backend/tests/test_studio_api.py— includes 5 new OpenAI function-calling tests (non-stream, stream, multi-turn, OpenAI SDK, vision+tools) + 1 Anthropictool_choiceregression teststudio/backend/tests/test_openai_tool_passthrough.py— Pydantic model validation,tool_choicetranslator,_build_passthrough_payload,_friendly_errorhttpx mappings,streamdefault regression/v1/chat/completionswithtool_choice: "required"→finish_reason: "tool_calls"+ correcttool_callsarray + non-zerousage.prompt_tokens/v1/messageswithtool_choice: {"type": "any"}→stop_reason: "tool_use"+ correcttool_usecontent blockstreamexplicitly)enable_tools: trueserver-side agentic path unaffected