Skip to content

Commit

Permalink
fix(vertex): avoid credentials refresh on every request (#575)
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertCraigie committed Jul 8, 2024
1 parent 0407a1b commit eea1662
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/anthropic/lib/vertex/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,11 @@ def __init__(

@override
def _prepare_request(self, request: httpx.Request) -> None:
access_token = self._ensure_access_token()

if request.headers.get("Authorization"):
# already authenticated, nothing for us to do
return

request.headers["Authorization"] = f"Bearer {access_token}"
request.headers["Authorization"] = f"Bearer {self._ensure_access_token()}"

def _ensure_access_token(self) -> str:
if self.access_token is not None:
Expand All @@ -184,7 +182,8 @@ def _ensure_access_token(self) -> str:
self.credentials, project_id = load_auth(project_id=self.project_id)
if not self.project_id:
self.project_id = project_id
else:

if self.credentials.expired:
refresh_auth(self.credentials)

if not self.credentials.token:
Expand Down Expand Up @@ -256,13 +255,11 @@ def __init__(

@override
async def _prepare_request(self, request: httpx.Request) -> None:
access_token = await self._ensure_access_token()

if request.headers.get("Authorization"):
# already authenticated, nothing for us to do
return

request.headers["Authorization"] = f"Bearer {access_token}"
request.headers["Authorization"] = f"Bearer {await self._ensure_access_token()}"

async def _ensure_access_token(self) -> str:
if self.access_token is not None:
Expand All @@ -272,11 +269,12 @@ async def _ensure_access_token(self) -> str:
self.credentials, project_id = await asyncify(load_auth)(project_id=self.project_id)
if not self.project_id:
self.project_id = project_id
else:

if self.credentials.expired:
await asyncify(refresh_auth)(self.credentials)

if not self.credentials.token:
raise RuntimeError("Could not resolve API token from the environment")

assert isinstance(self.credentials.token, str)
return self.credentials.token
return self.credentials.token

0 comments on commit eea1662

Please sign in to comment.