Skip to content

Fix Deep Research JSON output on MLX and Transformers - #10611

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
Imagineer99:fix/research-mlx-json-output
Sep 10, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
Imagineer99:fix/research-mlx-json-output

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

Problem

Deep Research sends response_format: {"type": "json_object"} for planning, decisions and synthesis audits. Studio's MLX and Transformers routes reject this guided-decoding parameter, so research fails before generation with “Local model request failed with HTTP 400.”

Change

Retry a local Research call once without response_format only when the API returns HTTP 400 with code=unsupported_parameter and param=response_format. Keep the JSON prompts and existing output validation. Recheck cancellation and lease ownership before retrying within the original timeout and transport retry budget.

Supported local backends and external providers retain their format contract. Direct API requests still receive the unsupported-format error; unrelated errors and repeated refusals propagate. Tool opt-outs remain intact, including when server tools are forced on.

Validation

  • The integration regression fails on unchanged baseline 4b6bc280a9 and passes with the fix.
  • 892 surrounding Research and chat API tests passed.
  • Final focused run: 37 passed, including 30 fallback regressions and 7 existing Research tool-gate checks. These overlap the broader suite.
  • Six live application scenarios passed using real Uvicorn/TCP, authentication, SQLite, worker leases, plan approval, event streaming and persisted assistant messages. The unchanged baseline reproduces the original 400; the fix completes a cited report. Additional cases cover invalid plans, invented fetch URLs, invalid audits and cancellation. All internal workflow keys were revoked.
  • Repository formatter and Ruff checks passed.
  • Earlier Linux/macOS ARM64 runner reproduction confirms the original bug; it does not validate this fix.

Limitations

The live validation scripts model generation and search responses. Actual MLX weights, Apple Silicon inference and the exact reported desktop build have not been tested. The fallback adds one refused HTTP request per JSON phase. JSON quality remains model-dependent: existing validation rejects invalid plans, can fall back to an approved search for invalid decisions, and can proceed without an invalid audit.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-09T16:57:25.564518Z ac084e2 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits the path in studio/backend/core/research_runs.py where json_mode always sends response_format and the non-GGUF route in routes/inference.py rejects it with a 400, so Research cannot start on MLX or Transformers. Will get this reviewed.

The fallback keyed on code=unsupported_parameter plus param=response_format
alone. routes.inference sends that same pair from three places: the non-GGUF
branch that has no grammar engine, the GGUF audio branch, and Unsloth's tool
loop. Only the first is answerable by re-sending the same prompt without the
contract; the other two refuse again, and an audio model that does support
speech synthesizes the planner prompt instead of reporting.

Require the grammar-engine message as well, and skip the retry when the local
backend serving the run is an audio model, since the non-GGUF branch refuses
the format before it reaches its own audio routing. Both probes are the ones
routes.inference itself branches on, and an unprobeable backend keeps the
existing behaviour.

The refusal fixture now carries the message the route actually sends, with the
audio and tool-loop messages added as negative cases. The wall-clock test moves
from 0.4s/0.25s to 1.6s/1.0s: same semantics, 600ms of scheduling slack instead
of 150ms, which is what it has to survive under -n 4 on a loaded runner.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and tested this. The bug is real, the fix works, and I pushed one commit to the branch narrowing the refusal it negotiates on.

Before and after

Before: _stream_completion sets response_format: {"type": "json_object"} whenever json_mode is on, which is planning, every decision step and the synthesis audit. On any non-GGUF backend routes/inference.py:21788 refuses that field with a 400, so Deep Research on MLX or Transformers dies before generating a single token.

After: that one refusal is negotiated away once per call and the run proceeds on prompt-only JSON, which the phases already ask for and already validate.

I proved the regression rather than taking it on trust. Merge base is 4b6bc280a9, so I checked out the branch, reverted only research_runs.py to the base version and kept your test file:

19 failed, 11 passed      # base worker, PR tests
36 passed                 # head worker (30 yours + 6 mine)

The 12 test_local_json_research_recovers_through_the_real_route cases fail on the base with httpx.HTTPStatusError: 400 raised out of _stream_completion through the real FastAPI route, which is exactly the reported failure, not a fixture artifact.

Does it break anything

No. CI-shaped full backend run (studio/backend, pytest tests/ -n 4 with the workflow's ignores and -k filter), three times:

Tree Result
merge base 4b6bc280a9 278 failed, 38167 passed, 365 errors
PR head 4b9a025d3 278 failed, 38197 passed, 365 errors
head plus my commit 278 failed, 38203 passed, 365 errors

The failing and erroring node id sets are byte-identical across all three (643 unique ids each, empty symmetric difference). Those are pre-existing environment gaps on this host, untouched by the PR. The passed delta is exactly the new test file.

Blast radius is genuinely small: the diff touches research_runs.py and one test file, routes/inference.py is unchanged, so direct API clients, /v1/responses, /v1/messages, the data recipe structured-output path and the frontend all keep their existing contract. _stream_completion is private with callers only inside ResearchSupervisor. No new persisted field, so a run created by an older build and resumed after upgrade is fine in both directions, and so is downgrading back.

On hardware: this is not a new hardware path. The route's discriminator is using_gguf = llama_backend.is_loaded, which is "a healthy llama-server child process exists". The [Windows, Linux, WSL, Mac] x [NVIDIA, AMD, CPU] matrix collapses to two states, llama.cpp loaded or not, and the vendor never selects the branch. is_mlx is a label on the same non-GGUF path, which is why your parametrization over it correctly shows no difference. Both changed files are pure asyncio and httpx with no path, signal or event-loop assumption, so Windows' ProactorEventLoop and macOS behave the same. No browser surface is involved.

What I changed

The predicate matched code=unsupported_parameter plus param=response_format and nothing else, but routes/inference.py sends that same pair from three places:

  • :21788 no grammar engine, the intended target
  • :21747 GGUF audio, "response_format cannot be honored by an audio reply"
  • :22452 Unsloth tool loop, "send the request without enable_tools to use guided decoding"

I drove all three through the real route. The tool-loop one is unreachable for Research (it sits behind _explicit_studio_tool_loop_requested, which needs enable_tools or mcp_enabled, and a CLI --enable-tools policy does not satisfy it). The audio one is reachable: nothing in _sanitize_config stops a TTS model from being the research model, and worse, on the non-GGUF side the grammar refusal fires at :21789 before the is_audio routing at :21797, so the retry falls into text-to-speech. With a scripted backend it just 400s again, but a model whose audio_type is in _TRANSFORMERS_TTS_AUDIO_TYPES would synthesize the planner prompt to a clip and then stall the run on a reply carrying no SSE, where before it got a 400 that named the problem.

So the commit does two things:

  1. requires the grammar-engine message as well, following the _NO_MODEL_LOADED_DETAIL precedent already in this file
  2. skips the retry when the local backend serving the run is an audio model, reading the same two flags routes/inference.py branches on, best effort, unknown reads as not-audio so an unprobeable backend keeps today's behaviour

Plus tests: your _REFUSAL fixture now carries the message the route actually sends, the audio and tool-loop messages are negative cases, and test_json_fallback_does_not_restart_the_total_timeout moves from 0.4s/0.25s to 1.6s/1.0s. Same semantics, but 600ms of scheduling slack instead of 150ms, which matters because that file runs under -n 4.

I also ran a separate simulation suite outside the tree, 27 cases: chunked and mid-read-failing refusal bodies, a 200KB unicode body, malformed error envelopes, aclose() raising during the fallback, LeaseLost in place of RunCancelled, a trickling body against the wall clock, model switch before and after the fallback, two concurrent runs, and the real route under five backend states. All green after the change.

Follow-ups, not blockers

  • payload is local to _stream_completion, so nothing remembers the refusal. On MLX every planning, decision and audit call pays its own 400 first: with maxSteps at 12 that is up to 14 wasted round trips per run, each spending real wall clock out of modelTimeoutSeconds. A per-run memo would halve the request count. Your comment about negotiating after routing is the right reason not to probe up front, but it does not rule out remembering the answer.
  • The guard is an exact {"type": "json_object"} match. If Research ever moves to a json_schema contract the fallback silently stops applying and MLX regresses, with no test catching it.
  • routes/data_recipe/jobs.py:188 has the same underlying defect and no fallback: it injects a constraining response_format for every llm-structured column, and _ensure_selected_local_model_loaded passes a non-GGUF model through, so every row 400s. Out of scope here, worth a separate issue.

Limitation

Everything above is scripted backends and the real FastAPI route on Linux. No real MLX weights and no Apple Silicon inference, same caveat you gave.

@Etherll Etherll self-assigned this Sep 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: ea8c9825d2

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

@Etherll

Etherll commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

With scripted non-GGUF model output, Deep Research now reaches plan review after the local API refuses JSON grammar support. The same installed Studio scenario fails with HTTP 400 on the merge base; the head retries once, makes one generation call, and displays the plan. Reload preserved the plan, Stop research cancelled it, and invalid JSON still failed validation.

The model-switch fix keeps Research requests text-only across retries. Focused backend and audio regressions passed. Model generation was scripted; native MLX and complete report generation were not tested. Pre-commit passed; 40 Actions jobs were cancelled and provide no validation result.

Before 4b6bc280a9242065466bd266a421752e09d3a6b1 → after ea8c9825d251df0cb97ced9bb6089eccfd7058ec.

Research JSON planning before and after

Not every caller of this route hands it a request with headers. The durable-run
producer builds its own, routes/preview.py passes one through, and the audio
monitor tests stand one in without them, which is why the UI-events header is
already read through a getattr-guarded helper rather than off request.headers.

The new opt-out read headers directly, so every audio reply on those callers
raised AttributeError instead: three existing monitor tests went red. Give it a
named constant and the same guarded reader, and pin the header-less shape on
both the GGUF and non-GGUF audio branches so it cannot regress.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Heads up on ea8c9825d: the text-output opt-out is a good idea and it closes the interleaving Codex raised, but reading it off request.headers directly broke three existing tests. Fixed in 53e93e05d.

Not every caller of this route hands it a request that has headers. core/inference/chat_generation_runs.py:690 builds its own for the durable-run producer, routes/preview.py:167 passes one through, and TestApiMonitorAudioInput stands in a SimpleNamespace. That is exactly why the UI-events header next door is read through a getattr-guarded helper rather than off request.headers, and the new line skipped that:

routes/inference.py:21704: in _monitored_generate_audio
    if request.headers.get("X-Unsloth-Require-Text") == "1":
E   AttributeError: 'types.SimpleNamespace' object has no attribute 'headers'

Every audio reply on such a caller raised instead of answering. Red on my full backend run at ea8c9825d:

FAILED tests/test_openai_tool_passthrough.py::TestApiMonitorAudioInput::test_gguf_tts_auto_route_records_monitor
FAILED tests/test_openai_tool_passthrough.py::TestApiMonitorAudioInput::test_non_gguf_tts_auto_route_records_monitor
FAILED tests/test_openai_tool_passthrough.py::TestApiMonitorAudioInput::test_non_gguf_tts_cancel_finalizes_monitor

53e93e05d gives the header a named constant and the same guarded reader _ui_stream_events_enabled uses, and pins the header-less shape on both the GGUF and non-GGUF audio branches so it cannot come back. 48 pass across test_research_json_fallback.py plus that monitor class.

On the fix itself: I had written the same server-side reorder before I saw your commit, then dropped it, since yours is strictly better. The header covers the case a route-side check alone cannot, a switch to audio landing after the refusal and before the re-send. I drove that interleaving end to end against the real route rather than reasoning about it: statuses [400, 400], second body This request requires text output; select a text model., synthesizer invoked 0 times, and both attempts carry the header. An ordinary chat request to the same audio model still returns 200 and still synthesizes, so nothing outside Research changed.

The 40 red checks on the previous head were not yours. Every run for ea8c9825d came back conclusion: cancelled, all at the same instant across unrelated workflows, which gh pr checks renders as fail. I have the branch replicated on a staging repo running the ubuntu / macos-15 / windows-latest triple plus Playwright so the org queue is not the bottleneck; I will report those results.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 53e93e05d8

ℹ️ 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 lines this branch adds go from 28 to 10, licence header included.
Delete what the code already says, collapse the rest to one line where the
indentation leaves room. Every surviving line carries a fact the code does not
state: which refusals share the code and param, why the retry is negotiated
after routing, why the opt-out is per request rather than per model, and what
the wall-clock test's margin is protecting against.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: ac084e28e5

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

@Etherll Etherll left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Tested Locally + In colab waiting for CI

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from Etherll Sep 9, 2026
@unslothai unslothai deleted a comment from Etherll Sep 9, 2026
@unslothai unslothai deleted a comment from Etherll Sep 9, 2026
@danielhanchen
danielhanchen merged commit d9caa7c into unslothai:main Sep 10, 2026
45 of 48 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants