Skip to content

Studio: wire Anthropic web_fetch server-side tool - #5671

Merged
danielhanchen merged 5 commits into
mainfrom
feat/anthropic-web-fetch-bash-tools
May 22, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
feat/anthropic-web-fetch-bash-tools

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Studio's Anthropic passthrough only forwarded web_search and code_execution when enabled_tools was set. Asking Claude to fetch a specific URL through Studio produced no fetch because the tool was not in the outbound tools array, so users had to fall back to web_search even when they already had the exact URL they wanted.

This change opts in web_fetch_20250910 when enabled_tools contains "web_fetch". The new entry is appended alongside any existing web_search / code_execution entries:

{ "type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5 }

No anthropic-beta header is required (web_fetch is GA); the existing code-execution-2025-08-25 flag continues to merge cleanly when both tools are enabled in the same turn.

SSE translation mirrors the web_search path. A server_tool_use block with name="web_fetch" emits a tool_start _toolEvent carrying the URL the model asked to fetch; the matching web_fetch_tool_result block emits a tool_end _toolEvent whose result string follows the Title / URL / Snippet shape parseSourcesFromResult on the frontend already expects, so the source pill renders identically. Error blocks (web_fetch_tool_error) are surfaced as "Error: <error_code>" matching the code_execution error path.

The final Anthropic stream complete log line picks up web_fetch_requested / web_fetch_invocations / web_fetch_urls so support reports of "the model did not fetch anything" can be triaged from the log.

Live verification

End to end against claude-haiku-4-5 with enabled_tools=["web_fetch"]:

tool_events (2):
  start tool=web_fetch args={'url': 'https://example.com'}
  end   id=srvtoolu_01Pqi6MCPiv5T9pE2kE7TfX6 result='Title: Example Domain\nURL: https://example.com\nSnippet: ...'

assistant: The title of the page is "Example Domain".

Tests

  • 5 new unit tests in tests/test_anthropic_web_fetch.py:
    • Tool entry appears in outbound body.
    • Combined ["web_search", "web_fetch", "code_execution"] request carries all three tool types and the code-execution beta flag still merges.
    • Pill-off case (no web_fetch in enabled_tools): outbound body has no web_fetch_20250910 entry.
    • Success path: server_tool_use + web_fetch_tool_result emits one tool_start with arguments.url and one tool_end with Title: / URL: / Snippet: prefix.
    • Error path: web_fetch_tool_error renders as Error: <error_code>.
  • All 242 existing tests across test_anthropic_code_execution.py, test_anthropic_messages.py, test_anthropic_thinking_translation.py, test_openai_code_execution.py, test_openai_responses_translation.py, test_openai_tool_passthrough.py, test_responses_tool_passthrough.py, test_responses_api.py still pass.

Docs

The enabled_tools field description on ChatCompletionRequest (models/inference.py) is updated so OpenAPI consumers see the new option: ['web_search', 'web_fetch', 'code_execution'] for Anthropic, ['web_search', 'code_execution'] for OpenAI Responses, and the existing ['web_search', 'python', 'terminal'] for local GGUF models.

Studio's Anthropic passthrough only forwarded web_search and
code_execution when enabled_tools was set. Asking Claude through Studio
to fetch a URL produced no fetch (the tool was not in the outbound
tools array), so users had to fall back to web_search even when they
already had the exact URL they wanted.

This change opts in web_fetch_20250910 when enabled_tools contains
"web_fetch". The new tool entry is appended alongside any existing
web_search / code_execution entries:

  {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}

No anthropic-beta header is required (web_fetch is GA); the existing
code-execution-2025-08-25 flag continues to merge cleanly when both
tools are enabled in the same turn.

SSE translation mirrors the web_search path. A `server_tool_use` block
with name="web_fetch" emits a `tool_start` _toolEvent carrying the
URL the model asked to fetch; the matching `web_fetch_tool_result`
block emits a `tool_end` _toolEvent whose result string follows the
Title / URL / Snippet shape parseSourcesFromResult on the frontend
already expects, so the source pill renders identically. Error blocks
(`web_fetch_tool_error`) are surfaced as "Error: <error_code>" matching
the code_execution error path.

The final "Anthropic stream complete" log line picks up web_fetch_
requested / web_fetch_invocations / web_fetch_urls so support reports
of "the model did not fetch anything" can be triaged from the log.

Verified end to end against claude-haiku-4-5 with
`enabled_tools=["web_fetch"]`: the model emitted tool_start with
url=https://example.com and tool_end with the page Title + URL +
Snippet, plus the assistant message correctly read back "Example
Domain" as the title.

Tests:
- 5 new unit tests in test_anthropic_web_fetch.py covering tool
  registration, the combined web_search + web_fetch + code_execution
  request body, the pill-off case, and SSE translation for both
  success and error paths.
- All 242 existing Anthropic + OpenAI provider tests still pass.

The enabled_tools field description in models/inference.py is updated
so OpenAPI consumers see the new option.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1590 to +1591
title = document.get("title") or ""
source = document.get("source") or {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Populate Title for titleless web_fetch results

_format_web_fetch_result leaves title empty when Anthropic omits document.title (the comment already marks it optional), so the emitted tool result can contain only URL:/Snippet:. The frontend source parser (parseSourcesFromResult in studio/frontend/src/features/chat/api/chat-adapter.ts) only creates a source pill when both Title: and URL: are present, so these fetches silently lose citations in the UI. Use the same fallback as web search (title = title or url) before formatting.

Useful? React with 👍 / 👎.

@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 implements support for Anthropic's server-side web_fetch tool, including request configuration, stream processing for tool usage and results, and comprehensive unit tests. Feedback from the review suggests improving observability by logging exceptions during JSON parsing, and removing redundant logic such as an unnecessary type check and a duplicate fallback string already provided by the formatting helper.

Comment on lines +1967 to +1968
tool_use_id = current_web_fetch_use["id"]
if tool_use_id in web_fetch_calls:

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.

medium

Avoid using broad, silent exception handlers. As per the general rules, exceptions should be logged (even at a debug level) to aid in future troubleshooting when parsing tool inputs fails.

Suggested change
tool_use_id = current_web_fetch_use["id"]
if tool_use_id in web_fetch_calls:
except Exception:
logger.debug("Failed to parse web_fetch input_json", buffer=buffer)
url = ""
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

Comment on lines +1987 to +1989
)
if tool_use_id in web_fetch_calls:
web_fetch_calls[tool_use_id]["result"] = result_text

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.

medium

This isinstance check is redundant. The inner variable is already guaranteed to be a dictionary by the sanitization logic in the content_block_start handler (line 1745).

                                result_text = _format_web_fetch_result(inner)

}
)
current_web_fetch_result = None
elif thinking_open:

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.

medium

The fallback string "(fetch complete)" is redundant here. The _format_web_fetch_result helper already returns this exact string as its default return value if no content parts are found (line 1611).

Suggested change
elif thinking_open:
"result": result_text,

Three review nits on the previous commit:

1. `_format_web_fetch_result` left `title` empty when Anthropic omitted
   `document.title`. The frontend `parseSourcesFromResult` only emits
   a source pill when both `Title:` and `URL:` lines are present, so
   fetches against pages without an HTML title tag silently lost
   their citation in the UI. Fall back to `title = title or url`,
   matching the web_search formatter.

2. The broad `except Exception` around `json.loads(buffer)` for the
   web_fetch input swallowed the failure with no trace. Log at debug
   so a malformed partial_json buffer can be triaged from the server
   log without changing behavior.

3. `inner` was already sanitised to a dict at the matching
   content_block_start and `_format_web_fetch_result` always returns
   a non-empty string (defaulting to "(fetch complete)"), so the
   `isinstance(inner, dict) else {}` guard and the
   `result_text or "(fetch complete)"` fallback at the emit site
   were dead code. Removed.

Added a test exercising the titleless path so the fallback stays
covered.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1982 to +1984
"type": "tool_start",
"tool_name": "web_fetch",
"tool_call_id": tool_use_id,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve source-pill extraction for web_fetch tool results

Emitting tool_start with tool_name set to web_fetch breaks source-pill rendering in the current frontend path: parseSourcesFromResult is only applied to tool calls where toolName === "web_search" (studio/frontend/src/features/chat/api/chat-adapter.ts, lines 1650-1652). As a result, even though this backend formats Title:/URL:/Snippet: text, web_fetch citations are never converted into source parts, so users lose the clickable source pills for fetches.

Useful? React with 👍 / 👎.

`parseSourcesFromResult` was only wired up for tool calls where
`toolName === "web_search"`, so the Title / URL / Snippet block the
backend formatter emits for `web_fetch_tool_result` never reached the
source-pill renderer. Users saw the raw tool result in the tool card
but the dedicated source-pill row at the message tail stayed empty.

Both web_search and web_fetch ship the same text shape today, so the
fix is to broaden the gate.
…cation

Two reviewer follow-ups on the Anthropic web_fetch PR:

1. The backend tool wiring landed but the frontend chat-adapter
   never put `web_fetch` in `enabled_tools`, so toggling the Search
   pill only ever attached `web_search` -- web_fetch was unreachable
   from the UI. Added providerSupportsBuiltinWebFetch() (Anthropic
   today) and paired the entry with the existing Search pill, since
   the canonical workflow is "search returns URLs, fetch reads
   them" and there is no separate UI toggle yet.

2. `pause_turn` from Anthropic's stop_reason vocabulary fell through
   the finish_reason map's "stop" default, which the OpenAI-format
   client renders as end-of-message and truncates the answer. Per
   the docs pause_turn means "Claude paused a long server-tool
   turn (web_search / web_fetch) and will resume". Mapped to None
   and skipped the chunk emission so the SSE stream still ends with
   [DONE] on message_stop but no terminal finish_reason lands on
   the client. While there: added explicit mappings for `tool_use`
   (-> tool_calls) and `refusal` (-> content_filter) which were
   also falling through to "stop".

Tests added: pause_turn emits no finish_reason, end_turn still
emits "stop", refusal maps to "content_filter".

Sourcing: https://platform.claude.com/docs/en/api/messages#response-stop-reason
@danielhanchen
danielhanchen merged commit a2d2b78 into main May 22, 2026
34 checks passed
@danielhanchen
danielhanchen deleted the feat/anthropic-web-fetch-bash-tools branch May 22, 2026 13:03
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request May 22, 2026
Conflict in studio/frontend/src/features/chat/api/chat-adapter.ts:
upstream main (unslothai#5671 Anthropic web_fetch wiring) extended the
sources extractor to handle both web_search and web_fetch tool
results. The PR branch only had the web_search-only version.
Took main's expanded condition; kept the existing multi-line
parseSourcesFromResult call style for codebase consistency.
rsd-darshan pushed a commit to rsd-darshan/unsloth that referenced this pull request Jun 3, 2026
* Studio: wire Anthropic web_fetch server-side tool

Studio's Anthropic passthrough only forwarded web_search and
code_execution when enabled_tools was set. Asking Claude through Studio
to fetch a URL produced no fetch (the tool was not in the outbound
tools array), so users had to fall back to web_search even when they
already had the exact URL they wanted.

This change opts in web_fetch_20250910 when enabled_tools contains
"web_fetch". The new tool entry is appended alongside any existing
web_search / code_execution entries:

  {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}

No anthropic-beta header is required (web_fetch is GA); the existing
code-execution-2025-08-25 flag continues to merge cleanly when both
tools are enabled in the same turn.

SSE translation mirrors the web_search path. A `server_tool_use` block
with name="web_fetch" emits a `tool_start` _toolEvent carrying the
URL the model asked to fetch; the matching `web_fetch_tool_result`
block emits a `tool_end` _toolEvent whose result string follows the
Title / URL / Snippet shape parseSourcesFromResult on the frontend
already expects, so the source pill renders identically. Error blocks
(`web_fetch_tool_error`) are surfaced as "Error: <error_code>" matching
the code_execution error path.

The final "Anthropic stream complete" log line picks up web_fetch_
requested / web_fetch_invocations / web_fetch_urls so support reports
of "the model did not fetch anything" can be triaged from the log.

Verified end to end against claude-haiku-4-5 with
`enabled_tools=["web_fetch"]`: the model emitted tool_start with
url=https://example.com and tool_end with the page Title + URL +
Snippet, plus the assistant message correctly read back "Example
Domain" as the title.

Tests:
- 5 new unit tests in test_anthropic_web_fetch.py covering tool
  registration, the combined web_search + web_fetch + code_execution
  request body, the pill-off case, and SSE translation for both
  success and error paths.
- All 242 existing Anthropic + OpenAI provider tests still pass.

The enabled_tools field description in models/inference.py is updated
so OpenAPI consumers see the new option.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* web_fetch: title fallback to URL, log parse failures, drop dead checks

Three review nits on the previous commit:

1. `_format_web_fetch_result` left `title` empty when Anthropic omitted
   `document.title`. The frontend `parseSourcesFromResult` only emits
   a source pill when both `Title:` and `URL:` lines are present, so
   fetches against pages without an HTML title tag silently lost
   their citation in the UI. Fall back to `title = title or url`,
   matching the web_search formatter.

2. The broad `except Exception` around `json.loads(buffer)` for the
   web_fetch input swallowed the failure with no trace. Log at debug
   so a malformed partial_json buffer can be triaged from the server
   log without changing behavior.

3. `inner` was already sanitised to a dict at the matching
   content_block_start and `_format_web_fetch_result` always returns
   a non-empty string (defaulting to "(fetch complete)"), so the
   `isinstance(inner, dict) else {}` guard and the
   `result_text or "(fetch complete)"` fallback at the emit site
   were dead code. Removed.

Added a test exercising the titleless path so the fallback stays
covered.

* chat-adapter: emit source pills for web_fetch tool calls

`parseSourcesFromResult` was only wired up for tool calls where
`toolName === "web_search"`, so the Title / URL / Snippet block the
backend formatter emits for `web_fetch_tool_result` never reached the
source-pill renderer. Users saw the raw tool result in the tool card
but the dedicated source-pill row at the message tail stayed empty.

Both web_search and web_fetch ship the same text shape today, so the
fix is to broaden the gate.

* Address review: wire web_fetch from Search pill + fix pause_turn truncation

Two reviewer follow-ups on the Anthropic web_fetch PR:

1. The backend tool wiring landed but the frontend chat-adapter
   never put `web_fetch` in `enabled_tools`, so toggling the Search
   pill only ever attached `web_search` -- web_fetch was unreachable
   from the UI. Added providerSupportsBuiltinWebFetch() (Anthropic
   today) and paired the entry with the existing Search pill, since
   the canonical workflow is "search returns URLs, fetch reads
   them" and there is no separate UI toggle yet.

2. `pause_turn` from Anthropic's stop_reason vocabulary fell through
   the finish_reason map's "stop" default, which the OpenAI-format
   client renders as end-of-message and truncates the answer. Per
   the docs pause_turn means "Claude paused a long server-tool
   turn (web_search / web_fetch) and will resume". Mapped to None
   and skipped the chunk emission so the SSE stream still ends with
   [DONE] on message_stop but no terminal finish_reason lands on
   the client. While there: added explicit mappings for `tool_use`
   (-> tool_calls) and `refusal` (-> content_filter) which were
   also falling through to "stop".

Tests added: pause_turn emits no finish_reason, end_turn still
emits "stop", refusal maps to "content_filter".

Sourcing: https://platform.claude.com/docs/en/api/messages#response-stop-reason

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

1 participant