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
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.72.0"
".": "0.72.1"
}
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# Changelog

## 0.72.1 (2025-11-11)

Full Changelog: [v0.72.0...v0.72.1](https://github.com/anthropics/anthropic-sdk-python/compare/v0.72.0...v0.72.1)

### Bug Fixes

* **client:** close streams without requiring full consumption ([109b771](https://github.com/anthropics/anthropic-sdk-python/commit/109b77175c844c37e6e57899a732a0ba293a2942))
* compat with Python 3.14 ([bd2a137](https://github.com/anthropics/anthropic-sdk-python/commit/bd2a137a46cd899e28e81dd8d445dad23440674c))
* **compat:** update signatures of `model_dump` and `model_dump_json` for Pydantic v1 ([540f0f8](https://github.com/anthropics/anthropic-sdk-python/commit/540f0f8fdb0aa5d0d104259a59a0ee359296953e))


### Chores

* **internal/tests:** avoid race condition with implicit client cleanup ([72767ce](https://github.com/anthropics/anthropic-sdk-python/commit/72767cebc31a9d5608f08533888a1cf69862a598))
* **internal:** grammar fix (it's -> its) ([9efe993](https://github.com/anthropics/anthropic-sdk-python/commit/9efe99371577c3ff51050aeab5d480a442577b46))
* **package:** drop Python 3.8 support ([e9af5d3](https://github.com/anthropics/anthropic-sdk-python/commit/e9af5d3676a0a77881a18bc9b4e8a30ecf46b017))

## 0.72.0 (2025-10-28)

Full Changelog: [v0.71.1...v0.72.0](https://github.com/anthropics/anthropic-sdk-python/compare/v0.71.1...v0.72.0)
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<!-- prettier-ignore -->
[![PyPI version](https://img.shields.io/pypi/v/anthropic.svg?label=pypi%20(stable))](https://pypi.org/project/anthropic/)

The Anthropic Python library provides convenient access to the Anthropic REST API from any Python 3.8+
The Anthropic Python library provides convenient access to the Anthropic REST API from any Python 3.9+
application. It includes type definitions for all request params and response fields,
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).

Expand Down Expand Up @@ -867,7 +867,7 @@ print(anthropic.__version__)

## Requirements

Python 3.8 or higher.
Python 3.9 or higher.

## Contributing

Expand Down
7 changes: 3 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "anthropic"
version = "0.72.0"
version = "0.72.1"
description = "The official Python library for the anthropic API"
dynamic = ["readme"]
license = "MIT"
Expand All @@ -17,11 +17,10 @@ dependencies = [
"jiter>=0.4.0, <1",
"docstring-parser>=0.15,<1",
]
requires-python = ">= 3.8"
requires-python = ">= 3.9"
classifiers = [
"Typing :: Typed",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down Expand Up @@ -136,7 +135,7 @@ format-command="ruff format --stdin-filename {filename}"
# there are a couple of flags that are still disabled by
# default in strict mode as they are experimental and niche.
typeCheckingMode = "strict"
pythonVersion = "3.8"
pythonVersion = "3.9"

exclude = [
".git",
Expand Down
65 changes: 15 additions & 50 deletions requirements-dev.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,14 @@
-e .
annotated-types==0.7.0
# via pydantic
anyio==4.5.2 ; python_full_version < '3.9'
# via
# anthropic
# httpx
anyio==4.8.0 ; python_full_version >= '3.9'
anyio==4.8.0
# via
# anthropic
# httpx
asttokens==3.0.0
# via inline-snapshot
astunparse==1.6.3 ; python_full_version < '3.9'
# via griffe
boto3-stubs==1.40.54
botocore-stubs==1.38.30 ; python_full_version < '3.9'
# via boto3-stubs
botocore-stubs==1.40.54 ; python_full_version >= '3.9'
boto3-stubs==1.40.69
botocore-stubs==1.40.69
# via boto3-stubs
certifi==2024.12.14
# via
Expand All @@ -41,8 +33,7 @@ execnet==2.1.1
# via pytest-xdist
executing==2.2.1
# via inline-snapshot
griffe==1.4.0 ; python_full_version < '3.9'
griffe==1.13.0 ; python_full_version >= '3.9'
griffe==1.13.0
h11==0.16.0
# via httpcore
httpcore==1.0.9
Expand All @@ -55,14 +46,11 @@ idna==3.10
# via
# anyio
# httpx
importlib-metadata==8.5.0 ; python_full_version < '3.9'
importlib-metadata==8.6.1 ; python_full_version >= '3.9'
importlib-metadata==8.6.1
iniconfig==2.0.0
# via pytest
inline-snapshot==0.30.0
jiter==0.9.1 ; python_full_version < '3.9'
# via anthropic
jiter==0.11.0 ; python_full_version >= '3.9'
inline-snapshot==0.31.1
jiter==0.12.0
# via anthropic
markdown-it-py==3.0.0
# via rich
Expand All @@ -77,62 +65,46 @@ packaging==24.2
# via pytest
pluggy==1.5.0
# via pytest
pydantic==2.10.6 ; python_full_version < '3.9'
# via anthropic
pydantic==2.11.9 ; python_full_version >= '3.9'
pydantic==2.10.3
# via anthropic
pydantic-core==2.27.2 ; python_full_version < '3.9'
# via pydantic
pydantic-core==2.33.2 ; python_full_version >= '3.9'
pydantic-core==2.27.1
# via pydantic
pygments==2.19.1
# via
# pytest
# rich
pyright==1.1.399
pytest==8.3.5 ; python_full_version < '3.9'
# via
# inline-snapshot
# pytest-asyncio
# pytest-xdist
pytest==8.4.1 ; python_full_version >= '3.9'
pytest==8.4.1
# via
# inline-snapshot
# pytest-asyncio
# pytest-xdist
pytest-asyncio==0.24.0
pytest-xdist==3.6.1 ; python_full_version < '3.9'
pytest-xdist==3.7.0 ; python_full_version >= '3.9'
pytest-xdist==3.7.0
python-dateutil==2.9.0.post0
# via time-machine
pytz==2024.2 ; python_full_version < '3.9'
# via dirty-equals
respx==0.22.0
rich==13.9.4
# via inline-snapshot
ruff==0.9.4
six==1.17.0
# via
# astunparse
# python-dateutil
# via python-dateutil
sniffio==1.3.1
# via
# anthropic
# anyio
time-machine==2.15.0 ; python_full_version < '3.9'
time-machine==2.16.0 ; python_full_version >= '3.9'
time-machine==2.16.0
tomli==2.2.1 ; python_full_version < '3.11'
# via
# inline-snapshot
# mypy
# pytest
types-awscrt==0.28.1
types-awscrt==0.28.2
# via botocore-stubs
types-s3transfer==0.14.0
# via boto3-stubs
typing-extensions==4.12.2
# via
# annotated-types
# anthropic
# anyio
# boto3-stubs
Expand All @@ -141,12 +113,5 @@ typing-extensions==4.12.2
# pydantic-core
# pyright
# rich
# typing-inspection
typing-inspection==0.4.1 ; python_full_version >= '3.9'
# via pydantic
wheel==0.45.1 ; python_full_version < '3.9'
# via astunparse
zipp==3.20.2 ; python_full_version < '3.9'
# via importlib-metadata
zipp==3.21.0 ; python_full_version >= '3.9'
zipp==3.21.0
# via importlib-metadata
4 changes: 2 additions & 2 deletions scripts/test
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ if [[ -n "$UV_PYTHON" ]]; then
else
# If UV_PYTHON is not set, run the command for min and max versions

echo "==> Running tests for Python 3.8"
UV_PYTHON=3.8 run_tests "$@"
echo "==> Running tests for Python 3.9"
UV_PYTHON=3.9 run_tests "$@"

echo "==> Running tests for Python 3.13"
UV_PYTHON=3.13 run_tests "$@"
Expand Down
52 changes: 37 additions & 15 deletions src/anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import inspect
import weakref
from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
from datetime import date, datetime
from typing_extensions import (
Expand Down Expand Up @@ -272,32 +273,41 @@ def model_dump(
mode: Literal["json", "python"] | str = "python",
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
context: dict[str, Any] | None = None,
serialize_as_any: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> dict[str, Any]:
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Args:
mode: The mode in which `to_python` should run.
If mode is 'json', the dictionary will only contain JSON serializable types.
If mode is 'python', the dictionary may contain any Python objects.
include: A list of fields to include in the output.
exclude: A list of fields to exclude from the output.
If mode is 'json', the output will only contain JSON serializable types.
If mode is 'python', the output may contain non-JSON-serializable Python objects.
include: A set of fields to include in the output.
exclude: A set of fields to exclude from the output.
context: Additional context to pass to the serializer.
by_alias: Whether to use the field's alias in the dictionary key if defined.
exclude_unset: Whether to exclude fields that are unset or None from the output.
exclude_defaults: Whether to exclude fields that are set to their default value from the output.
exclude_none: Whether to exclude fields that have a value of `None` from the output.
round_trip: Whether to enable serialization and deserialization round-trip support.
warnings: Whether to log warnings when invalid fields are encountered.
exclude_unset: Whether to exclude fields that have not been explicitly set.
exclude_defaults: Whether to exclude fields that are set to their default value.
exclude_none: Whether to exclude fields that have a value of `None`.
exclude_computed_fields: Whether to exclude computed fields.
While this can be useful for round-tripping, it is usually recommended to use the dedicated
`round_trip` parameter instead.
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
fallback: A function to call when an unknown value is encountered. If not provided,
a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

Returns:
A dictionary representation of the model.
Expand All @@ -314,6 +324,8 @@ def model_dump(
raise ValueError("serialize_as_any is only supported in Pydantic v2")
if fallback is not None:
raise ValueError("fallback is only supported in Pydantic v2")
if exclude_computed_fields != False:
raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
dumped = super().dict( # pyright: ignore[reportDeprecated]
include=include,
exclude=exclude,
Expand All @@ -330,15 +342,17 @@ def model_dump_json(
self,
*,
indent: int | None = None,
ensure_ascii: bool = False,
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
context: dict[str, Any] | None = None,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> str:
Expand Down Expand Up @@ -370,6 +384,10 @@ def model_dump_json(
raise ValueError("serialize_as_any is only supported in Pydantic v2")
if fallback is not None:
raise ValueError("fallback is only supported in Pydantic v2")
if ensure_ascii != False:
raise ValueError("ensure_ascii is only supported in Pydantic v2")
if exclude_computed_fields != False:
raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
return super().json( # type: ignore[reportDeprecated]
indent=indent,
include=include,
Expand Down Expand Up @@ -589,6 +607,9 @@ class CachedDiscriminatorType(Protocol):
__discriminator__: DiscriminatorDetails


DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary()


class DiscriminatorDetails:
field_name: str
"""The name of the discriminator field in the variant class, e.g.
Expand Down Expand Up @@ -631,8 +652,9 @@ def __init__(


def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
if isinstance(union, CachedDiscriminatorType):
return union.__discriminator__
cached = DISCRIMINATOR_CACHE.get(union)
if cached is not None:
return cached

discriminator_field_name: str | None = None

Expand Down Expand Up @@ -685,7 +707,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
discriminator_field=discriminator_field_name,
discriminator_alias=discriminator_alias,
)
cast(CachedDiscriminatorType, union).__discriminator__ = details
DISCRIMINATOR_CACHE.setdefault(union, details)
return details


Expand Down
10 changes: 4 additions & 6 deletions src/anthropic/_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,8 @@ def __stream__(self) -> Iterator[_T]:
response=self.response,
)

# Ensure the entire stream is consumed
for _sse in iterator:
...
# As we might not fully consume the response stream, we need to close it explicitly
response.close()

def __enter__(self) -> Self:
return self
Expand Down Expand Up @@ -231,9 +230,8 @@ async def __stream__(self) -> AsyncIterator[_T]:
response=self.response,
)

# Ensure the entire stream is consumed
async for _sse in iterator:
...
# As we might not fully consume the response stream, we need to close it explicitly
await response.aclose()

async def __aenter__(self) -> Self:
return self
Expand Down
Loading