Repository navigation
Studio: improve OpenAI- and Anthropic-compatible API spec compliance - #6010
Conversation
There was a problem hiding this comment.
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)
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)
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)
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
- When parsing literals using
ast.literal_evalwhere a dictionary is expected, defensively verify that the evaluated object is indeed a dictionary (e.g., usingisinstance(obj, dict)) before calling dictionary-specific methods like.get(). This preventsAttributeErrorcrashes if the parsed literal is of an unexpected type (such as a set, list, orNone).
studio/backend/routes/inference.py (4232-4235)
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)
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():There was a problem hiding this comment.
💡 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".
… and small stream-handling guards
|
/gemini review |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
|
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 The PR should be good to merge as-is. |
# Conflicts: # studio/backend/core/inference/llama_cpp.py # studio/backend/models/inference.py # studio/backend/routes/inference.py
…ontext bar and tok/s repopulate
There was a problem hiding this comment.
💡 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".
…top_reason, tool_result id correlation, and parallel-tool execution cap
There was a problem hiding this comment.
💡 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".
Resolve Studio inference conflicts and preserve OpenAI stream usage opt-in on passthrough requests.
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
|
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. |
|
I have reviewed all of your new commits in this PR and agree with them, and my tests show no regressions. Thanks, @wasimysaid! |
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)
400error, not a500. llama-server returns a400when the prompt exceeds the context window; Studio was wrapping it as a500. The official SDKs retry 5xx by default and do not retry a400. It is now mapped to a400withcode: "context_length_exceeded"(OpenAI) andtype: "invalid_request_error"(Anthropic) on the non-streaming path. On a stream the200headers are already sent, so the same code/type are surfaced in the body instead: OpenAI as an error chunk carrying the code, Anthropic as anerrorevent (previously the stream ended with an emptyend_turn).finish_reason: "length"and Anthropicstop_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'sfinish_reason, which those paths were discarding.POST /v1/messages/count_tokensis implemented (was405). It counts input tokens with the loaded model's tokenizer and returns{"input_tokens": N}, the shape the Anthropic spec defines.message_start.usage.input_tokensis populated (was0). 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 > 1is honored on the GGUF non-streaming path (it was ignored before, always returning a single choice). With multiple choices,prompt_tokensis counted once andtotal_tokensisprompt_tokens + sum(completion_tokens), so usage is not inflated byn. The OpenAI spec notes you are charged on generated tokens across all choices (thenfield on/chat/completions).prompt_tokens_detailsandcompletion_tokens_details(OpenAI) match theCompletionUsageshape in the spec;cache_creation_input_tokensandcache_read_input_tokens(Anthropic) are two fields from the spec'sUsageschema, now emitted (Studio does not implement the fullUsageschema). 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 anyreasoning_contentis unconstrained). Every such response was also being wrapped in a ```json markdown fence that only the internal data-recipe parser needs, which brokejson.loads()for everyone else. That wrap is now opt-in, so public clients get the unwrapped JSON.Request params
max_completion_tokensis honored on every path, including the tool andresponse_formatpassthrough. It was absent from the request model, so when it was the only cap set (nomax_tokens) it was dropped and the response was not capped. It is OpenAI's current field;max_tokensis deprecated.stopis honored on the plain GGUF chat path. It was already forwarded on the tool andresponse_formatpassthrough, and Anthropicstop_sequencesalready worked, but the plain chat path ignored it and left the sequence in the output.parallel_tool_calls: false(OpenAI) anddisable_parallel_tool_use(Anthropic) cap the response to one tool call (best-effort: extra calls are filtered from llama-server's output).developerrole is accepted and treated assystem(was rejected with422).Error shapes
/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 returns400instead of422. The OpenAI envelope matches the specErrorschema. The Anthropic envelope matchesErrorResponse, including the required (nullable) top-levelrequest_id(emitted asnull, since Studio has no request-id system)./api/*and the frontend keep the{"detail": ...}shape.toolsentry returns400instead of500. llama-server returns500 "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 returned200with a{"error": ...}body./v1/completionsresponse ids use thecmpl-prefix (waschatcmpl-).usagechunk is only sent whenstream_options.include_usageis set (was always sent).toolu_prefix.Notes
/api/*file (routes/data_recipe/jobs.py) gets a one-line opt-in flag so its output stays the same after theresponse_formatdefault changed. The/v1/*error envelopes are scoped to/v1/only, so other/api/*responses are unaffected.modelnames 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 likellama-serverand textgen. Only anullor non-stringmodelis 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:
/chat/completions,/completions,/models,/models/{model}. The file is large, so grep for a path or schema name rather than reading it whole..ymlextension). If the hash ever rotates, the current URL is theopenapi_spec_urlfield in.stats.ymlonmainof https://github.com/anthropics/anthropic-sdk-typescript. Relevant paths:/v1/messages,/v1/messages/count_tokens.