Skip to content

Commit 68d8226

Browse files
feat(api): add claude 4 models, files API, code execution tool, MCP connector and more
1 parent c79b65b commit 68d8226

File tree

73 files changed

+2475
-49
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+2475
-49
lines changed

.stats.yml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
configured_endpoints: 21
2-
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-087f1149681ef9bc1074184df28ed4b4b9cc37b86cba50eb18e6c18452864446.yml
3-
openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d
4-
config_hash: 7b88da171a1b1bdb963ec2311e417cbe
1+
configured_endpoints: 26
2+
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-1fdf23e8226430012c21819427e8d1ed16c08c0fb2d4abf69b8e318a42e99552.yml
3+
openapi_spec_hash: 836bbb4ab7c33c37456d1842876d7aba
4+
config_hash: 7b17fe2f10f5942177ff51b0a13506fa

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,23 @@ message = client.messages.create(
398398
print(message.metadata)
399399
```
400400

401+
## File uploads
402+
403+
Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.
404+
405+
```python
406+
from pathlib import Path
407+
from anthropic import Anthropic
408+
409+
client = Anthropic()
410+
411+
client.beta.files.upload(
412+
file=Path("/path/to/file"),
413+
)
414+
```
415+
416+
The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.
417+
401418
## Handling errors
402419

403420
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `anthropic.APIConnectionError` is raised.

api.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ from anthropic.types.beta import (
200200
BetaBase64PDFBlock,
201201
BetaBase64PDFSource,
202202
BetaCacheControlEphemeral,
203+
BetaCacheCreation,
203204
BetaCitationCharLocation,
204205
BetaCitationCharLocationParam,
205206
BetaCitationContentBlockLocation,
@@ -210,12 +211,32 @@ from anthropic.types.beta import (
210211
BetaCitationsConfigParam,
211212
BetaCitationsDelta,
212213
BetaCitationsWebSearchResultLocation,
214+
BetaCodeExecutionOutputBlock,
215+
BetaCodeExecutionOutputBlockParam,
216+
BetaCodeExecutionResultBlock,
217+
BetaCodeExecutionResultBlockParam,
218+
BetaCodeExecutionTool20250522,
219+
BetaCodeExecutionToolResultBlock,
220+
BetaCodeExecutionToolResultBlockContent,
221+
BetaCodeExecutionToolResultBlockParam,
222+
BetaCodeExecutionToolResultBlockParamContent,
223+
BetaCodeExecutionToolResultError,
224+
BetaCodeExecutionToolResultErrorCode,
225+
BetaCodeExecutionToolResultErrorParam,
226+
BetaContainer,
227+
BetaContainerUploadBlock,
228+
BetaContainerUploadBlockParam,
213229
BetaContentBlock,
214230
BetaContentBlockParam,
215231
BetaContentBlockSource,
216232
BetaContentBlockSourceContent,
233+
BetaFileDocumentSource,
234+
BetaFileImageSource,
217235
BetaImageBlockParam,
218236
BetaInputJSONDelta,
237+
BetaMCPToolResultBlock,
238+
BetaMCPToolUseBlock,
239+
BetaMCPToolUseBlockParam,
219240
BetaMessage,
220241
BetaMessageDeltaUsage,
221242
BetaMessageParam,
@@ -232,6 +253,9 @@ from anthropic.types.beta import (
232253
BetaRawMessageStreamEvent,
233254
BetaRedactedThinkingBlock,
234255
BetaRedactedThinkingBlockParam,
256+
BetaRequestMCPServerToolConfiguration,
257+
BetaRequestMCPServerURLDefinition,
258+
BetaRequestMCPToolResultBlockParam,
235259
BetaServerToolUsage,
236260
BetaServerToolUseBlock,
237261
BetaServerToolUseBlockParam,
@@ -261,6 +285,7 @@ from anthropic.types.beta import (
261285
BetaToolResultBlockParam,
262286
BetaToolTextEditor20241022,
263287
BetaToolTextEditor20250124,
288+
BetaToolTextEditor20250429,
264289
BetaToolUnion,
265290
BetaToolUseBlock,
266291
BetaToolUseBlockParam,
@@ -276,6 +301,7 @@ from anthropic.types.beta import (
276301
BetaWebSearchToolResultBlockParam,
277302
BetaWebSearchToolResultBlockParamContent,
278303
BetaWebSearchToolResultError,
304+
BetaWebSearchToolResultErrorCode,
279305
)
280306
```
281307

@@ -310,3 +336,19 @@ Methods:
310336
- <code title="delete /v1/messages/batches/{message_batch_id}?beta=true">client.beta.messages.batches.<a href="./src/anthropic/resources/beta/messages/batches.py">delete</a>(message_batch_id) -> <a href="./src/anthropic/types/beta/messages/beta_deleted_message_batch.py">BetaDeletedMessageBatch</a></code>
311337
- <code title="post /v1/messages/batches/{message_batch_id}/cancel?beta=true">client.beta.messages.batches.<a href="./src/anthropic/resources/beta/messages/batches.py">cancel</a>(message_batch_id) -> <a href="./src/anthropic/types/beta/messages/beta_message_batch.py">BetaMessageBatch</a></code>
312338
- <code title="get /v1/messages/batches/{message_batch_id}/results?beta=true">client.beta.messages.batches.<a href="./src/anthropic/resources/beta/messages/batches.py">results</a>(message_batch_id) -> <a href="./src/anthropic/types/beta/messages/beta_message_batch_individual_response.py">JSONLDecoder[BetaMessageBatchIndividualResponse]</a></code>
339+
340+
## Files
341+
342+
Types:
343+
344+
```python
345+
from anthropic.types.beta import DeletedFile, FileMetadata
346+
```
347+
348+
Methods:
349+
350+
- <code title="get /v1/files?beta=true">client.beta.files.<a href="./src/anthropic/resources/beta/files.py">list</a>(\*\*<a href="src/anthropic/types/beta/file_list_params.py">params</a>) -> <a href="./src/anthropic/types/beta/file_metadata.py">SyncPage[FileMetadata]</a></code>
351+
- <code title="delete /v1/files/{file_id}?beta=true">client.beta.files.<a href="./src/anthropic/resources/beta/files.py">delete</a>(file_id) -> <a href="./src/anthropic/types/beta/deleted_file.py">DeletedFile</a></code>
352+
- <code title="get /v1/files/{file_id}/content?beta=true">client.beta.files.<a href="./src/anthropic/resources/beta/files.py">download</a>(file_id) -> BinaryAPIResponse</code>
353+
- <code title="get /v1/files/{file_id}?beta=true">client.beta.files.<a href="./src/anthropic/resources/beta/files.py">retrieve_metadata</a>(file_id) -> <a href="./src/anthropic/types/beta/file_metadata.py">FileMetadata</a></code>
354+
- <code title="post /v1/files?beta=true">client.beta.files.<a href="./src/anthropic/resources/beta/files.py">upload</a>(\*\*<a href="src/anthropic/types/beta/file_upload_params.py">params</a>) -> <a href="./src/anthropic/types/beta/file_metadata.py">FileMetadata</a></code>

examples/mcp.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env -S rye run python
2+
3+
from anthropic import Anthropic
4+
5+
anthropic = Anthropic()
6+
7+
response = anthropic.beta.messages.create(
8+
model="claude-3-7-sonnet-20250219",
9+
max_tokens=1000,
10+
messages=[
11+
{
12+
"role": "user",
13+
"content": 'Calculate 1+2',
14+
},
15+
],
16+
mcp_servers=[
17+
{
18+
"type": "url",
19+
"url": "http://example-server.modelcontextprotocol.io/sse",
20+
"name": "example",
21+
"tool_configuration": { # Optional, by default all tools are enabled
22+
"enabled": True,
23+
"allowed_tools": ['echo', 'add'], # Optional
24+
},
25+
}
26+
],
27+
extra_headers={
28+
"anthropic-beta": "mcp-client-2025-04-04",
29+
},
30+
)
31+
print(response.content)

examples/messages_stream.py

100644100755
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#!/usr/bin/env -S rye run python
2+
13
import asyncio
24

35
from anthropic import AsyncAnthropic

src/anthropic/_base_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -689,12 +689,12 @@ def platform_headers(self) -> Dict[str, str]:
689689
# https://github.com/python/cpython/issues/88476
690690
return platform_headers(self._version, platform=self._platform)
691691

692-
def _calculate_nonstreaming_timeout(self, max_tokens: int) -> Timeout:
692+
def _calculate_nonstreaming_timeout(self, max_tokens: int, max_nonstreaming_tokens: int | None) -> Timeout:
693693
maximum_time = 60 * 60
694694
default_time = 60 * 10
695695

696696
expected_time = maximum_time * max_tokens / 128_000
697-
if expected_time > default_time:
697+
if expected_time > default_time or (max_nonstreaming_tokens and max_tokens > max_nonstreaming_tokens):
698698
raise ValueError(
699699
"Streaming is strongly recommended for operations that may take longer than 10 minutes. "
700700
+ "See https://github.com/anthropics/anthropic-sdk-python#long-requests for more details",

src/anthropic/_constants.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,11 @@
1616
HUMAN_PROMPT = "\n\nHuman:"
1717

1818
AI_PROMPT = "\n\nAssistant:"
19+
20+
MODEL_NONSTREAMING_TOKENS = {
21+
"claude-opus-4-20250514": 8_192,
22+
"claude-opus-4-0": 8_192,
23+
"claude-4-opus-20250514": 8_192,
24+
"anthropic.claude-opus-4-20250514-v1:0": 8_192,
25+
"claude-opus-4@20250514": 8_192,
26+
}

src/anthropic/_files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
3434
if not is_file_content(obj):
3535
prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
3636
raise RuntimeError(
37-
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead."
37+
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/anthropics/anthropic-sdk-python/tree/main#file-uploads"
3838
) from None
3939

4040

src/anthropic/lib/streaming/_beta_messages.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def build_events(
329329
)
330330
)
331331
elif event.delta.type == "input_json_delta":
332-
if content_block.type == "tool_use":
332+
if content_block.type == "tool_use" or content_block.type == "mcp_tool_use":
333333
events_to_fire.append(
334334
build(
335335
BetaInputJsonEvent,
@@ -425,7 +425,7 @@ def accumulate_event(
425425
if content.type == "text":
426426
content.text += event.delta.text
427427
elif event.delta.type == "input_json_delta":
428-
if content.type == "tool_use":
428+
if content.type == "tool_use" or content.type == "mcp_tool_use":
429429
from jiter import from_json
430430

431431
# we need to keep track of the raw JSON string as well so that we can
@@ -455,6 +455,7 @@ def accumulate_event(
455455
if TYPE_CHECKING: # type: ignore[unreachable]
456456
assert_never(event.delta)
457457
elif event.type == "message_delta":
458+
current_snapshot.container = event.delta.container
458459
current_snapshot.stop_reason = event.delta.stop_reason
459460
current_snapshot.stop_sequence = event.delta.stop_sequence
460461
current_snapshot.usage.output_tokens = event.usage.output_tokens

src/anthropic/lib/vertex/_auth.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ def load_auth(*, project_id: str | None) -> tuple[Credentials, str]:
1919
try:
2020
from google.auth.transport.requests import Request # type: ignore[import-untyped]
2121
except ModuleNotFoundError as err:
22-
raise RuntimeError(f'Could not import google.auth, you need to install the SDK with `pip install anthropic[vertex]`') from err
22+
raise RuntimeError(
23+
f"Could not import google.auth, you need to install the SDK with `pip install anthropic[vertex]`"
24+
) from err
2325

2426
credentials, loaded_project_id = google_auth.default(
2527
scopes=["https://www.googleapis.com/auth/cloud-platform"],

0 commit comments

Comments
 (0)