Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(vertex): avoid credentials refresh on every request #575

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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