Skip to content

feat(tool): add Brave Search as a selectable web_search provider (#294) - #324

Merged
franciscojavierarceo merged 3 commits into
vllm-project:mainfrom
Zheng-Lu:feat/294-brave-search-provider
Sep 17, 2026
Merged

franciscojavierarceo merged 3 commits into
vllm-project:mainfrom
Zheng-Lu:feat/294-brave-search-provider

Conversation

@Zheng-Lu

@Zheng-Lu Zheng-Lu commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #294 (Phase 2 of #291).

Implements the Brave Search API provider behind the typed WebSearchProvider contract established in Phase 1 (#293), making search backends cleanly selectable via AGENTIC_WEB_SEARCH_PROVIDER (environment) or [web_search].provider (configuration file), while keeping default You.com behavior and recorded cassettes byte-identical.

Key Implementation Details

  1. Provider Implementation (crates/agentic-server-core/src/tool/web_search/brave.rs):

    • Hits GET {base_url}/res/v1/web/search with result_filter=web,news and X-Subscription-Token.
    • Passes text_decorations=false so the LLM receives clean, unadorned snippet text without raw <strong> HTML tags.
    • Strictly respects transport rules: avoids Accept-Encoding: gzip (core reqwest lacks gzip decompression).
    • Maps freshness accurately: supports both short codes (pd, pw, pm, py) AND date ranges (YYYY-MM-DDtoYYYY-MM-DD).
    • Clamps count to the Brave 20-result limit with tracing::debug!.
    • Post-filters domain allowlists/blocklists client-side using label-boundary suffix matching.
    • Non-retrying 401/403 (names BRAVE_API_KEY without secret leaks) and 429 (surfaces Retry-After or X-RateLimit-Reset).
  2. Concurrency & Rate Limiting:

  3. Wire Compatibility & RFC [RFC] Pluggable Web Search Providers and Typed Result Normalization #291 Q5 Resolution:

    • Resolves Q5: surfaces "provider": "brave" in metadata[].
    • Uses #[serde(skip_serializing_if = "WebSearchProviderKind::is_you")] to ensure existing You.com output and recorded Messages cassettes remain 100% byte-identical.
  4. Zero Extra Dependencies & Non-Breaking API:

    • Zero added external crates (no strum dependency added; uses standard library FromStr).
    • Keeps WebSearchProviderConfig::new backward-compatible; introduces fluent .with_provider(...) / .with_max_concurrent_queries(...) builders and WebSearchHandler::from_config(...).
  5. Testing & Documentation:

    • Dedicated integration test suite: crates/agentic-server-core/tests/web_search_brave_test.rs covering 200 OK (web+news), empty results, domain filtering, 401/403, 429 with Retry-After/X-RateLimit-Reset, batched query serialization, and concurrency overrides.
    • Fully updated README.md, docs/deploying/README.md, docs/deploying/kubernetes.md, CHANGELOG.md, and ARCHITECTURE.md.

Review follow-up: keep provider credentials unpinned in generated configs so provider switches select the matching default API-key variable, preserve HTTP-date Retry-After values verbatim, and split shared provider types/config resolution into focused modules to pass the production file-size checks.

Test Plan

Validation after the review patch:

  • After merging fix: preserve and verify image input through Responses #263 and fix(mcp): follow tools/list pagination cursors #311, the integrated tree exactly matches the combined checkout with 1,532 passing workspace tests (9 ignored) and passing launcher contract tests. All pre-commit hooks passed again after baseline reconciliation.

  • 60 core tests matching web_search passed.

  • 10 Brave integration tests and 25 common/You integration tests passed.

  • 6 configuration-resolution tests passed.

  • Provider-switch and HTTP-date Retry-After regressions failed before their fixes and passed afterward.

  • cargo clippy --all-targets -- -D warnings passed.

  • pre-commit run --all-files passed, including formatting and production file-size checks.

New Brave coverage uses local Axum HTTP mocks. No live Brave provider call or new Brave cassette was recorded during review.

…m-project#294)

Phase 2 of vllm-project#291. Add `tool/web_search/brave.rs` behind the typed provider
contract from Phase 1 and make the backend selectable through
`AGENTIC_WEB_SEARCH_PROVIDER` / `[web_search] provider`.

- Brave requests use `GET /res/v1/web/search` with `result_filter=web,news`
  and `X-Subscription-Token`; `Accept-Encoding` is never sent because the
  core reqwest build has no gzip support.
- Adapt the shared tool contract: apply `allowed_domains` / `blocked_domains`
  client-side through `DomainFilter`, clamp `count` to 20, render `freshness`
  as `pd`/`pw`/`pm`/`py`, map `language` to `search_lang`, and ignore the
  You.com-specific livecrawl arguments.
- Fail 401/403 naming `BRAVE_API_KEY` without echoing the body; fail 429
  without retrying and surface `Retry-After` (or `X-RateLimit-Reset`).
- Add `[web_search] max_concurrent_queries` and
  `AGENTIC_WEB_SEARCH_MAX_CONCURRENT_QUERIES`; Brave defaults to one
  in-flight request for its free-plan rate limit, You.com keeps inheriting
  `max_concurrent_gateway_calls`.
- Resolve the endpoint as `AGENTIC_WEB_SEARCH_BASE_URL`, then
  `YOU_API_BASE_URL` (You.com only), then the file, then the provider
  default; generated config files record the selected provider.
- Serialize `metadata[].provider` for non-default providers only, so
  You.com output and the recorded Messages cassettes stay byte-identical.
- Make `WebSearchProviderConfig` non-exhaustive with `with_provider` and
  `with_max_concurrent_queries` builders so later providers are additive.

Claude-Session: https://claude.ai/code/session_01EsbCF1Smauv41qnpnqYvfz
Signed-off-by: Zheng Lu <[email protected]>

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

patched provider switching in generated configs and HTTP-date Retry-After handling, with regression tests. the provider/configuration tests, Clippy, and pre-commit checks pass locally. Brave HTTP behavior is covered by mocks; no live Brave run was performed.

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

reconciled the baseline after #263 and #311 merged. the resulting Git tree is identical to the combined checkout that passed all 1,532 workspace tests and launcher tests; all pre-commit hooks also pass on this head.

@franciscojavierarceo
franciscojavierarceo merged commit 137783e into vllm-project:main Sep 17, 2026
14 checks passed
haoshan98 pushed a commit that referenced this pull request Sep 28, 2026
Closes #327 (Part of #291).

## Summary

Adds [Tavily](https://tavily.com) as the third backend for the
gateway-owned `web_search` tool (Phase 3 of #291, closes #327),
following the typed provider contract from #293/#294 and the Brave
pattern from #324.

- **`WebSearchProviderKind::Tavily`** (`config.rs`): `config_name =
"tavily"`, `TAVILY_API_KEY`, default endpoint `https://api.tavily.com`,
no provider-specific concurrency ceiling (Tavily plans are metered per
minute, so it inherits the gateway limit). `ALL`, `FromStr`, and the
"expected one of" message list all three providers. No public signature
changes: the enum and `WebSearchProviderConfig` are `#[non_exhaustive]`,
and `WebSearchHandler::from_config` gains a match arm.
`WebSearchProviderKind::ALL` is now a `&'static [Self]` slice so adding
a provider no longer changes its type.
- **`tool/web_search/tavily.rs`** (new, 391 production lines):
`TavilySearchProvider` posts a typed `TavilySearchBody` to `POST
{base_url}/search` with `Content-Type: application/json`, `Accept:
application/json`, and `Authorization: Bearer <key>`. The key is never
placed in the body and `Accept-Encoding` is never sent (core `reqwest`
has no gzip). Request shaping:
- `count` / `search_context_size` → `max_results`, clamped to 20 with a
debug log;
- `freshness` day/week/month/year → `time_range`;
`YYYY-MM-DDtoYYYY-MM-DD` → `start_date` / `end_date` widened by one day
on each side (checked `pred_opt` / `succ_opt`), because the gateway's
range is inclusive while Tavily documents its bounds as "after" /
"before";
- `allowed_domains` / `blocked_domains` (request config wins) or the
model's `include_domains` / `exclude_domains` → native `include_domains`
/ `exclude_domains`, **and** re-applied client-side through
`DomainFilter` as defense in depth; the shared include+exclude/boost
conflict rule is preserved;
- `language` keeps Tavily's documented compound tags lowercased (`zh-CN`
→ `zh-cn`) and otherwise reduces to the primary subtag (`en-GB` → `en`);
`safesearch` → boolean `safe_search` (`off` → omitted);
- `include_published_date: true` so `page_age` is populated for the
`general` topic;
- `country` (Tavily wants full country names, not ISO codes) and the
You.com-specific `livecrawl*`, `crawl_timeout`, `boost_domains` are
dropped with one debug log.
- One `topic: "general"` request per query: every hit lands in
`results.web`, `results.news` stays empty. A second `news` request per
query would double credit spend; this is documented.
- **Response mapping**: forward-compatible `#[serde(default)]` structs
read `results[] { title, url, content, published_date }` plus
`response_time` and `request_id`; `content` → `description`,
`published_date` → `page_age`. `metadata[]` carries `"provider":
"tavily"`, `request_id` as `search_uuid`, and `response_time` as
`latency` (existing `skip_serializing_if` rules, You.com output
unchanged).
- **Failures** (credential-free): 401/403 name `TAVILY_API_KEY` without
reading the body; 429 is not retried and surfaces `Retry-After` verbatim
(or says none was provided); Tavily's non-standard 432/433 plan-limit
statuses are reported without retry; anything else reports status +
size-bounded body.
- **`mod.rs` size**: adding the module pushed `mod.rs` to 507 production
lines, so the shared `null_as_default` and `read_response_limited`
helpers moved to `provider.rs` (where the provider contract lives). Both
were and remain crate-private, so no public API changed. `mod.rs` is now
476 lines; no other file changed behavior.
- **Server plumbing**: `web_search_config.rs` / `config_file.rs` are
provider-generic already; only doc comments and tests changed.
- **Docs**: `README.md` (feature bullet, quick start, `config.toml`
comments, provider table, Tavily section), `docs/deploying/README.md`,
`docs/deploying/kubernetes.md`, `ARCHITECTURE.md`, `CHANGELOG.md`.

No new dependencies; the request body is serialized with the existing
`serde_json` rather than enabling `reqwest`'s `json` feature.

Deliberately kept in parity with `brave.rs` / `you.rs` rather than
changed here (candidates for a cross-provider follow-up): generic
non-2xx failures echo the size-bounded upstream body
(401/403/429/432/433 never do), `Retry-After` is whitespace-trimmed, and
the caller-supplied `reqwest::Client` contract is gateway-wide.

## Test Plan

- [x] `cargo fmt -- --check`
- [x] `cargo clippy --all-targets -- -D warnings`
- [x] `cargo test` — 1606 passed, 0 failed (You.com and Brave suites
untouched and green)
- [x] `pre-commit run --all-files` — all hooks pass, including the Rust
production file-size policy (`mod.rs` 476, `tavily.rs` 391,
`provider.rs` 144)
- [x] New hermetic integration suite
`crates/agentic-server-core/tests/web_search_tavily_test.rs` (12 tests,
Axum mock on `127.0.0.1:0`, nothing reaches the network):
- 200 search: exact JSON body (clamped `max_results`, `time_range`,
`language`, `safe_search`, `exclude_domains`, no
`country`/`livecrawl`/`api_key`), `Bearer` auth, `Content-Type`, no
`Accept-Encoding`, byte-exact model-facing output with
`"provider":"tavily"` + `search_uuid` + `latency`, `web_search_call`
public sources
- date-range freshness → `start_date`/`end_date` widened by one day each
side, no `max_results` when count unset
  - empty `results` → `{"web":[],"news":[]}` with no invented sources
- domain filters: request-level allowlist wins and is forwarded
natively; off-list results from a mock that ignores the filter are
dropped client-side; `exclude_domains` forwarded and enforced
- 401/403: names `TAVILY_API_KEY`, never echoes the key or the upstream
body
- 429: `Retry-After` integer and HTTP-date surfaced verbatim, absence
reported, exactly one request (no retry)
  - 432/433: plan-limit message, no retry
  - 500: status + body; non-JSON body → "invalid JSON"
- concurrency: 5 batched queries overlap by default (gateway ceiling 5);
`max_concurrent_queries = 1` serializes
- [x] Inline unit tests in `tavily.rs` (13 tests) cover the private
request/response types: payload rendering and omission of unset fields,
clamping, freshness mapping including month/year boundary widening,
language (`zh-CN` → `zh-cn`, `zh-TW` → `zh`, `en-GB` → `en`) and
safe-search reduction, ignored arguments, config-over-args precedence,
conflict rejection, envelope tolerance (`{}`, nulls, unknown keys),
metadata serialization, defense-in-depth filtering
- [x] `config.rs`, `web_search_config.rs`, `config_file.rs` tests
extended for the third provider (labels, parsing, env/file resolution,
`api_key_env` override, provider switching without pinned credentials,
TOML round trip)

---------

Signed-off-by: Zheng Lu <[email protected]>
@Zheng-Lu
Zheng-Lu deleted the feat/294-brave-search-provider branch October 9, 2026 13:17
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.

[Feature] Add Brave Search as a selectable web_search provider

2 participants