From 11106d2fd2eb2f3b49e216d2fedd9a7a16a31205 Mon Sep 17 00:00:00 2001 From: Cohen Karnell Date: Tue, 28 Jul 2026 13:10:37 -0500 Subject: [PATCH] Apply the Bearer token guard to AsyncClient web_search and web_fetch Client.web_search and Client.web_fetch raise ValueError when no Bearer token is configured. The AsyncClient versions had no such check, so an unconfigured async caller sent an unauthenticated request to ollama.com and got a 401 back instead of failing locally with an actionable message. Adds the same guard and the matching Raises: docstring section to both async methods, plus the two async tests that mirror the existing sync ones. --- ollama/_client.py | 10 ++++++++++ tests/test_client.py | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/ollama/_client.py b/ollama/_client.py index 8dfce824..51239d9f 100644 --- a/ollama/_client.py +++ b/ollama/_client.py @@ -801,7 +801,12 @@ async def web_search(self, query: str, max_results: int = 3) -> WebSearchRespons Returns: WebSearchResponse with the search results + Raises: + ValueError: If OLLAMA_API_KEY environment variable is not set """ + if not self._client.headers.get('authorization', '').startswith('Bearer '): + raise ValueError('Authorization header with Bearer token is required for web search') + return await self._request( WebSearchResponse, 'POST', @@ -821,7 +826,12 @@ async def web_fetch(self, url: str) -> WebFetchResponse: Returns: WebFetchResponse with the fetched result + Raises: + ValueError: If OLLAMA_API_KEY environment variable is not set """ + if not self._client.headers.get('authorization', '').startswith('Bearer '): + raise ValueError('Authorization header with Bearer token is required for web fetch') + return await self._request( WebFetchResponse, 'POST', diff --git a/tests/test_client.py b/tests/test_client.py index 7b7ab38e..981b1aa9 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1397,6 +1397,24 @@ def test_client_web_fetch_requires_bearer_auth_header(monkeypatch: pytest.Monkey client.web_fetch('https://example.com') +async def test_async_client_web_search_requires_bearer_auth_header(monkeypatch: pytest.MonkeyPatch): + monkeypatch.delenv('OLLAMA_API_KEY', raising=False) + + client = AsyncClient() + + with pytest.raises(ValueError, match='Authorization header with Bearer token is required for web search'): + await client.web_search('test query') + + +async def test_async_client_web_fetch_requires_bearer_auth_header(monkeypatch: pytest.MonkeyPatch): + monkeypatch.delenv('OLLAMA_API_KEY', raising=False) + + client = AsyncClient() + + with pytest.raises(ValueError, match='Authorization header with Bearer token is required for web fetch'): + await client.web_fetch('https://example.com') + + def _mock_request_web_search(self, cls, method, url, json=None, **kwargs): assert method == 'POST' assert url == 'https://ollama.com/api/web_search'