Skip to content
Merged
Show file tree
Hide file tree
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
53 changes: 0 additions & 53 deletions pydantic_ai_slim/pydantic_ai/profiles/anthropic.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from __future__ import annotations as _annotations

from dataclasses import dataclass

from .._json_schema import JsonSchema, JsonSchemaTransformer
from . import ModelProfile


Expand All @@ -22,54 +19,4 @@ def anthropic_model_profile(model_name: str) -> ModelProfile | None:
return ModelProfile(
thinking_tags=('<thinking>', '</thinking>'),
supports_json_schema_output=supports_json_schema_output,
json_schema_transformer=AnthropicJsonSchemaTransformer,
)


@dataclass(init=False)
class AnthropicJsonSchemaTransformer(JsonSchemaTransformer):
"""Transforms schemas to the subset supported by Anthropic structured outputs.

Transformation is applied when:
- `NativeOutput` is used as the `output_type` of the Agent
- `strict=True` is set on the `Tool`

The behavior of this transformer differs from the OpenAI one in that it sets `Tool.strict=False` by default when not explicitly set to True.

Example:
```python
from pydantic_ai import Agent

agent = Agent('anthropic:claude-sonnet-4-5')

@agent.tool_plain # -> defaults to strict=False
def my_tool(x: str) -> dict[str, int]:
...
```

Anthropic's SDK `transform_schema()` automatically:
- Adds `additionalProperties: false` to all objects (required by API)
- Removes unsupported constraints (minLength, pattern, etc.)
- Moves removed constraints to description field
- Removes title and $schema fields
"""

def walk(self) -> JsonSchema:
from anthropic import transform_schema

schema = super().walk()

# The caller (pydantic_ai.models._customize_tool_def or _customize_output_object) coalesces
# - output_object.strict = self.is_strict_compatible
# - tool_def.strict = self.is_strict_compatible
# the reason we don't default to `strict=True` is that the transformation could be lossy
# so in order to change the behavior (default to True), we need to come up with logic that will check for lossiness
# https://github.com/pydantic/pydantic-ai/issues/3541
self.is_strict_compatible = self.strict is True # not compatible when strict is False/None

return transform_schema(schema) if self.strict is True else schema

def transform(self, schema: JsonSchema) -> JsonSchema:
schema.pop('title', None)
schema.pop('$schema', None)
return schema
58 changes: 57 additions & 1 deletion pydantic_ai_slim/pydantic_ai/providers/anthropic.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations as _annotations

import os
from dataclasses import dataclass
from typing import TypeAlias, overload

import httpx
Expand All @@ -11,6 +12,8 @@
from pydantic_ai.profiles.anthropic import anthropic_model_profile
from pydantic_ai.providers import Provider

from .._json_schema import JsonSchema, JsonSchemaTransformer

try:
from anthropic import AsyncAnthropic, AsyncAnthropicBedrock, AsyncAnthropicVertex
except ImportError as _import_error:
Expand Down Expand Up @@ -39,7 +42,8 @@ def client(self) -> AsyncAnthropicClient:
return self._client

def model_profile(self, model_name: str) -> ModelProfile | None:
return anthropic_model_profile(model_name)
profile = anthropic_model_profile(model_name)
return ModelProfile(json_schema_transformer=AnthropicJsonSchemaTransformer).update(profile)

@overload
def __init__(self, *, anthropic_client: AsyncAnthropicClient | None = None) -> None: ...
Expand Down Expand Up @@ -83,3 +87,55 @@ def __init__(
else:
http_client = cached_async_http_client(provider='anthropic')
self._client = AsyncAnthropic(api_key=api_key, base_url=base_url, http_client=http_client)


@dataclass(init=False)
class AnthropicJsonSchemaTransformer(JsonSchemaTransformer):
"""Transforms schemas to the subset supported by Anthropic structured outputs.

Transformation is applied when:
- `NativeOutput` is used as the `output_type` of the Agent
- `strict=True` is set on the `Tool`

The behavior of this transformer differs from the OpenAI one in that it sets `Tool.strict=False` by default when not explicitly set to True.

Example:
```python
from pydantic_ai import Agent

agent = Agent('anthropic:claude-sonnet-4-5')

@agent.tool_plain # -> defaults to strict=False
def my_tool(x: str) -> dict[str, int]:
...
```

Anthropic's SDK `transform_schema()` automatically:
- Adds `additionalProperties: false` to all objects (required by API)
- Removes unsupported constraints (minLength, pattern, etc.)
- Moves removed constraints to description field
- Removes title and $schema fields
"""

def walk(self) -> JsonSchema:
schema = super().walk()

# The caller (pydantic_ai.models._customize_tool_def or _customize_output_object) coalesces
# - output_object.strict = self.is_strict_compatible
# - tool_def.strict = self.is_strict_compatible
# the reason we don't default to `strict=True` is that the transformation could be lossy
# so in order to change the behavior (default to True), we need to come up with logic that will check for lossiness
# https://github.com/pydantic/pydantic-ai/issues/3541
self.is_strict_compatible = self.strict is True # not compatible when strict is False/None

if self.strict is True:
from anthropic import transform_schema

return transform_schema(schema)
else:
return schema

def transform(self, schema: JsonSchema) -> JsonSchema:
schema.pop('title', None)
schema.pop('$schema', None)
return schema
4 changes: 3 additions & 1 deletion tests/profiles/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
from inline_snapshot import snapshot
from pydantic import BaseModel, Field

from pydantic_ai.providers.anthropic import AnthropicJsonSchemaTransformer

from ..conftest import try_import

with try_import() as imports_successful:
from pydantic_ai.profiles.anthropic import AnthropicJsonSchemaTransformer, anthropic_model_profile
from pydantic_ai.profiles.anthropic import anthropic_model_profile

pytestmark = [
pytest.mark.skipif(not imports_successful(), reason='anthropic not installed'),
Expand Down
5 changes: 5 additions & 0 deletions tests/providers/test_bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,16 @@ def test_bedrock_provider_model_profile(env: TestEnv, mocker: MockerFixture):
anthropic_model_profile_mock.assert_called_with('claude-3-5-sonnet-20240620')
assert isinstance(anthropic_profile, BedrockModelProfile)
assert anthropic_profile.bedrock_supports_tool_choice is True
# Bedrock does not support native structured output, even for models that support it via direct Anthropic API
assert anthropic_profile.supports_json_schema_output is False
assert anthropic_profile.json_schema_transformer is None

anthropic_profile = provider.model_profile('anthropic.claude-instant-v1')
anthropic_model_profile_mock.assert_called_with('claude-instant')
assert isinstance(anthropic_profile, BedrockModelProfile)
assert anthropic_profile.bedrock_supports_tool_choice is True
assert anthropic_profile.supports_json_schema_output is False
assert anthropic_profile.json_schema_transformer is None

mistral_profile = provider.model_profile('mistral.mistral-large-2407-v1:0')
mistral_model_profile_mock.assert_called_with('mistral-large-2407')
Expand Down
4 changes: 2 additions & 2 deletions tests/providers/test_openrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pydantic_ai.agent import Agent
from pydantic_ai.exceptions import UserError
from pydantic_ai.profiles.amazon import amazon_model_profile
from pydantic_ai.profiles.anthropic import AnthropicJsonSchemaTransformer, anthropic_model_profile
from pydantic_ai.profiles.anthropic import anthropic_model_profile
from pydantic_ai.profiles.cohere import cohere_model_profile
from pydantic_ai.profiles.deepseek import deepseek_model_profile
from pydantic_ai.profiles.google import google_model_profile
Expand Down Expand Up @@ -127,7 +127,7 @@ def test_openrouter_provider_model_profile(mocker: MockerFixture):
anthropic_profile = provider.model_profile('anthropic/claude-3.5-sonnet')
anthropic_model_profile_mock.assert_called_with('claude-3.5-sonnet')
assert anthropic_profile is not None
assert anthropic_profile.json_schema_transformer == AnthropicJsonSchemaTransformer
assert anthropic_profile.json_schema_transformer == OpenAIJsonSchemaTransformer

mistral_profile = provider.model_profile('mistralai/mistral-large-2407')
mistral_model_profile_mock.assert_called_with('mistral-large-2407')
Expand Down
4 changes: 2 additions & 2 deletions tests/providers/test_vercel.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pydantic_ai._json_schema import InlineDefsJsonSchemaTransformer
from pydantic_ai.exceptions import UserError
from pydantic_ai.profiles.amazon import amazon_model_profile
from pydantic_ai.profiles.anthropic import AnthropicJsonSchemaTransformer, anthropic_model_profile
from pydantic_ai.profiles.anthropic import anthropic_model_profile
from pydantic_ai.profiles.cohere import cohere_model_profile
from pydantic_ai.profiles.deepseek import deepseek_model_profile
from pydantic_ai.profiles.google import GoogleJsonSchemaTransformer, google_model_profile
Expand Down Expand Up @@ -82,7 +82,7 @@ def test_vercel_provider_model_profile(mocker: MockerFixture):
profile = provider.model_profile('anthropic/claude-sonnet-4-5')
anthropic_mock.assert_called_with('claude-sonnet-4-5')
assert profile is not None
assert profile.json_schema_transformer == AnthropicJsonSchemaTransformer
assert profile.json_schema_transformer == OpenAIJsonSchemaTransformer

# Test bedrock provider
profile = provider.model_profile('bedrock/anthropic.claude-sonnet-4-5')
Expand Down