-
Notifications
You must be signed in to change notification settings - Fork 781
Add provider for Anthropic's Vertexai Client #1392
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,7 +34,7 @@ | |
from . import Model, ModelRequestParameters, StreamedResponse, cached_async_http_client, check_allow_model_requests | ||
|
||
try: | ||
from anthropic import NOT_GIVEN, APIStatusError, AsyncAnthropic, AsyncStream | ||
from anthropic import NOT_GIVEN, APIStatusError, AsyncAnthropic, AsyncAnthropicVertex, AsyncStream | ||
from anthropic.types import ( | ||
Base64PDFSourceParam, | ||
ContentBlock, | ||
|
@@ -108,7 +108,7 @@ class AnthropicModel(Model): | |
We anticipate adding support for streaming responses in a near-term future release. | ||
""" | ||
|
||
client: AsyncAnthropic = field(repr=False) | ||
client: AsyncAnthropic | AsyncAnthropicVertex = field(repr=False) | ||
|
||
_model_name: AnthropicModelName = field(repr=False) | ||
_system: str = field(default='anthropic', repr=False) | ||
|
@@ -117,15 +117,21 @@ def __init__( | |
self, | ||
model_name: AnthropicModelName, | ||
*, | ||
provider: Literal['anthropic'] | Provider[AsyncAnthropic] = 'anthropic', | ||
# breaking this in multiple lines breaks pycharm type recognition. However, I was unable to stop ruff from | ||
# doing it - # fmt: skip etc didn't work :( | ||
provider: Literal['anthropic', 'anthropic-vertex'] | ||
| Provider[AsyncAnthropicVertex] | ||
| Provider[AsyncAnthropic] = # fmt: skip | ||
'anthropic', | ||
): | ||
"""Initialize an Anthropic model. | ||
|
||
Args: | ||
model_name: The name of the Anthropic model to use. List of model names available | ||
[here](https://docs.anthropic.com/en/docs/about-claude/models). | ||
provider: The provider to use for the Anthropic API. Can be either the string 'anthropic' or an | ||
instance of `Provider[AsyncAnthropic]`. If not provided, the other parameters will be used. | ||
provider: The provider to use for the Anthropic API. Can be either the string 'anthropic', | ||
'anthropic-vertex', or an instance of Provider[AsyncAnthropic] or Provider[AsyncAnthropicVertex]. | ||
Defaults to 'anthropic'. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe you should also add an entry to the |
||
""" | ||
self._model_name = model_name | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -73,6 +73,10 @@ def infer_provider(provider: str) -> Provider[Any]: | |
from .anthropic import AnthropicProvider | ||
|
||
return AnthropicProvider() | ||
elif provider == 'anthropic-vertex': | ||
from .anthropic_vertex import AnthropicVertexProvider | ||
|
||
return AnthropicVertexProvider() | ||
Comment on lines
+76
to
+79
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is tricky. If you want Right now, the class GoogleVertexProvider(Provider):
def get_client(self, tp: type[T]) -> T:
if isinstance(tp, httpx.AsyncClient):
return self.httpx_client
elif isinstance(tp, AsyncAnthropicVertex):
return self.anthropic_client
else:
raise ValueError('not supported') |
||
elif provider == 'mistral': | ||
from .mistral import MistralProvider | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
from __future__ import annotations as _annotations | ||
|
||
from pydantic_ai.providers import Provider | ||
|
||
try: | ||
from anthropic import AsyncAnthropicVertex | ||
except ImportError as _import_error: # pragma: no cover | ||
raise ImportError( | ||
'Please install the `anthropic` package to use the Anthropic provider, ' | ||
'you can use the `anthropic` optional group — `pip install "pydantic-ai-slim[anthropic]"`' | ||
) from _import_error | ||
|
||
|
||
class AnthropicVertexProvider(Provider[AsyncAnthropicVertex]): | ||
"""Provider for Anthropic API.""" | ||
|
||
@property | ||
def name(self) -> str: | ||
return 'anthropic-vertex' | ||
|
||
@property | ||
def base_url(self) -> str: | ||
return str(self._client.base_url) | ||
|
||
@property | ||
def client(self) -> AsyncAnthropicVertex: | ||
return self._client | ||
|
||
def __init__( | ||
self, | ||
*, | ||
anthropic_client: AsyncAnthropicVertex | None = None, | ||
) -> None: | ||
"""Create a new Anthropic provider. | ||
|
||
Args: | ||
anthropic_client: An existing [`AsyncAnthropic`](https://github.com/anthropics/anthropic-sdk-python) | ||
client to use. If provided, the `api_key` and `http_client` arguments will be ignored. | ||
""" | ||
if anthropic_client: | ||
self._client = anthropic_client | ||
else: | ||
self._client = AsyncAnthropicVertex() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from __future__ import annotations as _annotations | ||
|
||
import pytest | ||
|
||
from ..conftest import try_import | ||
|
||
with try_import() as imports_successful: | ||
from anthropic import AsyncAnthropicVertex | ||
|
||
from pydantic_ai.providers.anthropic_vertex import AnthropicVertexProvider | ||
|
||
|
||
pytestmark = pytest.mark.skipif(not imports_successful(), reason='need to install anthropic-vertex') | ||
|
||
|
||
def test_anthropic_provider_with_project_and_region(): | ||
mock_region = 'us-east5' | ||
client = AsyncAnthropicVertex(project_id='test-project', region=mock_region) | ||
provider = AnthropicVertexProvider(anthropic_client=client) | ||
assert provider.name == 'anthropic-vertex' | ||
assert provider.base_url == f'https://{mock_region}-aiplatform.googleapis.com/v1/' | ||
assert isinstance(provider.client, AsyncAnthropicVertex) | ||
assert provider.client.region == mock_region | ||
|
||
|
||
def test_anthropic_provider_with_empty_client_and_valid_env(monkeypatch: pytest.MonkeyPatch): | ||
mock_region = 'europe-west3' | ||
monkeypatch.setenv('CLOUD_ML_REGION', mock_region) | ||
|
||
client = AsyncAnthropicVertex() | ||
provider = AnthropicVertexProvider(anthropic_client=client) | ||
assert provider.name == 'anthropic-vertex' | ||
assert provider.client.region == mock_region | ||
assert provider.base_url == f'https://{mock_region}-aiplatform.googleapis.com/v1/' | ||
assert isinstance(provider.client, AsyncAnthropicVertex) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you need to do
# fmt: off
and# fmt: on
after.