Skip to content

Commit 19cfbbf

Browse files
jerry-reevoKludex
andauthored
Remove anthropic-beta default header set in AnthropicModel (#2544)
Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent 3429d35 commit 19cfbbf

24 files changed

+1189
-981
lines changed

pydantic_ai_slim/pydantic_ai/models/anthropic.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,6 @@
88
from datetime import datetime, timezone
99
from typing import Any, Literal, Union, cast, overload
1010

11-
from anthropic.types.beta import (
12-
BetaCitationsDelta,
13-
BetaCodeExecutionToolResultBlock,
14-
BetaCodeExecutionToolResultBlockParam,
15-
BetaInputJSONDelta,
16-
BetaServerToolUseBlockParam,
17-
BetaWebSearchToolResultBlockParam,
18-
)
1911
from typing_extensions import assert_never
2012

2113
from pydantic_ai.builtin_tools import CodeExecutionTool, WebSearchTool
@@ -47,24 +39,21 @@
4739
from ..providers import Provider, infer_provider
4840
from ..settings import ModelSettings
4941
from ..tools import ToolDefinition
50-
from . import (
51-
Model,
52-
ModelRequestParameters,
53-
StreamedResponse,
54-
check_allow_model_requests,
55-
download_item,
56-
get_user_agent,
57-
)
42+
from . import Model, ModelRequestParameters, StreamedResponse, check_allow_model_requests, download_item, get_user_agent
5843

5944
try:
6045
from anthropic import NOT_GIVEN, APIStatusError, AsyncAnthropic, AsyncStream
6146
from anthropic.types.beta import (
6247
BetaBase64PDFBlockParam,
6348
BetaBase64PDFSourceParam,
49+
BetaCitationsDelta,
6450
BetaCodeExecutionTool20250522Param,
51+
BetaCodeExecutionToolResultBlock,
52+
BetaCodeExecutionToolResultBlockParam,
6553
BetaContentBlock,
6654
BetaContentBlockParam,
6755
BetaImageBlockParam,
56+
BetaInputJSONDelta,
6857
BetaMessage,
6958
BetaMessageParam,
7059
BetaMetadataParam,
@@ -78,6 +67,7 @@
7867
BetaRawMessageStreamEvent,
7968
BetaRedactedThinkingBlock,
8069
BetaServerToolUseBlock,
70+
BetaServerToolUseBlockParam,
8171
BetaSignatureDelta,
8272
BetaTextBlock,
8373
BetaTextBlockParam,
@@ -94,6 +84,7 @@
9484
BetaToolUseBlockParam,
9585
BetaWebSearchTool20250305Param,
9686
BetaWebSearchToolResultBlock,
87+
BetaWebSearchToolResultBlockParam,
9788
)
9889
from anthropic.types.beta.beta_web_search_tool_20250305_param import UserLocation
9990
from anthropic.types.model_param import ModelParam
@@ -246,7 +237,9 @@ async def _messages_create(
246237
) -> BetaMessage | AsyncStream[BetaRawMessageStreamEvent]:
247238
# standalone function to make it easier to override
248239
tools = self._get_tools(model_request_parameters)
249-
tools += self._get_builtin_tools(model_request_parameters)
240+
builtin_tools, tool_headers = self._get_builtin_tools(model_request_parameters)
241+
tools += builtin_tools
242+
250243
tool_choice: BetaToolChoiceParam | None
251244

252245
if not tools:
@@ -264,8 +257,10 @@ async def _messages_create(
264257

265258
try:
266259
extra_headers = model_settings.get('extra_headers', {})
260+
for k, v in tool_headers.items():
261+
extra_headers.setdefault(k, v)
267262
extra_headers.setdefault('User-Agent', get_user_agent())
268-
extra_headers.setdefault('anthropic-beta', 'code-execution-2025-05-22')
263+
269264
return await self.client.beta.messages.create(
270265
max_tokens=model_settings.get('max_tokens', 4096),
271266
system=system_prompt or NOT_GIVEN,
@@ -352,8 +347,11 @@ async def _process_streamed_response(
352347
def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[BetaToolParam]:
353348
return [self._map_tool_definition(r) for r in model_request_parameters.tool_defs.values()]
354349

355-
def _get_builtin_tools(self, model_request_parameters: ModelRequestParameters) -> list[BetaToolUnionParam]:
350+
def _get_builtin_tools(
351+
self, model_request_parameters: ModelRequestParameters
352+
) -> tuple[list[BetaToolUnionParam], dict[str, str]]:
356353
tools: list[BetaToolUnionParam] = []
354+
extra_headers: dict[str, str] = {}
357355
for tool in model_request_parameters.builtin_tools:
358356
if isinstance(tool, WebSearchTool):
359357
user_location = UserLocation(type='approximate', **tool.user_location) if tool.user_location else None
@@ -367,12 +365,13 @@ def _get_builtin_tools(self, model_request_parameters: ModelRequestParameters) -
367365
)
368366
)
369367
elif isinstance(tool, CodeExecutionTool): # pragma: no branch
368+
extra_headers['anthropic-beta'] = 'code-execution-2025-05-22'
370369
tools.append(BetaCodeExecutionTool20250522Param(name='code_execution', type='code_execution_20250522'))
371370
else: # pragma: no cover
372371
raise UserError(
373372
f'`{tool.__class__.__name__}` is not supported by `AnthropicModel`. If it should be, please file an issue.'
374373
)
375-
return tools
374+
return tools, extra_headers
376375

377376
async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[BetaMessageParam]]: # noqa: C901
378377
"""Just maps a `pydantic_ai.Message` to a `anthropic.types.MessageParam`."""

tests/models/cassettes/test_anthropic/test_anthropic_code_execution_tool.yaml

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ interactions:
1515
- api.anthropic.com
1616
method: POST
1717
parsed_body:
18-
max_tokens: 1024
18+
max_tokens: 4096
1919
messages:
2020
- content:
2121
- text: How much is 3 * 12390?
@@ -34,7 +34,7 @@ interactions:
3434
connection:
3535
- keep-alive
3636
content-length:
37-
- '927'
37+
- '994'
3838
content-type:
3939
- application/json
4040
strict-transport-security:
@@ -43,12 +43,12 @@ interactions:
4343
- chunked
4444
parsed_body:
4545
container:
46-
expires_at: '2025-05-26T13:30:45.703429+00:00'
47-
id: container_011CPW9LpfbF8dmXMvVNCiQJ
46+
expires_at: '2025-08-14T12:35:01.802902Z'
47+
id: container_011CS7XodG8mEYj1PnST46H5
4848
content:
4949
- text: I'll calculate 3 * 12390 for you.
5050
type: text
51-
- id: srvtoolu_01CPfaeVC7ju4VsdzxjSLDrY
51+
- id: srvtoolu_01PZTDQyDyxVNeVikBoNo2fb
5252
input:
5353
code: |-
5454
result = 3 * 12390
@@ -62,21 +62,24 @@ interactions:
6262
stdout: |
6363
3 * 12390 = 37170
6464
type: code_execution_result
65-
tool_use_id: srvtoolu_01CPfaeVC7ju4VsdzxjSLDrY
65+
tool_use_id: srvtoolu_01PZTDQyDyxVNeVikBoNo2fb
6666
type: code_execution_tool_result
67-
- text: The answer is **37,170**.
67+
- text: 3 * 12390 = 37,170
6868
type: text
69-
id: msg_015H6Emn2T8vZhE52mU2jF1U
69+
id: msg_01RJnbK7VMxvS2SyvtyJAQVU
7070
model: claude-sonnet-4-20250514
7171
role: assistant
7272
stop_reason: end_turn
7373
stop_sequence: null
7474
type: message
7575
usage:
76+
cache_creation:
77+
ephemeral_1h_input_tokens: 0
78+
ephemeral_5m_input_tokens: 0
7679
cache_creation_input_tokens: 0
7780
cache_read_input_tokens: 0
7881
input_tokens: 1630
79-
output_tokens: 105
82+
output_tokens: 109
8083
server_tool_use:
8184
web_search_requests: 0
8285
service_tier: standard

tests/models/cassettes/test_anthropic/test_anthropic_model_empty_message_on_history.yaml

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ interactions:
1515
- api.anthropic.com
1616
method: POST
1717
parsed_body:
18-
max_tokens: 1024
18+
max_tokens: 4096
1919
messages:
2020
- content:
2121
- text: Hello, how can I help you?
@@ -36,7 +36,7 @@ interactions:
3636
connection:
3737
- keep-alive
3838
content-length:
39-
- '671'
39+
- '777'
4040
content-type:
4141
- application/json
4242
strict-transport-security:
@@ -46,26 +46,29 @@ interactions:
4646
parsed_body:
4747
content:
4848
- text: |-
49-
I can't physically give you a potato since I'm a computer program. However, I can:
49+
I can't physically give you a potato since I'm a digital assistant. However, I can:
5050
5151
1. Help you find recipes that use potatoes
52-
2. Give you tips on how to select, store, or cook potatoes
53-
3. Share information about different potato varieties
54-
4. Provide guidance on growing potatoes
52+
2. Give you tips on how to select, store, or prepare potatoes
53+
3. Share information about different types of potatoes
54+
4. Suggest where you might buy potatoes locally
5555
56-
What specifically would you like to know about potatoes?
56+
What specific information about potatoes would be most helpful to you?
5757
type: text
58-
id: msg_01UjnDmX3B57Drosu49sMteT
58+
id: msg_01PAZFa5ciacA9ptgEDMbkZM
5959
model: claude-3-5-sonnet-20241022
6060
role: assistant
6161
stop_reason: end_turn
6262
stop_sequence: null
6363
type: message
6464
usage:
65+
cache_creation:
66+
ephemeral_1h_input_tokens: 0
67+
ephemeral_5m_input_tokens: 0
6568
cache_creation_input_tokens: 0
6669
cache_read_input_tokens: 0
6770
input_tokens: 41
68-
output_tokens: 82
71+
output_tokens: 88
6972
service_tier: standard
7073
status:
7174
code: 200

tests/models/cassettes/test_anthropic/test_anthropic_model_instructions.yaml

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ interactions:
1515
- api.anthropic.com
1616
method: POST
1717
parsed_body:
18-
max_tokens: 1024
18+
max_tokens: 4096
1919
messages:
2020
- content:
2121
- text: What is the capital of France?
@@ -32,7 +32,7 @@ interactions:
3232
connection:
3333
- keep-alive
3434
content-length:
35-
- '354'
35+
- '433'
3636
content-type:
3737
- application/json
3838
strict-transport-security:
@@ -43,13 +43,16 @@ interactions:
4343
content:
4444
- text: The capital of France is Paris.
4545
type: text
46-
id: msg_01BznVNBje2zyfpCfNQCD5en
46+
id: msg_01Fg1JVgvCYUHWsxrj9GkpEv
4747
model: claude-3-opus-20240229
4848
role: assistant
4949
stop_reason: end_turn
5050
stop_sequence: null
5151
type: message
5252
usage:
53+
cache_creation:
54+
ephemeral_1h_input_tokens: 0
55+
ephemeral_5m_input_tokens: 0
5356
cache_creation_input_tokens: 0
5457
cache_read_input_tokens: 0
5558
input_tokens: 20

0 commit comments

Comments
 (0)