| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
import json |
| 6 |
from typing import Any, Dict, List, cast |
| 7 |
from typing_extensions import Protocol |
| 8 |
|
| 9 |
import httpx2 |
| 10 |
import pytest |
| 11 |
from respx import MockRouter |
| 12 |
|
| 13 |
from anthropic import AnthropicVertex, AsyncAnthropicVertex, beta_tool, beta_async_tool |
| 14 |
from anthropic._compat import PYDANTIC_V1 |
| 15 |
from anthropic.lib.vertex._auth import refresh_auth |
| 16 |
from anthropic.lib._extras._common import MissingDependencyError |
| 17 |
|
| 18 |
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") |
| 19 |
|
| 20 |
|
| 21 |
class MockRequestCall(Protocol): |
| 22 |
request: httpx2.Request |
| 23 |
|
| 24 |
|
| 25 |
TOOL_RUNNER_URL = "https://region-aiplatform.googleapis.com/v1/projects/project/locations/region/publishers/anthropic/models/claude-haiku-4-5@20251001:rawPredict" |
| 26 |
|
| 27 |
|
| 28 |
def _vertex_message(content: List[Dict[str, Any]], stop_reason: str) -> httpx2.Response: |
| 29 |
return httpx2.Response( |
| 30 |
200, |
| 31 |
json={ |
| 32 |
"id": "msg_01", |
| 33 |
"type": "message", |
| 34 |
"role": "assistant", |
| 35 |
"model": "claude", |
| 36 |
"content": content, |
| 37 |
"stop_reason": stop_reason, |
| 38 |
"stop_sequence": None, |
| 39 |
"usage": {"input_tokens": 10, "output_tokens": 5}, |
| 40 |
}, |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
def _tool_runner_responses() -> List[httpx2.Response]: |
| 45 |
return [ |
| 46 |
_vertex_message( |
| 47 |
[{"type": "tool_use", "id": "toolu_01", "name": "get_weather", "input": {"city": "Paris"}}], |
| 48 |
"tool_use", |
| 49 |
), |
| 50 |
_vertex_message([{"type": "text", "text": "It is sunny in Paris."}], "end_turn"), |
| 51 |
] |
| 52 |
|
| 53 |
|
| 54 |
def _assert_tool_runner_calls(calls: List[MockRequestCall]) -> None: |
| 55 |
assert len(calls) == 2 |
| 56 |
for call in calls: |
| 57 |
assert call.request.url == TOOL_RUNNER_URL |
| 58 |
assert call.request.headers["Authorization"] == "Bearer my-access-token" |
| 59 |
body = json.loads(call.request.content) |
| 60 |
assert "model" not in body and "stream" not in body and "output_format" not in body |
| 61 |
assert body["anthropic_version"] == "vertex-2023-10-16" |
| 62 |
second = json.loads(calls[1].request.content) |
| 63 |
assert [m["role"] for m in second["messages"]] == ["user", "assistant", "user"] |
| 64 |
assert second["messages"][1]["content"][0]["type"] == "tool_use" |
| 65 |
assert second["messages"][2]["content"][0] == { |
| 66 |
"type": "tool_result", |
| 67 |
"tool_use_id": "toolu_01", |
| 68 |
"content": "sunny in Paris", |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
class TestAnthropicVertex: |
| 73 |
client = AnthropicVertex(region="region", project_id="project", access_token="my-access-token") |
| 74 |
|
| 75 |
@pytest.mark.respx() |
| 76 |
def test_messages_retries(self, respx_mock: MockRouter) -> None: |
| 77 |
request_url = "https://region-aiplatform.googleapis.com/v1/projects/project/locations/region/publishers/anthropic/models/claude-3-sonnet@20240229:rawPredict" |
| 78 |
respx_mock.post(request_url).mock( |
| 79 |
side_effect=[ |
| 80 |
httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}), |
| 81 |
httpx2.Response(200, json={"foo": "bar"}), |
| 82 |
] |
| 83 |
) |
| 84 |
|
| 85 |
self.client.messages.create( |
| 86 |
max_tokens=1024, |
| 87 |
messages=[ |
| 88 |
{ |
| 89 |
"role": "user", |
| 90 |
"content": "Say hello there!", |
| 91 |
} |
| 92 |
], |
| 93 |
model="claude-3-sonnet@20240229", |
| 94 |
) |
| 95 |
|
| 96 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 97 |
|
| 98 |
assert len(calls) == 2 |
| 99 |
|
| 100 |
assert calls[0].request.url == request_url |
| 101 |
assert calls[1].request.url == request_url |
| 102 |
|
| 103 |
def test_copy(self) -> None: |
| 104 |
copied = self.client.copy() |
| 105 |
assert id(copied) != id(self.client) |
| 106 |
|
| 107 |
copied = self.client.copy(region="another-region", project_id="another-project") |
| 108 |
assert copied.region == "another-region" |
| 109 |
assert self.client.region == "region" |
| 110 |
assert copied.project_id == "another-project" |
| 111 |
assert self.client.project_id == "project" |
| 112 |
|
| 113 |
def test_with_options(self) -> None: |
| 114 |
copied = self.client.with_options(region="another-region", project_id="another-project") |
| 115 |
assert copied.region == "another-region" |
| 116 |
assert self.client.region == "region" |
| 117 |
assert copied.project_id == "another-project" |
| 118 |
assert self.client.project_id == "project" |
| 119 |
|
| 120 |
def test_copy_default_options(self) -> None: |
| 121 |
# options that have a default are overridden correctly |
| 122 |
copied = self.client.copy(max_retries=7) |
| 123 |
assert copied.max_retries == 7 |
| 124 |
assert self.client.max_retries == 2 |
| 125 |
|
| 126 |
copied2 = copied.copy(max_retries=6) |
| 127 |
assert copied2.max_retries == 6 |
| 128 |
assert copied.max_retries == 7 |
| 129 |
|
| 130 |
# timeout |
| 131 |
assert isinstance(self.client.timeout, httpx2.Timeout) |
| 132 |
copied = self.client.copy(timeout=None) |
| 133 |
assert copied.timeout is None |
| 134 |
assert isinstance(self.client.timeout, httpx2.Timeout) |
| 135 |
|
| 136 |
def test_copy_default_headers(self) -> None: |
| 137 |
client = AnthropicVertex( |
| 138 |
base_url=base_url, |
| 139 |
region="region", |
| 140 |
project_id="project", |
| 141 |
_strict_response_validation=True, |
| 142 |
default_headers={"X-Foo": "bar"}, |
| 143 |
) |
| 144 |
assert client.default_headers["X-Foo"] == "bar" |
| 145 |
|
| 146 |
# does not override the already given value when not specified |
| 147 |
copied = client.copy() |
| 148 |
assert copied.default_headers["X-Foo"] == "bar" |
| 149 |
|
| 150 |
# merges already given headers |
| 151 |
copied = client.copy(default_headers={"X-Bar": "stainless"}) |
| 152 |
assert copied.default_headers["X-Foo"] == "bar" |
| 153 |
assert copied.default_headers["X-Bar"] == "stainless" |
| 154 |
|
| 155 |
# uses new values for any already given headers |
| 156 |
copied = client.copy(default_headers={"X-Foo": "stainless"}) |
| 157 |
assert copied.default_headers["X-Foo"] == "stainless" |
| 158 |
|
| 159 |
# set_default_headers |
| 160 |
|
| 161 |
# completely overrides already set values |
| 162 |
copied = client.copy(set_default_headers={}) |
| 163 |
assert copied.default_headers.get("X-Foo") is None |
| 164 |
|
| 165 |
copied = client.copy(set_default_headers={"X-Bar": "Robert"}) |
| 166 |
assert copied.default_headers["X-Bar"] == "Robert" |
| 167 |
|
| 168 |
with pytest.raises( |
| 169 |
ValueError, |
| 170 |
match="`default_headers` and `set_default_headers` arguments are mutually exclusive", |
| 171 |
): |
| 172 |
client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) |
| 173 |
|
| 174 |
def test_copy_x_stainless_helper_header_appends(self) -> None: |
| 175 |
# `x-stainless-helper` accumulates across copies instead of being clobbered |
| 176 |
client = AnthropicVertex( |
| 177 |
base_url=base_url, |
| 178 |
region="region", |
| 179 |
project_id="project", |
| 180 |
_strict_response_validation=True, |
| 181 |
default_headers={"x-stainless-helper": "parent"}, |
| 182 |
) |
| 183 |
copied = client.copy(default_headers={"x-stainless-helper": "child"}) |
| 184 |
assert copied.default_headers["x-stainless-helper"] == "parent, child" |
| 185 |
|
| 186 |
def test_global_region_base_url(self) -> None: |
| 187 |
"""Test that global region uses the correct base URL.""" |
| 188 |
client = AnthropicVertex(region="global", project_id="test-project", access_token="fake-token") |
| 189 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.googleapis.com/v1" |
| 190 |
|
| 191 |
def test_us_region_base_url(self) -> None: |
| 192 |
"""Test that us region uses the correct base URL.""" |
| 193 |
client = AnthropicVertex(region="us", project_id="test-project", access_token="fake-token") |
| 194 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.us.rep.googleapis.com/v1" |
| 195 |
|
| 196 |
def test_eu_region_base_url(self) -> None: |
| 197 |
"""Test that us region uses the correct base URL.""" |
| 198 |
client = AnthropicVertex(region="eu", project_id="test-project", access_token="fake-token") |
| 199 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.eu.rep.googleapis.com/v1" |
| 200 |
|
| 201 |
@pytest.mark.parametrize("region", ["us-central1", "europe-west1", "asia-southeast1"]) |
| 202 |
def test_regional_base_url(self, region: str) -> None: |
| 203 |
"""Test that regional endpoints use the correct base URL format.""" |
| 204 |
client = AnthropicVertex(region=region, project_id="test-project", access_token="fake-token") |
| 205 |
expected_url = f"https://{region}-aiplatform.googleapis.com/v1" |
| 206 |
assert str(client.base_url).rstrip("/") == expected_url |
| 207 |
|
| 208 |
def test_env_var_base_url_override(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 209 |
"""Test that ANTHROPIC_VERTEX_BASE_URL environment variable does not override client arg.""" |
| 210 |
test_url = "https://custom-endpoint.googleapis.com/v1" |
| 211 |
|
| 212 |
monkeypatch.setenv("ANTHROPIC_VERTEX_BASE_URL", test_url) |
| 213 |
|
| 214 |
client = AnthropicVertex( |
| 215 |
region="global", # we expect this to get ignored since the user is providing a base_url |
| 216 |
project_id="test-project", |
| 217 |
access_token="fake-token", |
| 218 |
base_url="https://test.googleapis.com/v1", |
| 219 |
) |
| 220 |
assert str(client.base_url).rstrip("/") == "https://test.googleapis.com/v1" |
| 221 |
|
| 222 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 223 |
@pytest.mark.respx() |
| 224 |
def test_beta_tool_runner_routes_through_raw_predict(self, respx_mock: MockRouter) -> None: |
| 225 |
@beta_tool |
| 226 |
def get_weather(city: str) -> str: |
| 227 |
"""Get the weather. |
| 228 |
|
| 229 |
Args: |
| 230 |
city: city name |
| 231 |
""" |
| 232 |
return f"sunny in {city}" |
| 233 |
|
| 234 |
respx_mock.post(url__startswith="https://region-aiplatform.googleapis.com/").mock( |
| 235 |
side_effect=_tool_runner_responses() |
| 236 |
) |
| 237 |
|
| 238 |
final = self.client.beta.messages.tool_runner( |
| 239 |
model="claude-haiku-4-5@20251001", |
| 240 |
max_tokens=256, |
| 241 |
messages=[{"role": "user", "content": "weather in Paris?"}], |
| 242 |
tools=[get_weather], |
| 243 |
).until_done() |
| 244 |
|
| 245 |
assert final.stop_reason == "end_turn" |
| 246 |
_assert_tool_runner_calls(cast("list[MockRequestCall]", respx_mock.calls)) |
| 247 |
|
| 248 |
def test_beta_messages_helpers_are_bound(self) -> None: |
| 249 |
for name in ("create", "parse", "stream", "tool_runner", "count_tokens"): |
| 250 |
assert callable(getattr(self.client.beta.messages, name)) |
| 251 |
|
| 252 |
|
| 253 |
def test_refresh_without_google_auth_raises_actionable_error(monkeypatch: pytest.MonkeyPatch) -> None: |
| 254 |
# `None` in sys.modules makes the import fail even when google-auth is installed. |
| 255 |
monkeypatch.setitem(sys.modules, "google.auth.transport.requests", cast(Any, None)) |
| 256 |
|
| 257 |
class FakeCredentials: |
| 258 |
def refresh(self, _request: object) -> None: |
| 259 |
raise AssertionError("should not be reached: building the request needs google-auth") |
| 260 |
|
| 261 |
with pytest.raises(MissingDependencyError, match=r"anthropic\[vertex\]"): |
| 262 |
refresh_auth(cast(Any, FakeCredentials())) |
| 263 |
|
| 264 |
|
| 265 |
class TestAsyncAnthropicVertex: |
| 266 |
client = AsyncAnthropicVertex(region="region", project_id="project", access_token="my-access-token") |
| 267 |
|
| 268 |
@pytest.mark.respx() |
| 269 |
@pytest.mark.asyncio() |
| 270 |
async def test_messages_retries(self, respx_mock: MockRouter) -> None: |
| 271 |
request_url = "https://region-aiplatform.googleapis.com/v1/projects/project/locations/region/publishers/anthropic/models/claude-3-sonnet@20240229:rawPredict" |
| 272 |
respx_mock.post(request_url).mock( |
| 273 |
side_effect=[ |
| 274 |
httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}), |
| 275 |
httpx2.Response(200, json={"foo": "bar"}), |
| 276 |
] |
| 277 |
) |
| 278 |
|
| 279 |
await self.client.with_options(timeout=0.2).messages.create( |
| 280 |
max_tokens=1024, |
| 281 |
messages=[ |
| 282 |
{ |
| 283 |
"role": "user", |
| 284 |
"content": "Say hello there!", |
| 285 |
} |
| 286 |
], |
| 287 |
model="claude-3-sonnet@20240229", |
| 288 |
) |
| 289 |
|
| 290 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 291 |
|
| 292 |
assert len(calls) == 2 |
| 293 |
|
| 294 |
assert calls[0].request.url == request_url |
| 295 |
assert calls[1].request.url == request_url |
| 296 |
|
| 297 |
def test_copy(self) -> None: |
| 298 |
copied = self.client.copy() |
| 299 |
assert id(copied) != id(self.client) |
| 300 |
|
| 301 |
copied = self.client.copy(region="another-region", project_id="another-project") |
| 302 |
assert copied.region == "another-region" |
| 303 |
assert self.client.region == "region" |
| 304 |
assert copied.project_id == "another-project" |
| 305 |
assert self.client.project_id == "project" |
| 306 |
|
| 307 |
def test_with_options(self) -> None: |
| 308 |
copied = self.client.with_options(region="another-region", project_id="another-project") |
| 309 |
assert copied.region == "another-region" |
| 310 |
assert self.client.region == "region" |
| 311 |
assert copied.project_id == "another-project" |
| 312 |
assert self.client.project_id == "project" |
| 313 |
|
| 314 |
def test_copy_default_options(self) -> None: |
| 315 |
# options that have a default are overridden correctly |
| 316 |
copied = self.client.copy(max_retries=7) |
| 317 |
assert copied.max_retries == 7 |
| 318 |
assert self.client.max_retries == 2 |
| 319 |
|
| 320 |
copied2 = copied.copy(max_retries=6) |
| 321 |
assert copied2.max_retries == 6 |
| 322 |
assert copied.max_retries == 7 |
| 323 |
|
| 324 |
# timeout |
| 325 |
assert isinstance(self.client.timeout, httpx2.Timeout) |
| 326 |
copied = self.client.copy(timeout=None) |
| 327 |
assert copied.timeout is None |
| 328 |
assert isinstance(self.client.timeout, httpx2.Timeout) |
| 329 |
|
| 330 |
def test_copy_default_headers(self) -> None: |
| 331 |
client = AsyncAnthropicVertex( |
| 332 |
base_url=base_url, |
| 333 |
region="region", |
| 334 |
project_id="project", |
| 335 |
_strict_response_validation=True, |
| 336 |
default_headers={"X-Foo": "bar"}, |
| 337 |
) |
| 338 |
assert client.default_headers["X-Foo"] == "bar" |
| 339 |
|
| 340 |
# does not override the already given value when not specified |
| 341 |
copied = client.copy() |
| 342 |
assert copied.default_headers["X-Foo"] == "bar" |
| 343 |
|
| 344 |
# merges already given headers |
| 345 |
copied = client.copy(default_headers={"X-Bar": "stainless"}) |
| 346 |
assert copied.default_headers["X-Foo"] == "bar" |
| 347 |
assert copied.default_headers["X-Bar"] == "stainless" |
| 348 |
|
| 349 |
# uses new values for any already given headers |
| 350 |
copied = client.copy(default_headers={"X-Foo": "stainless"}) |
| 351 |
assert copied.default_headers["X-Foo"] == "stainless" |
| 352 |
|
| 353 |
# set_default_headers |
| 354 |
|
| 355 |
# completely overrides already set values |
| 356 |
copied = client.copy(set_default_headers={}) |
| 357 |
assert copied.default_headers.get("X-Foo") is None |
| 358 |
|
| 359 |
copied = client.copy(set_default_headers={"X-Bar": "Robert"}) |
| 360 |
assert copied.default_headers["X-Bar"] == "Robert" |
| 361 |
|
| 362 |
with pytest.raises( |
| 363 |
ValueError, |
| 364 |
match="`default_headers` and `set_default_headers` arguments are mutually exclusive", |
| 365 |
): |
| 366 |
client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) |
| 367 |
|
| 368 |
def test_copy_x_stainless_helper_header_appends(self) -> None: |
| 369 |
# `x-stainless-helper` accumulates across copies instead of being clobbered |
| 370 |
client = AsyncAnthropicVertex( |
| 371 |
base_url=base_url, |
| 372 |
region="region", |
| 373 |
project_id="project", |
| 374 |
_strict_response_validation=True, |
| 375 |
default_headers={"x-stainless-helper": "parent"}, |
| 376 |
) |
| 377 |
copied = client.copy(default_headers={"x-stainless-helper": "child"}) |
| 378 |
assert copied.default_headers["x-stainless-helper"] == "parent, child" |
| 379 |
|
| 380 |
def test_global_region_base_url(self) -> None: |
| 381 |
"""Test that global region uses the correct base URL.""" |
| 382 |
client = AsyncAnthropicVertex(region="global", project_id="test-project", access_token="fake-token") |
| 383 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.googleapis.com/v1" |
| 384 |
|
| 385 |
def test_us_region_base_url(self) -> None: |
| 386 |
"""Test that us region uses the correct base URL.""" |
| 387 |
client = AsyncAnthropicVertex(region="us", project_id="test-project", access_token="fake-token") |
| 388 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.us.rep.googleapis.com/v1" |
| 389 |
|
| 390 |
def test_eu_region_base_url(self) -> None: |
| 391 |
"""Test that eu region uses the correct base URL.""" |
| 392 |
client = AsyncAnthropicVertex(region="eu", project_id="test-project", access_token="fake-token") |
| 393 |
assert str(client.base_url).rstrip("/") == "https://aiplatform.eu.rep.googleapis.com/v1" |
| 394 |
|
| 395 |
def test_regional_base_url(self) -> None: |
| 396 |
"""Test that regional endpoints use the correct base URL format.""" |
| 397 |
test_regions = ["us-central1", "europe-west1", "asia-southeast1"] |
| 398 |
|
| 399 |
for region in test_regions: |
| 400 |
client = AsyncAnthropicVertex(region=region, project_id="test-project", access_token="fake-token") |
| 401 |
expected_url = f"https://{region}-aiplatform.googleapis.com/v1" |
| 402 |
assert str(client.base_url).rstrip("/") == expected_url |
| 403 |
|
| 404 |
def test_env_var_base_url_override(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 405 |
"""Test that ANTHROPIC_VERTEX_BASE_URL environment variable does not override client arg.""" |
| 406 |
test_url = "https://custom-endpoint.googleapis.com/v1" |
| 407 |
|
| 408 |
monkeypatch.setenv("ANTHROPIC_VERTEX_BASE_URL", test_url) |
| 409 |
|
| 410 |
client = AsyncAnthropicVertex( |
| 411 |
region="global", # we expect this to get ignored since the user is providing a base_url |
| 412 |
project_id="test-project", |
| 413 |
access_token="fake-token", |
| 414 |
base_url="https://test.googleapis.com/v1", |
| 415 |
) |
| 416 |
assert str(client.base_url).rstrip("/") == "https://test.googleapis.com/v1" |
| 417 |
|
| 418 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 419 |
@pytest.mark.respx() |
| 420 |
@pytest.mark.asyncio() |
| 421 |
async def test_beta_tool_runner_routes_through_raw_predict(self, respx_mock: MockRouter) -> None: |
| 422 |
@beta_async_tool |
| 423 |
async def get_weather(city: str) -> str: |
| 424 |
"""Get the weather. |
| 425 |
|
| 426 |
Args: |
| 427 |
city: city name |
| 428 |
""" |
| 429 |
return f"sunny in {city}" |
| 430 |
|
| 431 |
respx_mock.post(url__startswith="https://region-aiplatform.googleapis.com/").mock( |
| 432 |
side_effect=_tool_runner_responses() |
| 433 |
) |
| 434 |
|
| 435 |
final = await self.client.beta.messages.tool_runner( |
| 436 |
model="claude-haiku-4-5@20251001", |
| 437 |
max_tokens=256, |
| 438 |
messages=[{"role": "user", "content": "weather in Paris?"}], |
| 439 |
tools=[get_weather], |
| 440 |
).until_done() |
| 441 |
|
| 442 |
assert final.stop_reason == "end_turn" |
| 443 |
_assert_tool_runner_calls(cast("list[MockRequestCall]", respx_mock.calls)) |
| 444 |
|
| 445 |
def test_beta_messages_helpers_are_bound(self) -> None: |
| 446 |
for name in ("create", "parse", "stream", "tool_runner", "count_tokens"): |
| 447 |
assert callable(getattr(self.client.beta.messages, name)) |