Repository navigation
Studio: forward standard OpenAI tools / tool_choice to llama-server - #5099
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.
…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.
…acing Three related fixes called out by the PR review: 1. Preserve upstream status codes in the streaming passthrough. The httpx request is now dispatched before the StreamingResponse is constructed. Non-200 upstream responses and httpx RequestError transport failures raise HTTPException with the real status instead of being buried inside a 200 SSE error frame, so OpenAI SDK clients see APIError/BadRequestError/... as expected. 2. Require non-empty content on user/system/tool messages. Per the OpenAI spec, content may only be omitted on assistant messages that carry tool_calls; enforce that at the request boundary so malformed messages never reach the passthrough path. 3. Role-constrain tool-call metadata. tool_calls is only valid on role=assistant, tool_call_id and name only on role=tool. Without this, a user/system message with tool_calls would flip the passthrough branch on and be forwarded to llama-server, surfacing as an opaque upstream error.
|
proof server side tools still work fine server-side-tools-still-work.mp4openai_server_side_tools.mp4 |
There was a problem hiding this comment.
Code Review
This pull request implements standard OpenAI function-calling pass-through for GGUF models, allowing clients to utilize native tools and tool_choice fields. It updates the ChatMessage and ChatCompletionRequest models to support the OpenAI specification, including the tool role and structured tool_calls. Key improvements include enhanced error handling for connection failures, explicit iterator cleanup in async generators to support Python 3.13, and the addition of comprehensive integration tests. Feedback was provided regarding the optimization of JSON passthrough responses to reduce overhead and ensuring broader image mode compatibility during conversion to RGB.
Two Gemini-code-assist review findings on PR #5099: 1. Unconditionally convert decoded images to RGB before PNG encoding. The prior code only handled RGBA, letting CMYK/I/F images crash at img.save(format="PNG") and surface as opaque 400s. Applied to both the passthrough helper and the non-passthrough GGUF path that originally carried this pattern, keeping the two sites in sync. 2. Return the upstream JSON body as raw bytes via Response rather than parse-then-re-serialize with JSONResponse. Matches the passthrough helper's "verbatim" contract and drops a redundant round-trip.
|
fully retested with tool_choice + server side tools and claude. still working. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 595fba0ce9
ℹ️ 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".
| async with httpx.AsyncClient() as client: | ||
| resp = await client.post(target_url, json = body, timeout = 600) |
There was a problem hiding this comment.
Forward llama-server API key in passthrough calls
This new passthrough request is sent without auth headers, but when UNSLOTH_DIRECT_STREAM=1 the backend starts llama-server with --api-key and expects internal callers to send Authorization: Bearer ... (as existing llama_cpp.py helpers already do). In that mode, tool passthrough requests will get upstream 401s and standard OpenAI tool-calling breaks (same omission also appears in _openai_passthrough_stream). Please include llama_backend._api_key on these httpx calls.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I believe slopo's observation here is valid and is related to what I'm experiencing: start unsloth studio run --model, and observe that the tool calling breaks the openai-compatible messaging sent to opencode:
Hello
Type validation failed: Value: {"type":"tool_status","content":""}.
Error message: [
{
"code": "invalid_union",
"errors": [
[
{
"expected": "array",
"code": "invalid_type",
"path": [
"choices"
],
"message": "Invalid input: expected array, received undefined"
}
],
[
{
"expected": "object",
"code": "invalid_type",
"path": [
"error"
],
"message": "Invalid input: expected object, received undefined"
}
]
],
"path": [],
"message": "Invalid input"
}
]
If you instead start unsloth studio and pick a model from the web ui's chat's dropdown, the opencode problem doesn't happen any more:
Hello
Hello! How can I help you today?
Supersedes #5061
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