| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
from typing import TYPE_CHECKING, Any, Union, Mapping, TypeVar, Sequence |
| 5 |
from typing_extensions import Self, override |
| 6 |
|
| 7 |
import httpx2 |
| 8 |
|
| 9 |
from ... import _exceptions |
| 10 |
from ._auth import load_auth, refresh_auth |
| 11 |
from ._beta import Beta, AsyncBeta |
| 12 |
from ..._types import NotGiven, not_given |
| 13 |
from ..._utils import is_dict, asyncify, is_given |
| 14 |
from ..._compat import model_copy, typed_cached_property |
| 15 |
from ..._models import FinalRequestOptions |
| 16 |
from ..._version import __version__ |
| 17 |
from ..._streaming import Stream, AsyncStream |
| 18 |
from ..._exceptions import AnthropicError, APIStatusError |
| 19 |
from ..._middleware import MiddlewareInput |
| 20 |
from ..._base_client import ( |
| 21 |
DEFAULT_MAX_RETRIES, |
| 22 |
BaseClient, |
| 23 |
SyncAPIClient, |
| 24 |
AsyncAPIClient, |
| 25 |
merge_headers, |
| 26 |
) |
| 27 |
from ...resources.messages import Messages, AsyncMessages |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from google.auth.credentials import Credentials as GoogleCredentials # type: ignore |
| 31 |
|
| 32 |
|
| 33 |
DEFAULT_VERSION = "vertex-2023-10-16" |
| 34 |
|
| 35 |
_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx2.Client, httpx2.AsyncClient]) |
| 36 |
_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) |
| 37 |
|
| 38 |
|
| 39 |
class BaseVertexClient(BaseClient[_HttpxClientT, _DefaultStreamT]): |
| 40 |
@typed_cached_property |
| 41 |
def region(self) -> str: |
| 42 |
raise RuntimeError("region not set") |
| 43 |
|
| 44 |
@typed_cached_property |
| 45 |
def project_id(self) -> str | None: |
| 46 |
project_id = os.environ.get("ANTHROPIC_VERTEX_PROJECT_ID") |
| 47 |
if project_id: |
| 48 |
return project_id |
| 49 |
|
| 50 |
return None |
| 51 |
|
| 52 |
@override |
| 53 |
def _make_status_error( |
| 54 |
self, |
| 55 |
err_msg: str, |
| 56 |
*, |
| 57 |
body: object, |
| 58 |
response: httpx2.Response, |
| 59 |
) -> APIStatusError: |
| 60 |
if response.status_code == 400: |
| 61 |
return _exceptions.BadRequestError(err_msg, response=response, body=body) |
| 62 |
|
| 63 |
if response.status_code == 401: |
| 64 |
return _exceptions.AuthenticationError(err_msg, response=response, body=body) |
| 65 |
|
| 66 |
if response.status_code == 403: |
| 67 |
return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) |
| 68 |
|
| 69 |
if response.status_code == 404: |
| 70 |
return _exceptions.NotFoundError(err_msg, response=response, body=body) |
| 71 |
|
| 72 |
if response.status_code == 409: |
| 73 |
return _exceptions.ConflictError(err_msg, response=response, body=body) |
| 74 |
|
| 75 |
if response.status_code == 422: |
| 76 |
return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) |
| 77 |
|
| 78 |
if response.status_code == 429: |
| 79 |
return _exceptions.RateLimitError(err_msg, response=response, body=body) |
| 80 |
|
| 81 |
if response.status_code == 503: |
| 82 |
return _exceptions.ServiceUnavailableError(err_msg, response=response, body=body) |
| 83 |
|
| 84 |
if response.status_code == 504: |
| 85 |
return _exceptions.DeadlineExceededError(err_msg, response=response, body=body) |
| 86 |
|
| 87 |
if response.status_code >= 500: |
| 88 |
return _exceptions.InternalServerError(err_msg, response=response, body=body) |
| 89 |
return APIStatusError(err_msg, response=response, body=body) |
| 90 |
|
| 91 |
|
| 92 |
class AnthropicVertex(BaseVertexClient[httpx2.Client, Stream[Any]], SyncAPIClient): |
| 93 |
messages: Messages |
| 94 |
beta: Beta |
| 95 |
|
| 96 |
def __init__( |
| 97 |
self, |
| 98 |
*, |
| 99 |
region: str | NotGiven = not_given, |
| 100 |
project_id: str | NotGiven = not_given, |
| 101 |
access_token: str | None = None, |
| 102 |
credentials: GoogleCredentials | None = None, |
| 103 |
base_url: str | httpx2.URL | None = None, |
| 104 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 105 |
max_retries: int = DEFAULT_MAX_RETRIES, |
| 106 |
default_headers: Mapping[str, str] | None = None, |
| 107 |
default_query: Mapping[str, object] | None = None, |
| 108 |
# Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. |
| 109 |
http_client: httpx2.Client | None = None, |
| 110 |
middleware: Sequence[MiddlewareInput] | None = None, |
| 111 |
_strict_response_validation: bool = False, |
| 112 |
) -> None: |
| 113 |
if not is_given(region): |
| 114 |
region = os.environ.get("CLOUD_ML_REGION", not_given) |
| 115 |
if not is_given(region): |
| 116 |
raise ValueError( |
| 117 |
"No region was given. The client should be instantiated with the `region` argument or the `CLOUD_ML_REGION` environment variable should be set." |
| 118 |
) |
| 119 |
|
| 120 |
if base_url is None: |
| 121 |
base_url = os.environ.get("ANTHROPIC_VERTEX_BASE_URL") |
| 122 |
if base_url is None: |
| 123 |
if region == "global": |
| 124 |
base_url = "https://aiplatform.googleapis.com/v1" |
| 125 |
elif region == "us": |
| 126 |
base_url = "https://aiplatform.us.rep.googleapis.com/v1" |
| 127 |
elif region == "eu": |
| 128 |
base_url = "https://aiplatform.eu.rep.googleapis.com/v1" |
| 129 |
else: |
| 130 |
base_url = f"https://{region}-aiplatform.googleapis.com/v1" |
| 131 |
|
| 132 |
super().__init__( |
| 133 |
version=__version__, |
| 134 |
base_url=base_url, |
| 135 |
timeout=timeout, |
| 136 |
max_retries=max_retries, |
| 137 |
custom_headers=default_headers, |
| 138 |
custom_query=default_query, |
| 139 |
http_client=http_client, |
| 140 |
middleware=middleware, |
| 141 |
_strict_response_validation=_strict_response_validation, |
| 142 |
) |
| 143 |
|
| 144 |
if is_given(project_id): |
| 145 |
self.project_id = project_id |
| 146 |
|
| 147 |
self.region = region |
| 148 |
self.access_token = access_token |
| 149 |
self.credentials = credentials |
| 150 |
|
| 151 |
self.messages = Messages(self) |
| 152 |
self.beta = Beta(self) |
| 153 |
|
| 154 |
@override |
| 155 |
def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: |
| 156 |
return _prepare_options(options, project_id=self.project_id, region=self.region) |
| 157 |
|
| 158 |
@override |
| 159 |
def _prepare_request(self, request: httpx2.Request) -> None: |
| 160 |
if request.headers.get("Authorization"): |
| 161 |
# already authenticated, nothing for us to do |
| 162 |
return |
| 163 |
|
| 164 |
request.headers["Authorization"] = f"Bearer {self._ensure_access_token()}" |
| 165 |
|
| 166 |
def _ensure_access_token(self) -> str: |
| 167 |
if self.access_token is not None: |
| 168 |
return self.access_token |
| 169 |
|
| 170 |
if not self.credentials: |
| 171 |
self.credentials, project_id = load_auth(project_id=self.project_id) |
| 172 |
if not self.project_id: |
| 173 |
self.project_id = project_id |
| 174 |
|
| 175 |
if self.credentials.expired or not self.credentials.token: |
| 176 |
refresh_auth(self.credentials) |
| 177 |
|
| 178 |
if not self.credentials.token: |
| 179 |
raise RuntimeError("Could not resolve API token from the environment") |
| 180 |
|
| 181 |
assert isinstance(self.credentials.token, str) |
| 182 |
return self.credentials.token |
| 183 |
|
| 184 |
def copy( |
| 185 |
self, |
| 186 |
*, |
| 187 |
region: str | NotGiven = not_given, |
| 188 |
project_id: str | NotGiven = not_given, |
| 189 |
access_token: str | None = None, |
| 190 |
credentials: GoogleCredentials | None = None, |
| 191 |
base_url: str | httpx2.URL | None = None, |
| 192 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 193 |
http_client: httpx2.Client | None = None, |
| 194 |
max_retries: int | NotGiven = not_given, |
| 195 |
default_headers: Mapping[str, str] | None = None, |
| 196 |
set_default_headers: Mapping[str, str] | None = None, |
| 197 |
default_query: Mapping[str, object] | None = None, |
| 198 |
set_default_query: Mapping[str, object] | None = None, |
| 199 |
middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given, |
| 200 |
_extra_kwargs: Mapping[str, Any] = {}, |
| 201 |
) -> Self: |
| 202 |
""" |
| 203 |
Create a new client instance re-using the same options given to the current client with optional overriding. |
| 204 |
""" |
| 205 |
if default_headers is not None and set_default_headers is not None: |
| 206 |
raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") |
| 207 |
|
| 208 |
if default_query is not None and set_default_query is not None: |
| 209 |
raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") |
| 210 |
|
| 211 |
headers = self._custom_headers |
| 212 |
if default_headers is not None: |
| 213 |
headers = merge_headers(headers, default_headers) |
| 214 |
elif set_default_headers is not None: |
| 215 |
headers = set_default_headers |
| 216 |
|
| 217 |
params = self._custom_query |
| 218 |
if default_query is not None: |
| 219 |
params = {**params, **default_query} |
| 220 |
elif set_default_query is not None: |
| 221 |
params = set_default_query |
| 222 |
|
| 223 |
http_client = http_client or self._client |
| 224 |
|
| 225 |
return self.__class__( |
| 226 |
region=region if is_given(region) else self.region, |
| 227 |
project_id=project_id if is_given(project_id) else self.project_id or not_given, |
| 228 |
access_token=access_token or self.access_token, |
| 229 |
credentials=credentials or self.credentials, |
| 230 |
base_url=base_url or self.base_url, |
| 231 |
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, |
| 232 |
http_client=http_client, |
| 233 |
max_retries=max_retries if is_given(max_retries) else self.max_retries, |
| 234 |
default_headers=headers, |
| 235 |
default_query=params, |
| 236 |
middleware=self._middleware if isinstance(middleware, NotGiven) else middleware, |
| 237 |
**_extra_kwargs, |
| 238 |
) |
| 239 |
|
| 240 |
# Alias for `copy` for nicer inline usage, e.g. |
| 241 |
# client.with_options(timeout=10).foo.create(...) |
| 242 |
with_options = copy |
| 243 |
|
| 244 |
def with_middleware(self, *middleware: MiddlewareInput) -> Self: |
| 245 |
"""A new client with the given middleware appended after this client's middleware. |
| 246 |
|
| 247 |
Convenience for applying extra middleware to a single request: |
| 248 |
|
| 249 |
```py |
| 250 |
client.with_middleware(my_middleware).messages.create(...) |
| 251 |
``` |
| 252 |
""" |
| 253 |
return self.copy(middleware=[*self._middleware, *middleware]) |
| 254 |
|
| 255 |
|
| 256 |
class AsyncAnthropicVertex(BaseVertexClient[httpx2.AsyncClient, AsyncStream[Any]], AsyncAPIClient): |
| 257 |
messages: AsyncMessages |
| 258 |
beta: AsyncBeta |
| 259 |
|
| 260 |
def __init__( |
| 261 |
self, |
| 262 |
*, |
| 263 |
region: str | NotGiven = not_given, |
| 264 |
project_id: str | NotGiven = not_given, |
| 265 |
access_token: str | None = None, |
| 266 |
credentials: GoogleCredentials | None = None, |
| 267 |
base_url: str | httpx2.URL | None = None, |
| 268 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 269 |
max_retries: int = DEFAULT_MAX_RETRIES, |
| 270 |
default_headers: Mapping[str, str] | None = None, |
| 271 |
default_query: Mapping[str, object] | None = None, |
| 272 |
# Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. |
| 273 |
http_client: httpx2.AsyncClient | None = None, |
| 274 |
middleware: Sequence[MiddlewareInput] | None = None, |
| 275 |
_strict_response_validation: bool = False, |
| 276 |
) -> None: |
| 277 |
if not is_given(region): |
| 278 |
region = os.environ.get("CLOUD_ML_REGION", not_given) |
| 279 |
if not is_given(region): |
| 280 |
raise ValueError( |
| 281 |
"No region was given. The client should be instantiated with the `region` argument or the `CLOUD_ML_REGION` environment variable should be set." |
| 282 |
) |
| 283 |
|
| 284 |
if base_url is None: |
| 285 |
base_url = os.environ.get("ANTHROPIC_VERTEX_BASE_URL") |
| 286 |
if base_url is None: |
| 287 |
if region == "global": |
| 288 |
base_url = "https://aiplatform.googleapis.com/v1" |
| 289 |
elif region == "us": |
| 290 |
base_url = "https://aiplatform.us.rep.googleapis.com/v1" |
| 291 |
elif region == "eu": |
| 292 |
base_url = "https://aiplatform.eu.rep.googleapis.com/v1" |
| 293 |
else: |
| 294 |
base_url = f"https://{region}-aiplatform.googleapis.com/v1" |
| 295 |
|
| 296 |
super().__init__( |
| 297 |
version=__version__, |
| 298 |
base_url=base_url, |
| 299 |
timeout=timeout, |
| 300 |
max_retries=max_retries, |
| 301 |
custom_headers=default_headers, |
| 302 |
custom_query=default_query, |
| 303 |
http_client=http_client, |
| 304 |
middleware=middleware, |
| 305 |
_strict_response_validation=_strict_response_validation, |
| 306 |
) |
| 307 |
|
| 308 |
if is_given(project_id): |
| 309 |
self.project_id = project_id |
| 310 |
|
| 311 |
self.region = region |
| 312 |
self.access_token = access_token |
| 313 |
self.credentials = credentials |
| 314 |
|
| 315 |
self.messages = AsyncMessages(self) |
| 316 |
self.beta = AsyncBeta(self) |
| 317 |
|
| 318 |
@override |
| 319 |
async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: |
| 320 |
return _prepare_options(options, project_id=self.project_id, region=self.region) |
| 321 |
|
| 322 |
@override |
| 323 |
async def _prepare_request(self, request: httpx2.Request) -> None: |
| 324 |
if request.headers.get("Authorization"): |
| 325 |
# already authenticated, nothing for us to do |
| 326 |
return |
| 327 |
|
| 328 |
request.headers["Authorization"] = f"Bearer {await self._ensure_access_token()}" |
| 329 |
|
| 330 |
async def _ensure_access_token(self) -> str: |
| 331 |
if self.access_token is not None: |
| 332 |
return self.access_token |
| 333 |
|
| 334 |
if not self.credentials: |
| 335 |
self.credentials, project_id = await asyncify(load_auth)(project_id=self.project_id) |
| 336 |
if not self.project_id: |
| 337 |
self.project_id = project_id |
| 338 |
|
| 339 |
if self.credentials.expired or not self.credentials.token: |
| 340 |
await asyncify(refresh_auth)(self.credentials) |
| 341 |
|
| 342 |
if not self.credentials.token: |
| 343 |
raise RuntimeError("Could not resolve API token from the environment") |
| 344 |
|
| 345 |
assert isinstance(self.credentials.token, str) |
| 346 |
return self.credentials.token |
| 347 |
|
| 348 |
def copy( |
| 349 |
self, |
| 350 |
*, |
| 351 |
region: str | NotGiven = not_given, |
| 352 |
project_id: str | NotGiven = not_given, |
| 353 |
access_token: str | None = None, |
| 354 |
credentials: GoogleCredentials | None = None, |
| 355 |
base_url: str | httpx2.URL | None = None, |
| 356 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 357 |
http_client: httpx2.AsyncClient | None = None, |
| 358 |
max_retries: int | NotGiven = not_given, |
| 359 |
default_headers: Mapping[str, str] | None = None, |
| 360 |
set_default_headers: Mapping[str, str] | None = None, |
| 361 |
default_query: Mapping[str, object] | None = None, |
| 362 |
set_default_query: Mapping[str, object] | None = None, |
| 363 |
middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given, |
| 364 |
_extra_kwargs: Mapping[str, Any] = {}, |
| 365 |
) -> Self: |
| 366 |
""" |
| 367 |
Create a new client instance re-using the same options given to the current client with optional overriding. |
| 368 |
""" |
| 369 |
if default_headers is not None and set_default_headers is not None: |
| 370 |
raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") |
| 371 |
|
| 372 |
if default_query is not None and set_default_query is not None: |
| 373 |
raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") |
| 374 |
|
| 375 |
headers = self._custom_headers |
| 376 |
if default_headers is not None: |
| 377 |
headers = merge_headers(headers, default_headers) |
| 378 |
elif set_default_headers is not None: |
| 379 |
headers = set_default_headers |
| 380 |
|
| 381 |
params = self._custom_query |
| 382 |
if default_query is not None: |
| 383 |
params = {**params, **default_query} |
| 384 |
elif set_default_query is not None: |
| 385 |
params = set_default_query |
| 386 |
|
| 387 |
http_client = http_client or self._client |
| 388 |
|
| 389 |
return self.__class__( |
| 390 |
region=region if is_given(region) else self.region, |
| 391 |
project_id=project_id if is_given(project_id) else self.project_id or not_given, |
| 392 |
access_token=access_token or self.access_token, |
| 393 |
credentials=credentials or self.credentials, |
| 394 |
base_url=base_url or self.base_url, |
| 395 |
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, |
| 396 |
http_client=http_client, |
| 397 |
max_retries=max_retries if is_given(max_retries) else self.max_retries, |
| 398 |
default_headers=headers, |
| 399 |
default_query=params, |
| 400 |
middleware=self._middleware if isinstance(middleware, NotGiven) else middleware, |
| 401 |
**_extra_kwargs, |
| 402 |
) |
| 403 |
|
| 404 |
# Alias for `copy` for nicer inline usage, e.g. |
| 405 |
# client.with_options(timeout=10).foo.create(...) |
| 406 |
with_options = copy |
| 407 |
|
| 408 |
def with_middleware(self, *middleware: MiddlewareInput) -> Self: |
| 409 |
"""A new client with the given middleware appended after this client's middleware. |
| 410 |
|
| 411 |
Convenience for applying extra middleware to a single request: |
| 412 |
|
| 413 |
```py |
| 414 |
client.with_middleware(my_middleware).messages.create(...) |
| 415 |
``` |
| 416 |
""" |
| 417 |
return self.copy(middleware=[*self._middleware, *middleware]) |
| 418 |
|
| 419 |
|
| 420 |
def _prepare_options(input_options: FinalRequestOptions, *, project_id: str | None, region: str) -> FinalRequestOptions: |
| 421 |
options = model_copy(input_options, deep=True) |
| 422 |
|
| 423 |
if is_dict(options.json_data): |
| 424 |
options.json_data.setdefault("anthropic_version", DEFAULT_VERSION) |
| 425 |
|
| 426 |
if options.url in {"/v1/messages", "/v1/messages?beta=true"} and options.method == "post": |
| 427 |
if project_id is None: |
| 428 |
raise RuntimeError( |
| 429 |
"No project_id was given and it could not be resolved from credentials. The client should be instantiated with the `project_id` argument or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set." |
| 430 |
) |
| 431 |
|
| 432 |
if not is_dict(options.json_data): |
| 433 |
raise RuntimeError("Expected json data to be a dictionary for post /v1/messages") |
| 434 |
|
| 435 |
model = options.json_data.pop("model") |
| 436 |
stream = options.json_data.get("stream", False) |
| 437 |
specifier = "streamRawPredict" if stream else "rawPredict" |
| 438 |
|
| 439 |
options.url = f"/projects/{project_id}/locations/{region}/publishers/anthropic/models/{model}:{specifier}" |
| 440 |
|
| 441 |
if options.url in {"/v1/messages/count_tokens", "/v1/messages/count_tokens?beta=true"} and options.method == "post": |
| 442 |
if project_id is None: |
| 443 |
raise RuntimeError( |
| 444 |
"No project_id was given and it could not be resolved from credentials. The client should be instantiated with the `project_id` argument or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set." |
| 445 |
) |
| 446 |
|
| 447 |
options.url = f"/projects/{project_id}/locations/{region}/publishers/anthropic/models/count-tokens:rawPredict" |
| 448 |
|
| 449 |
if options.url.startswith("/v1/messages/batches"): |
| 450 |
raise AnthropicError("The Batch API is not supported in the Vertex client yet") |
| 451 |
|
| 452 |
return options |