Skip to content

Studio: improve OpenAI- and Anthropic-compatible API spec compliance - #6010

Merged
wasimysaid merged 37 commits into
unslothai:mainfrom
oobabooga:api-spec-compliance
Jun 9, 2026
Merged

wasimysaid merged 37 commits into
unslothai:mainfrom
oobabooga:api-spec-compliance

Conversation

@oobabooga

@oobabooga oobabooga commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

The /v1/* endpoints implement the OpenAI and Anthropic HTTP APIs so the official SDKs, and tools built on them, can talk to a local Unsloth model without changes. Several responses diverged from what those specs define. This PR fixes them.

Each item below is the old behavior and the new behavior. Everything was checked against the official machine-readable OpenAPI specs (links at the bottom), so any of it can be re-verified.

Changes

Ordered roughly by impact on a standard SDK client.

Token counts and status codes (most impactful)

  • Over-context returns a 400 error, not a 500. llama-server returns a 400 when the prompt exceeds the context window; Studio was wrapping it as a 500. The official SDKs retry 5xx by default and do not retry a 400. It is now mapped to a 400 with code: "context_length_exceeded" (OpenAI) and type: "invalid_request_error" (Anthropic) on the non-streaming path. On a stream the 200 headers are already sent, so the same code/type are surfaced in the body instead: OpenAI as an error chunk carrying the code, Anthropic as an error event (previously the stream ended with an empty end_turn).
  • Truncation is reported correctly. When output stops because it hit the token cap, OpenAI now returns finish_reason: "length" and Anthropic stop_reason: "max_tokens". On the default GGUF paths these previously returned the natural-stop value ("stop" and "end_turn"), so a capped response looked identical to a complete one. The value comes from llama-server's finish_reason, which those paths were discarding.
  • POST /v1/messages/count_tokens is implemented (was 405). It counts input tokens with the loaded model's tokenizer and returns {"input_tokens": N}, the shape the Anthropic spec defines.
  • Streaming message_start.usage.input_tokens is populated (was 0). The non-streaming path already reported it. Tool-schema tokens are included when the model's chat template renders tool declarations (best-effort, via llama-server's /apply-template).
  • n > 1 is honored on the GGUF non-streaming path (it was ignored before, always returning a single choice). With multiple choices, prompt_tokens is counted once and total_tokens is prompt_tokens + sum(completion_tokens), so usage is not inflated by n. The OpenAI spec notes you are charged on generated tokens across all choices (the n field on /chat/completions).
  • Usage detail fields added: prompt_tokens_details and completion_tokens_details (OpenAI) match the CompletionUsage shape in the spec; cache_creation_input_tokens and cache_read_input_tokens (Anthropic) are two fields from the spec's Usage schema, now emitted (Studio does not implement the full Usage schema). All are zero where Studio has nothing to report.

Structured output

  • response_format (json_object, json_schema) returns raw JSON to public clients. The field reaches llama-server, whose GBNF grammar constrains the output to the JSON shape and types (it does not check semantic content, and any reasoning_content is unconstrained). Every such response was also being wrapped in a ```json markdown fence that only the internal data-recipe parser needs, which broke json.loads() for everyone else. That wrap is now opt-in, so public clients get the unwrapped JSON.

Request params

  • max_completion_tokens is honored on every path, including the tool and response_format passthrough. It was absent from the request model, so when it was the only cap set (no max_tokens) it was dropped and the response was not capped. It is OpenAI's current field; max_tokens is deprecated.
  • stop is honored on the plain GGUF chat path. It was already forwarded on the tool and response_format passthrough, and Anthropic stop_sequences already worked, but the plain chat path ignored it and left the sequence in the output.
  • parallel_tool_calls: false (OpenAI) and disable_parallel_tool_use (Anthropic) cap the response to one tool call (best-effort: extra calls are filtered from llama-server's output).
  • developer role is accepted and treated as system (was rejected with 422).

Error shapes

  • Client errors on /v1/* use the provider error envelopes, OpenAI {"error": {message, type, param, code}} and Anthropic {"type": "error", "error": {type, message}}, instead of FastAPI's {"detail": ...}, and request validation returns 400 instead of 422. The OpenAI envelope matches the spec Error schema. The Anthropic envelope matches ErrorResponse, including the required (nullable) top-level request_id (emitted as null, since Studio has no request-id system). /api/* and the frontend keep the {"detail": ...} shape.
  • A malformed tools entry returns 400 instead of 500. llama-server returns 500 "Failed to parse tools"; Studio now validates the tool shape first.

Metadata and smaller fixes

  • GET /v1/models/{id} is implemented. It was unrouted, so it returned 200 with a {"error": ...} body.
  • Legacy /v1/completions response ids use the cmpl- prefix (was chatcmpl-).
  • The trailing streaming usage chunk is only sent when stream_options.include_usage is set (was always sent).
  • Tool-use ids use the Anthropic toolu_ prefix.

Notes

  • Backend only. No frontend changes. One /api/* file (routes/data_recipe/jobs.py) gets a one-line opt-in flag so its output stays the same after the response_format default changed. The /v1/* error envelopes are scoped to /v1/ only, so other /api/* responses are unaffected.
  • Unknown model names are accepted by design. The requested model name is an informational label and the loaded model always answers, following the drop-in single-model convention of local servers like llama-server and textgen. Only a null or non-string model is rejected (400). The endpoints deliberately do not validate the model name.

Specs

Validated against the official OpenAPI specs. They are raw and machine-readable, so they are easy to grep or hand to an AI agent for review:

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request enhances the OpenAI and Anthropic compatibility layers by adding request ID middleware, standardizing error envelopes, implementing prompt token counting, and supporting advanced parameters like sequential generation for n > 1 and parallel tool call limits. Feedback from the review suggests several robustness improvements: forwarding openai_tools to the Anthropic streaming token counter to prevent undercounting, defensively verifying that streaming chunks are dictionaries before calling .get(), ensuring trailing SSE events are properly terminated with \n\n, and checking the cancellation status between sequential generation loops to avoid redundant processing.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

I am having trouble creating individual review comments. Click here to see my feedback.

studio/backend/routes/inference.py (5533-5549)

high

Pass openai_tools to _anthropic_tool_stream and forward it to count_chat_tokens so that tool-schema tokens are counted in the streaming input_tokens. Otherwise, the streaming input_tokens will undercount compared to the non-streaming and count_tokens paths, which is inconsistent with the passthrough path implementation.

    run_gen,
    message_id,
    model_name,
    llama_backend = None,
    openai_messages = None,
    openai_tools = None,
    disable_parallel_tool_use = False,
):
    """Streaming response for the tool-calling path."""
    _sentinel = object()

    # Prompt-token count for message_start.usage.input_tokens. count_chat_tokens
    # makes blocking HTTP calls to llama-server, so run it off the event loop.
    input_tokens = 0
    if llama_backend is not None and openai_messages is not None:
        input_tokens = await asyncio.to_thread(
            llama_backend.count_chat_tokens, openai_messages, None, openai_tools
        )

studio/backend/routes/inference.py (5487-5490)

high

Pass openai_tools to _anthropic_tool_stream to ensure tool-schema tokens are correctly counted in the streaming input_tokens.

                llama_backend = llama_backend,
                openai_messages = openai_messages,
                openai_tools = openai_tools,
                disable_parallel_tool_use = _disable_parallel,

studio/backend/routes/inference.py (162-167)

medium

Defensively check if chunk is a dictionary before calling .get() on it. If json.loads parses a non-dictionary JSON literal (such as a list or a boolean), calling .get() will raise an AttributeError and crash the stream.

def _drop_parallel_tool_call_deltas(chunk) -> bool:
    """In-place: drop tool_call deltas whose index >= 1 from a parsed OpenAI
    streaming chunk so only the first tool call survives (parallel_tool_calls=false
    / disable_parallel_tool_use, best-effort). Returns True if anything changed."""
    if not isinstance(chunk, dict):
        return False
    changed = False
    for ch in chunk.get("choices") or []:
References
  1. When parsing literals using ast.literal_eval where a dictionary is expected, defensively verify that the evaluated object is indeed a dictionary (e.g., using isinstance(obj, dict)) before calling dictionary-specific methods like .get(). This prevents AttributeError crashes if the parsed literal is of an unexpected type (such as a set, list, or None).

studio/backend/routes/inference.py (4232-4235)

medium

Ensure that the trailing event yielded from the buffer is terminated with \n\n. SSE events must be separated by a blank line (\n\n) to be correctly parsed by clients. Yielding the trailing event without a trailing \n\n can cause some client SSE parsers to hang or discard the final event.

                if buffer:
                    out = _cmpl_stream_event_out(buffer, _include_usage)
                    if out is not None:
                        yield out + b"\\n\\n"

studio/backend/routes/inference.py (3444-3448)

medium

Check if cancel_event is set before starting the next sequential generation iteration. If the request is cancelled during an earlier iteration, continuing to call gguf_generate() for subsequent choices will perform redundant connection attempts and raise unhandled GeneratorExit exceptions (which inherit from BaseException and are not caught by except Exception:).

                for _idx in range(_n):
                    if cancel_event.is_set():
                        break
                    full_text = ""
                    completion_usage = None
                    completion_finish = None
                    for token in gguf_generate():

@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: 2ff02f0947

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
@oobabooga

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly enhances the OpenAI and Anthropic API compatibility layers. Key additions include a new token-counting endpoint for Anthropic, support for the 'developer' role, request ID middleware, robust error-envelope wrapping for /v1/* endpoints, and sequential generation support for the n parameter. The review feedback highlights three main areas for improvement: defensively handling None in _message_delta_usage to prevent an AttributeError, ensuring elements in tool_calls are dictionaries before calling .get() during parallel tool call filtering, and correctly ignoring intermediate events (like text or status updates) when dropping parallel tool calls in the Anthropic streaming generator.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

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

@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: 26e6e0d552

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
@oobabooga oobabooga changed the title Studio: fix OpenAI- and Anthropic-compatible API spec compliance Studio: improve OpenAI- and Anthropic-compatible API spec compliance Jun 4, 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: e97a1b014f

ℹ️ 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 thread studio/backend/models/inference.py Resolved

@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: a5f7f0df3c

ℹ️ 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 thread studio/backend/routes/inference.py Resolved

@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: af43d5b9f7

ℹ️ 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".

@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: 35689f1a42

ℹ️ 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 thread studio/backend/routes/inference.py Resolved

@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: 4ff99f54b1

ℹ️ 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 thread studio/backend/routes/inference.py Resolved

@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: 3ea2b35005

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
@wasimysaid
wasimysaid requested a review from danielhanchen as a code owner June 5, 2026 20:42

@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: 5b6f657ae1

ℹ️ 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 thread studio/backend/models/inference.py Resolved

@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: bf0c61e581

ℹ️ 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 thread studio/backend/models/inference.py Resolved
@oobabooga

Copy link
Copy Markdown
Member Author

Thanks @wasimysaid, I have reviewed all of your commits and agree with all of them. Also ran several live spec compliance tests and found no regressions.

Nice that you fixed the n = 8 limit, that was indeed arbitrary.

The PR should be good to merge as-is.

oobabooga and others added 3 commits June 8, 2026 18:14
# Conflicts:
#	studio/backend/core/inference/llama_cpp.py
#	studio/backend/models/inference.py
#	studio/backend/routes/inference.py

@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: 0803048139

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
@wasimysaid wasimysaid self-assigned this Jun 9, 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: b197533ea2

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
wasimysaid and others added 2 commits June 9, 2026 15:19
Resolve Studio inference conflicts and preserve OpenAI stream usage opt-in on passthrough requests.

@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: c088a97f0f

ℹ️ 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 thread studio/backend/models/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/models/inference.py Resolved

@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: e65479f79f

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
@wasimysaid

Copy link
Copy Markdown
Collaborator

did a live smoke check on this PR with a local Studio server and Qwen3.5 4B GGUF loaded.

Checked chat completions, stream usage opt in, Responses stream usage with parallel_tool_calls=false, Anthropic streaming tool use, and n plus seed.

All passed.

@wasimysaid
wasimysaid merged commit 57be586 into unslothai:main Jun 9, 2026
30 checks passed
@oobabooga

Copy link
Copy Markdown
Member Author

I have reviewed all of your new commits in this PR and agree with them, and my tests show no regressions. Thanks, @wasimysaid!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants