Skip to content

Studio: forward standard OpenAI tools / tool_choice to llama-server - #5061

Closed
rolandtannous wants to merge 21 commits into
mainfrom
feature/tool-choice-kwarg-openai-format
Closed

rolandtannous wants to merge 21 commits into
mainfrom
feature/tool-choice-kwarg-openai-format

Conversation

@rolandtannous

@rolandtannous rolandtannous commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Solves #4999

Studio's /v1/chat/completions endpoint silently stripped standard OpenAI tools / tool_choice fields before forwarding to llama-server, so clients using standard function calling (opencode, Claude Code via OpenAI compat, Cursor, Continue, ...) never received structured tool_calls back — they got plain text with raw tool-call tokens leaked into content. 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: accept role="tool" + optional tool_call_id / tool_calls / name; make content optional (assistant with only tool_calls)
  • ChatCompletionRequest: add tools, tool_choice, stop; set extra="allow"
  • New _openai_passthrough_stream / _openai_passthrough_non_streaming helpers
  • Routing branch in openai_chat_completions — triggers when tools is present without Studio's enable_tools shorthand, so the existing server-side agentic loop is untouched
  • Vision + tools: legacy image_base64 spliced into the last user message as an image_url content part so vision-and-tools-capable GGUFs work transparently

2. Honor tool_choice on /v1/messages (secondary fix)

Previously tool_choice was accepted on the request model but was set always to auto. Now translates Anthropic's four shapes to OpenAI format and forwards:

Anthropic OpenAI
{"type": "auto"} "auto"
{"type": "any"} "required"
{"type": "none"} "none"
{"type": "tool", "name": "X"} {"type": "function", "function": {"name": "X"}}

3. Hardening

  • _friendly_error() recognizes httpx.RequestError subclasses — surfaces "Lost connection to the model server" instead of the generic "An internal error occurred" when llama-server is unreachable
  • Non-streaming passthrough wraps the httpx POST in try/except — raises 502 with friendly detail instead of a bare 500
  • Completes the 5cedd9a5 asyncgen cleanup fix: explicitly aclose() the aiter_lines() / aiter_bytes() iterator in the finally block 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.x

4. stream default correction

ChatCompletionRequest.stream now defaults to False, matching OpenAI's spec. Previously defaulted to True, silently switching naive curl clients that omit the field into SSE. Studio's own frontend always sets stream explicitly on every call site, so no UI impact.

Test plan

  • [x ] 16 E2E tests pass in studio/backend/tests/test_studio_api.py — includes 5 new OpenAI function-calling tests (non-stream, stream, multi-turn, OpenAI SDK, vision+tools) + 1 Anthropic tool_choice regression test
  • [x ] Unit tests pass in studio/backend/tests/test_openai_tool_passthrough.py — Pydantic model validation, tool_choice translator, _build_passthrough_payload, _friendly_error httpx mappings, stream default regression
  • [x ] Manual smoke with gpt-oss-20b: curl /v1/chat/completions with tool_choice: "required" → finish_reason: "tool_calls" + correct tool_calls array + non-zero usage.prompt_tokens
  • [x ] Manual smoke with gpt-oss-20b: curl /v1/messages with tool_choice: {"type": "any"} → stop_reason: "tool_use" + correct tool_use content block
  • [x ] Existing Studio web UI chat unaffected (frontend always sets stream explicitly)
  • [ x] Existing enable_tools: true server-side agentic path unaffected
tests_openai_tool_pass tests_server_startup tests_studio_api tests_tool_choice test_regular_call tests_anthropic_endpoint_tool_choice_pass tests_openai_endpoint_tool_pass

Roland Tannous added 4 commits April 15, 2026 17:18
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.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

Comment thread studio/backend/routes/inference.py Dismissed

@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: 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".

Comment thread studio/backend/routes/inference.py Resolved
@rolandtannous

rolandtannous commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor Author

proof server side tools still work fine

server-side-tools-still-work.mp4
openai_server_side_tools.mp4

@danielhanchen

Copy link
Copy Markdown
Member

Stale-rebase detected — auto-fix NOT applied. This PR would silently revert 120 lines across 10 files that already landed on origin/main. Auto-merge was not attempted (or failed — see review workspace logs).

Top reverted files:

  • studio/frontend/src/features/settings/tabs/general-tab.tsx — 35 line(s)
  • studio/frontend/src/features/settings/tabs/about-tab.tsx — 21 line(s)
  • studio/backend/main.py — 19 line(s)
  • studio/frontend/src/features/onboarding/components/wizard-layout.tsx — 17 line(s)
  • studio/frontend/src/features/onboarding/components/wizard-footer.tsx — 11 line(s)

To recover, pull main into the PR branch and push:

git fetch origin && git merge origin/main --no-edit && git push

The auto-review is still running against the unfixed tree; its findings may be unreliable until you push a clean rebase.

@danielhanchen danielhanchen added the auto-reviewing Auto-review in progress label Apr 16, 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: 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".

Comment thread studio/backend/models/inference.py Resolved
Roland Tannous and others added 3 commits April 16, 2026 21:10
…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.

@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: 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".

Comment on lines +3189 to +3192
},
}
yield f"data: {json.dumps(err)}\n\n"
return

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 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 👍 / 👎.

Comment on lines +350 to +352
content: Optional[Union[str, list[ContentPart]]] = Field(
None, description = "Message content (string or multimodal parts)"
)

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 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 👍 / 👎.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Apr 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Apr 16, 2026
@danielhanchen danielhanchen added auto-review-failed Auto-review rejected the PR and removed auto-reviewing Auto-review in progress labels Apr 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Auto-review verdict: Changes requested

Reason: no verdict parsed; defaulting based on commit history

@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: 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".

Comment on lines +378 to +380
else:
if self.content is None:
raise ValueError(f"{self.role} messages require content")

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 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 👍 / 👎.

@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: 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".

Comment on lines +1155 to +1160
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.",
)

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 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 👍 / 👎.

@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: 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".

Comment on lines +3233 to +3235
yield f"data: {json.dumps(err)}\n\n"
yield "data: [DONE]\n\n"
return

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 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 👍 / 👎.

danielhanchen and others added 5 commits April 16, 2026 18:39
…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.

@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: 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".

Comment on lines +2432 to +2433
if server_tools and payload.tool_choice is not None:
raise HTTPException(

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 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 👍 / 👎.

Comment on lines +3108 to +3109
if not payload.image_base64:
return messages

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 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 👍 / 👎.

@rolandtannous

Copy link
Copy Markdown
Contributor Author

superseded by #5099. closing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-review-failed Auto-review rejected the PR auto-stale-rebase

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants