Skip to content

Studio: pass search results and documents through to the model on /v1/messages - #11152

Merged
Lyxot merged 3 commits into
unslothai:mainfrom
NilayYadav:studio-anthropic-search-result-blocks
Sep 17, 2026
Merged

Lyxot merged 3 commits into
unslothai:mainfrom
NilayYadav:studio-anthropic-search-result-blocks

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

When a tool returned search_result or document blocks on the Anthropic style endpoint, Studio dropped them and sent the model an empty tool result. The model then said the documents had nothing in them. A search_result block in a user message was rejected with a 400.

These blocks are now turned into text with their title and source, in tool results and user messages. PDF, url and file documents become a short "document omitted" note. The token count uses the same text.

Tested with new unit tests and with the anthropic SDK against a local GGUF: the model now finds the answer in every case, and the user message case works instead of returning 400.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 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-16T21:10:26.315234Z fce0b27 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fce0b270e3

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

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the drop: studio/backend/models/inference.py:3319 rejects search_result and document, and the converter sends an empty tool result, so this is worth fixing. Two asks before I review: this also switches the tool_result join from a space to a newline, which changes text every existing tool call sends to the model, so could you confirm that on a couple of models, and could you drop the unrelated reformatting in main.py, the bootstrap banner tests and the playwright file so the diff is just the block handling?

NilayYadav and others added 3 commits September 17, 2026 10:59
A PDF, url or file document in a user message cannot be read, so it now 400s like any other untranslatable user block instead of reaching the model as an omitted-document note. Inside a tool result, which clients resend with history, it still degrades to the note.
@Lyxot
Lyxot force-pushed the studio-anthropic-search-result-blocks branch from fce0b27 to fc3ac7b Compare September 17, 2026 02:59
@Lyxot

Lyxot commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Pushed a small follow-up on top of this and rebased the branch on current main.

  • Rebase: the pre-commit.ci commit is gone, since main already has that reformatting. The diff is now just the block handling.
  • New commit fc3ac7b19a: a PDF, url or file document sent directly in a user message now returns 400, like any other user block Studio can't translate. Inside a tool_result, which clients resend with history, it still becomes the "document omitted" note. This follows the existing image rule: a top-level image on a text-only model returns 400, and a tool-result image becomes a note. It is also no looser than main, which rejected every top-level document.
  • Tests: a parametrized rejection test, a top-level content document case, and a stricter admission-estimate assertion. The estimate test previously passed even when top-level documents were left unrendered.

@Lyxot

Lyxot commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@Lyxot

Lyxot commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

could you drop the unrelated reformatting in main.py, the bootstrap banner tests and the playwright file

Done. After the rebase on current main the pre-commit.ci commit was dropped, because main already has that reformatting. The PR now changes only anthropic_compat.py, models/inference.py, routes/inference.py and three test files.

this also switches the tool_result join from a space to a newline ... could you confirm that on a couple of models

I checked this but didn't change the code. The join only affects a tool_result whose content is a list of more than one block. String content and single-block results are sent exactly as before. count_tokens goes through the same converter, and the admission estimate keeps the list unjoined, so both still match what is sent. For comparison, llama.cpp's own /v1/messages converter joins these blocks with no separator.

To compare the two joins, I ran the same tool conversation through main's converter and this branch's, against llama-server b10840 with temperature 0 and one tool call:

case             join      Qwen3-1.7B Q4_K_XL        gemma-4-E2B-it Q4_K_XL
file count       space     "1"  (wrong)              "3"  ok
                 newline   "1"  (wrong)              "3"  ok
status field     space     "degraded" ok             "Degraded" ok
                 newline   "degraded" ok             "degraded" ok
function names   space     add, sub ok               add, sub ok
                 newline   add, sub ok               add, sub ok
search results   space     tool content "" -> "1234" (made up)   "" (empty)
                 newline   PURPLE-ELEPHANT-42 ok     PURPLE-ELEPHANT-42 ok

On the three plain multi-block cases, both joins give the same answers on both models; the Qwen miss on the file count happens with either join. The newline is still needed for the new blocks, because with a space join consecutive search results run into each other's headers.

Souravrajvi0 pushed a commit to Souravrajvi0/unsloth that referenced this pull request Sep 17, 2026
* Stop two CI guards failing for the machine they ran on

Both went red on branches that touch neither of them.

tests/studio/test_update_release_notes.py's linearity guard reported 7.2x
against a bar of 6.0 on unslothai#11152. Pairing divides most contention out but not
all of it: the big leg runs four times longer than the small one, so a
scheduler stall is four times more likely to land in the big half, which biases
a pair upward and never downward, and three pairs is few enough that two
unlucky ones move the median. Re-measure on a larger sample instead of
loosening the bar. That is not a second chance, because a genuinely quadratic
path measures about sixteen in every pair and comes back over the bar as surely
the second time, while a stall does not survive being asked again. The cost is
paid only on the reading that would otherwise have failed.

assert_linear decides four test files and had no rows of its own, so it gets
them: linear passes, quadratic fails, a stalled linear path passes and is shown
to have really taken the retry, a stalled quadratic path still fails, and the
backstop reads the best big time rather than the worst. Cost is simulated
rather than spent, so the shapes are exact and the file runs in seconds.

studio/backend/tests/test_data_recipe_dataset_download.py snapshotted the
shared system temp dir to check a failed export unlinked what it created,
which made it a claim about the whole box. Its siblings each leave a
NamedTemporaryFile with the same .jsonl suffix in flight until their own
finally runs, and CI shards this suite with -n 4 --dist loadgroup, so one of
them on another worker could fail this test for something it does not measure.
Point tempfile.tempdir at a directory only this test can reach; the assertion
becomes nothing at all rather than the same set as a moment ago. Confirmed it
still fails when the cleanup arm is removed.

* Declare the cost in the guard's own tests instead of sleeping for it

The rows were driven by real sleeps, so on a loaded runner they could overshoot
independently and stop meaning what they say: stretch either nominal 4 ms small
leg in the stalled-but-linear row past about 6.7 ms and its injected ratio
falls under the bar, and if both stretch the retry is never reached and the
call-count assertion fails. That is the same unrelated red this change exists
to remove, reintroduced in the test of the fix.

growth and assert_linear now take an optional clock, defaulting to
time.perf_counter, and the rows drive a fake one that advances by exactly the
cost the shape declares. A quadratic path here is quadratic to the last digit,
the file runs in 0.04s, and fifteen consecutive runs give the same seven
passes. Nothing in the repo passes clock outside these tests.

Costs are scaled so the quadratic rows fail on the ratio rather than on the 60s
backstop, which now has a row of its own for each arm: one stalled leg must not
trip it, and a path genuinely too slow to measure must.

* Make the confirmation stand on its own reading

The retry could be accepted from a sample that never finished. If its first
pair blew the 60s backstop the loop stopped there, and if that same pair's
small leg was also slow the one surviving ratio could sit under the tolerance,
so a superlinear path passed on one aborted pair. Taking min(big, big_again)
then hid the abort, because the first sample's best big time was well under
budget.

Both halves are now required of the confirmation itself: its own big time under
the budget, and all of its pairs completed. Verified against the old code,
which accepts exactly this shape and now does not, with a row that sizes the
stalls so the surviving ratio really is under the bar and the failure is the
abort rather than the ratio.

growth reports how many pairs it completed, since a caller that reads its
median as a verdict cannot tell an aborted sample from a finished one.

* Bound what the confirmation may spend, not just one leg of it

The 60s backstop bounds a single leg. It does not bound the sample: a
regression that holds each big leg just under it still costs about 7 * 60s
in the confirmation, and the four pytest invocations in
studio-backend-ci.yml pass --timeout=330. The worker is killed part way
through, and the run reports a bare timeout instead of the linearity
failure this guard was written to name, which is the same complaint the
docstring already makes about the absolute budget it replaced.

The retry now takes as many pairs as it can afford of a 120s budget,
estimating the pair from the big leg already measured and the ratio already
formed. Fewer pairs is a weaker vote, not a broken one, since contention is
the same size in every pair. Below three there is nothing worth buying, so
the reading already taken becomes the verdict and says so in its message
rather than spending five minutes to reach the same answer.

Two rows for the two arms: a 40s big leg over the bar fails as a linearity
failure and provably does not start a confirmation (six legs, no more), and
a 20s one still takes five pairs and passes on them.

* Stop the confirmation on a measured deadline, not on a prediction

Sizing the retry from the first sample was an estimate dressed as a bound.
It reads the BEST big leg and the MEDIAN ratio, and those come from
different pairs: a sample of 59s, 59s and 1s big legs against 1s small legs
offers a one-second pair cost alongside a ratio of 59, so it authorises all
seven pairs, and if the confirmation's own legs then arrive at 40s the run
overruns --timeout=330 exactly as before.

growth() takes a budget_s that bounds the whole call, checked on the pair
boundary so a stopped sample still holds a whole number of ratios.
abort_over_s bounds one big leg and budget_s bounds the sample; neither
implies the other, which is the gap this closes. A confirmation cut short
already fails through the pairs_completed assertion, so the verdict arrives
as a sentence naming the unfinished sample rather than as the runner's
timeout, which is the whole point.

The pre-sizing stays, demoted to what it is: it refuses a retry that
obviously cannot fit and keeps a green run cheap. One row for the exact
mixed-estimate shape, pinning that the loop gives up after three of the
seven pairs it was authorised.

* Ask the budget before a pair runs, not after it has

A bound tested once a pair is already home is not a bound on that pair.
Three 59-second pairs under a 120-second budget all run, because each one
is inside the budget at the moment its predecessor finishes, and the sample
costs 177s. With a first sample of 39s, 59s and 59s big legs -- which sizes
the retry at three pairs, since the estimate reads the best leg and the
median ratio from different pairs -- the whole test reaches about 334s and
--timeout=330 kills it before the assertion, which is what the budget was
added to prevent.

The loop now reserves room for another pair at the cost of the worst pair
it has seen in this sample, and stops when that no longer fits. Worst
rather than mean because contention only adds. On the shape above it stops
at two pairs, the confirmation spends 118s of its 120, and the test lands
around 275s.

One row for that shape, asserting the pair count, the message, and that the
whole test stays under the runner's timeout. The existing mixed-estimate
row now stops at two pairs rather than three, for the same reason.

* Count the first sample against the budget it is part of

The retry got a fresh 120s no matter what the first sample had already
spent. The first sample has no bound of its own past the 60s per big leg,
so a scheduler stall in one of its small legs can burn most of the runner's
patience before the re-measurement is even considered, and a confirmation
counted fresh from there overruns whatever was left.

confirm_budget_s becomes total_budget_s and covers the whole call, first
sample included. The retry is sized and bounded by what remains, and the
message says how much that was. 240s against --timeout=330, leaving margin
for collection and the rest of the test body.

Two rows retuned rather than rewritten, since deducting the first sample
changes what each affords. The partial-affordability row now uses 30s big
legs, which put 90s into the first sample and leave four pairs of the
remaining 150. The before-the-pair row uses 13s / 20s / 20s big legs, which
cost 56s and authorise all seven, and its confirmation's 59s legs stop at
three for 177s of the 184 left; asked after the pair instead, the fourth
would have run to 236 and blown a bound it was never tested against while
inside it.

* Put the first sample inside the budget it belongs to

total_budget_s documented a whole-call guarantee and was only ever handed
to the confirmation. Contention landing in the SMALL legs is what that
misses: 50s small against 55s big reads as a ratio of 1.1, comfortably
under the tolerance, so nothing reaches the retry branch where the budget
was enforced, and three of those pairs run to 315s past --timeout=330 while
returning a cheerful pass.

The first growth call now takes the budget too, and a sample that stopped
short is not accepted as a verdict: two pairs is not the reading the caller
asked for, so it fails saying so rather than reporting a median of whatever
it managed. The per-leg backstop is still checked first, so a path with one
enormous leg keeps its own clearer message.

One row for that shape, asserting the pair count, the message, and that the
call stays under the runner's timeout.
@Lyxot

Lyxot commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@Lyxot Lyxot 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.

LGTM. Verified the empty tool result on main, reviewed the conversion and the admission estimate, checked both joins on Qwen3-1.7B and gemma-4-E2B, and ran staging CI and a Codex review on current main; all passed.

@Lyxot
Lyxot merged commit 3781136 into unslothai:main Sep 17, 2026
55 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Stop two CI guards failing for the machine they ran on

Both went red on branches that touch neither of them.

tests/studio/test_update_release_notes.py's linearity guard reported 7.2x
against a bar of 6.0 on unslothai#11152. Pairing divides most contention out but not
all of it: the big leg runs four times longer than the small one, so a
scheduler stall is four times more likely to land in the big half, which biases
a pair upward and never downward, and three pairs is few enough that two
unlucky ones move the median. Re-measure on a larger sample instead of
loosening the bar. That is not a second chance, because a genuinely quadratic
path measures about sixteen in every pair and comes back over the bar as surely
the second time, while a stall does not survive being asked again. The cost is
paid only on the reading that would otherwise have failed.

assert_linear decides four test files and had no rows of its own, so it gets
them: linear passes, quadratic fails, a stalled linear path passes and is shown
to have really taken the retry, a stalled quadratic path still fails, and the
backstop reads the best big time rather than the worst. Cost is simulated
rather than spent, so the shapes are exact and the file runs in seconds.

studio/backend/tests/test_data_recipe_dataset_download.py snapshotted the
shared system temp dir to check a failed export unlinked what it created,
which made it a claim about the whole box. Its siblings each leave a
NamedTemporaryFile with the same .jsonl suffix in flight until their own
finally runs, and CI shards this suite with -n 4 --dist loadgroup, so one of
them on another worker could fail this test for something it does not measure.
Point tempfile.tempdir at a directory only this test can reach; the assertion
becomes nothing at all rather than the same set as a moment ago. Confirmed it
still fails when the cleanup arm is removed.

* Declare the cost in the guard's own tests instead of sleeping for it

The rows were driven by real sleeps, so on a loaded runner they could overshoot
independently and stop meaning what they say: stretch either nominal 4 ms small
leg in the stalled-but-linear row past about 6.7 ms and its injected ratio
falls under the bar, and if both stretch the retry is never reached and the
call-count assertion fails. That is the same unrelated red this change exists
to remove, reintroduced in the test of the fix.

growth and assert_linear now take an optional clock, defaulting to
time.perf_counter, and the rows drive a fake one that advances by exactly the
cost the shape declares. A quadratic path here is quadratic to the last digit,
the file runs in 0.04s, and fifteen consecutive runs give the same seven
passes. Nothing in the repo passes clock outside these tests.

Costs are scaled so the quadratic rows fail on the ratio rather than on the 60s
backstop, which now has a row of its own for each arm: one stalled leg must not
trip it, and a path genuinely too slow to measure must.

* Make the confirmation stand on its own reading

The retry could be accepted from a sample that never finished. If its first
pair blew the 60s backstop the loop stopped there, and if that same pair's
small leg was also slow the one surviving ratio could sit under the tolerance,
so a superlinear path passed on one aborted pair. Taking min(big, big_again)
then hid the abort, because the first sample's best big time was well under
budget.

Both halves are now required of the confirmation itself: its own big time under
the budget, and all of its pairs completed. Verified against the old code,
which accepts exactly this shape and now does not, with a row that sizes the
stalls so the surviving ratio really is under the bar and the failure is the
abort rather than the ratio.

growth reports how many pairs it completed, since a caller that reads its
median as a verdict cannot tell an aborted sample from a finished one.

* Bound what the confirmation may spend, not just one leg of it

The 60s backstop bounds a single leg. It does not bound the sample: a
regression that holds each big leg just under it still costs about 7 * 60s
in the confirmation, and the four pytest invocations in
studio-backend-ci.yml pass --timeout=330. The worker is killed part way
through, and the run reports a bare timeout instead of the linearity
failure this guard was written to name, which is the same complaint the
docstring already makes about the absolute budget it replaced.

The retry now takes as many pairs as it can afford of a 120s budget,
estimating the pair from the big leg already measured and the ratio already
formed. Fewer pairs is a weaker vote, not a broken one, since contention is
the same size in every pair. Below three there is nothing worth buying, so
the reading already taken becomes the verdict and says so in its message
rather than spending five minutes to reach the same answer.

Two rows for the two arms: a 40s big leg over the bar fails as a linearity
failure and provably does not start a confirmation (six legs, no more), and
a 20s one still takes five pairs and passes on them.

* Stop the confirmation on a measured deadline, not on a prediction

Sizing the retry from the first sample was an estimate dressed as a bound.
It reads the BEST big leg and the MEDIAN ratio, and those come from
different pairs: a sample of 59s, 59s and 1s big legs against 1s small legs
offers a one-second pair cost alongside a ratio of 59, so it authorises all
seven pairs, and if the confirmation's own legs then arrive at 40s the run
overruns --timeout=330 exactly as before.

growth() takes a budget_s that bounds the whole call, checked on the pair
boundary so a stopped sample still holds a whole number of ratios.
abort_over_s bounds one big leg and budget_s bounds the sample; neither
implies the other, which is the gap this closes. A confirmation cut short
already fails through the pairs_completed assertion, so the verdict arrives
as a sentence naming the unfinished sample rather than as the runner's
timeout, which is the whole point.

The pre-sizing stays, demoted to what it is: it refuses a retry that
obviously cannot fit and keeps a green run cheap. One row for the exact
mixed-estimate shape, pinning that the loop gives up after three of the
seven pairs it was authorised.

* Ask the budget before a pair runs, not after it has

A bound tested once a pair is already home is not a bound on that pair.
Three 59-second pairs under a 120-second budget all run, because each one
is inside the budget at the moment its predecessor finishes, and the sample
costs 177s. With a first sample of 39s, 59s and 59s big legs -- which sizes
the retry at three pairs, since the estimate reads the best leg and the
median ratio from different pairs -- the whole test reaches about 334s and
--timeout=330 kills it before the assertion, which is what the budget was
added to prevent.

The loop now reserves room for another pair at the cost of the worst pair
it has seen in this sample, and stops when that no longer fits. Worst
rather than mean because contention only adds. On the shape above it stops
at two pairs, the confirmation spends 118s of its 120, and the test lands
around 275s.

One row for that shape, asserting the pair count, the message, and that the
whole test stays under the runner's timeout. The existing mixed-estimate
row now stops at two pairs rather than three, for the same reason.

* Count the first sample against the budget it is part of

The retry got a fresh 120s no matter what the first sample had already
spent. The first sample has no bound of its own past the 60s per big leg,
so a scheduler stall in one of its small legs can burn most of the runner's
patience before the re-measurement is even considered, and a confirmation
counted fresh from there overruns whatever was left.

confirm_budget_s becomes total_budget_s and covers the whole call, first
sample included. The retry is sized and bounded by what remains, and the
message says how much that was. 240s against --timeout=330, leaving margin
for collection and the rest of the test body.

Two rows retuned rather than rewritten, since deducting the first sample
changes what each affords. The partial-affordability row now uses 30s big
legs, which put 90s into the first sample and leave four pairs of the
remaining 150. The before-the-pair row uses 13s / 20s / 20s big legs, which
cost 56s and authorise all seven, and its confirmation's 59s legs stop at
three for 177s of the 184 left; asked after the pair instead, the fourth
would have run to 236 and blown a bound it was never tested against while
inside it.

* Put the first sample inside the budget it belongs to

total_budget_s documented a whole-call guarantee and was only ever handed
to the confirmation. Contention landing in the SMALL legs is what that
misses: 50s small against 55s big reads as a ratio of 1.1, comfortably
under the tolerance, so nothing reaches the retry branch where the budget
was enforced, and three of those pairs run to 315s past --timeout=330 while
returning a cheerful pass.

The first growth call now takes the budget too, and a sample that stopped
short is not accepted as a verdict: two pairs is not the reading the caller
asked for, so it fails saying so rather than reporting a median of whatever
it managed. The per-leg backstop is still checked first, so a path with one
enormous leg keeps its own clearer message.

One row for that shape, asserting the pair count, the message, and that the
call stays under the runner's timeout.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…/messages (unslothai#11152)

* Studio: render Anthropic search_result and document blocks instead of dropping them

* Note images inside content documents instead of dropping them

* fix(studio): reject unreadable top-level Anthropic documents

A PDF, url or file document in a user message cannot be read, so it now 400s like any other untranslatable user block instead of reaching the model as an omitted-document note. Inside a tool result, which clients resend with history, it still degrades to the note.

---------

Co-authored-by: Lyxot <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 18, 2026
…hai#18227)

When `unsloth start claude` (or any Messages API client pointed at
Studio) reads a PDF with its Read tool, the file comes back as a PDF
document inside the tool result. Studio only read plain text documents
there, so the model got the file name and a "document omitted" note
instead of the contents. It then answered without the document, said it
could not read it, or made up the numbers.

PDF documents in tool results on /v1/messages are now turned into text
with the same PDF reader web fetch already uses, with the same page and
length limits, so the model sees what is in the file. A PDF that cannot
be decoded or has no text still gets the omitted note. This extends the
document support added in unslothai#11152.

PDF documents sent directly in a user turn (not only inside a tool
result) are now accepted and read the same way, instead of being refused
with a 400. Text is extracted off the event loop before conversion and
kept on the request, so a long session with many PDFs is not re-parsed
on the event loop, and a small cache keyed by the payload's hash reuses
the text across turns without holding the base64.

## Screenshots

| Before (main) | After (this PR) |
| --- | --- |
| <img width="400" alt="before"
src="https://raw.githubusercontent.com/NilayYadav/unsloth/pr-screenshots/messages-read-pdf-documents/before.png">
| <img width="400" alt="after"
src="https://raw.githubusercontent.com/NilayYadav/unsloth/pr-screenshots/messages-read-pdf-documents/after.png">
|

---------

Co-authored-by: Daniel Han <[email protected]>
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