Skip to content
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

release: 0.7.3 #244

Merged
merged 4 commits into from
Nov 21, 2023
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.7.2"
".": "0.7.3"
}
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## 0.7.3 (2023-11-21)

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

### Bug Fixes

* **client:** attempt to parse unknown json content types ([#243](https://github.com/anthropics/anthropic-sdk-python/issues/243)) ([9fc275f](https://github.com/anthropics/anthropic-sdk-python/commit/9fc275f606b52690d5ccda78c72a6fded68ccb1e))


### Chores

* **client:** improve copy method ([#246](https://github.com/anthropics/anthropic-sdk-python/issues/246)) ([c84563f](https://github.com/anthropics/anthropic-sdk-python/commit/c84563fc69554b322d2a4254b6470ba7819689c3))
* **package:** add license classifier metadata ([#247](https://github.com/anthropics/anthropic-sdk-python/issues/247)) ([500d0ca](https://github.com/anthropics/anthropic-sdk-python/commit/500d0ca1e4d08f8c6b5d58071f438de9e1a31217))

## 0.7.2 (2023-11-17)

Full Changelog: [v0.7.1...v0.7.2](https://github.com/anthropics/anthropic-sdk-python/compare/v0.7.1...v0.7.2)
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "anthropic"
version = "0.7.2"
version = "0.7.3"
description = "The official Python library for the anthropic API"
readme = "README.md"
license = "MIT"
Expand Down Expand Up @@ -31,6 +31,7 @@ classifiers = [
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: MIT License"
]


Expand Down
20 changes: 14 additions & 6 deletions src/anthropic/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,12 @@
RAW_RESPONSE_HEADER,
)
from ._streaming import Stream, AsyncStream
from ._exceptions import APIStatusError, APITimeoutError, APIConnectionError
from ._exceptions import (
APIStatusError,
APITimeoutError,
APIConnectionError,
APIResponseValidationError,
)

log: logging.Logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -518,13 +523,16 @@ def _process_response_data(
if cast_to is UnknownResponse:
return cast(ResponseT, data)

if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol):
return cast(ResponseT, cast_to.build(response=response, data=data))
try:
if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol):
return cast(ResponseT, cast_to.build(response=response, data=data))

if self._strict_response_validation:
return cast(ResponseT, validate_type(type_=cast_to, value=data))
if self._strict_response_validation:
return cast(ResponseT, validate_type(type_=cast_to, value=data))

return cast(ResponseT, construct_type(type_=cast_to, value=data))
return cast(ResponseT, construct_type(type_=cast_to, value=data))
except pydantic.ValidationError as err:
raise APIResponseValidationError(response=response, body=data) from err

@property
def qs(self) -> Querystring:
Expand Down
18 changes: 8 additions & 10 deletions src/anthropic/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

import os
import asyncio
from typing import Union, Mapping
from typing_extensions import override
from typing import Any, Union, Mapping
from typing_extensions import Self, override

import httpx
from tokenizers import Tokenizer # type: ignore[import]
Expand Down Expand Up @@ -194,12 +194,10 @@ def copy(
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
set_default_query: Mapping[str, object] | None = None,
) -> Anthropic:
_extra_kwargs: Mapping[str, Any] = {},
) -> Self:
"""
Create a new client instance re-using the same options given to the current client with optional overriding.

It should be noted that this does not share the underlying httpx client class which may lead
to performance issues.
"""
if default_headers is not None and set_default_headers is not None:
raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
Expand Down Expand Up @@ -247,6 +245,7 @@ def copy(
max_retries=max_retries if is_given(max_retries) else self.max_retries,
default_headers=headers,
default_query=params,
**_extra_kwargs,
)

# Alias for `copy` for nicer inline usage, e.g.
Expand Down Expand Up @@ -455,12 +454,10 @@ def copy(
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
set_default_query: Mapping[str, object] | None = None,
) -> AsyncAnthropic:
_extra_kwargs: Mapping[str, Any] = {},
) -> Self:
"""
Create a new client instance re-using the same options given to the current client with optional overriding.

It should be noted that this does not share the underlying httpx client class which may lead
to performance issues.
"""
if default_headers is not None and set_default_headers is not None:
raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
Expand Down Expand Up @@ -508,6 +505,7 @@ def copy(
max_retries=max_retries if is_given(max_retries) else self.max_retries,
default_headers=headers,
default_query=params,
**_extra_kwargs,
)

# Alias for `copy` for nicer inline usage, e.g.
Expand Down
13 changes: 13 additions & 0 deletions src/anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,19 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
return construct_type(value=value, type_=type_)


def is_basemodel(type_: type) -> bool:
"""Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
origin = get_origin(type_) or type_
if is_union(type_):
for variant in get_args(type_):
if is_basemodel(variant):
return True

return False

return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)


def construct_type(*, value: object, type_: type) -> object:
"""Loose coercion to the expected type with construction of nested values.

Expand Down
31 changes: 21 additions & 10 deletions src/anthropic/_response.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
from __future__ import annotations

import inspect
import logging
import datetime
import functools
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast
from typing_extensions import Awaitable, ParamSpec, get_args, override, get_origin

import httpx
import pydantic

from ._types import NoneType, UnknownResponse, BinaryResponseContent
from ._utils import is_given
from ._models import BaseModel
from ._models import BaseModel, is_basemodel
from ._constants import RAW_RESPONSE_HEADER
from ._exceptions import APIResponseValidationError

Expand All @@ -23,6 +23,8 @@
P = ParamSpec("P")
R = TypeVar("R")

log: logging.Logger = logging.getLogger(__name__)


class APIResponse(Generic[R]):
_cast_to: type[R]
Expand Down Expand Up @@ -174,6 +176,18 @@ def _parse(self) -> R:
# in the response, e.g. application/json; charset=utf-8
content_type, *_ = response.headers.get("content-type").split(";")
if content_type != "application/json":
if is_basemodel(cast_to):
try:
data = response.json()
except Exception as exc:
log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
else:
return self._client._process_response_data(
data=data,
cast_to=cast_to, # type: ignore
response=response,
)

if self._client._strict_response_validation:
raise APIResponseValidationError(
response=response,
Expand All @@ -188,14 +202,11 @@ def _parse(self) -> R:

data = response.json()

try:
return self._client._process_response_data(
data=data,
cast_to=cast_to, # type: ignore
response=response,
)
except pydantic.ValidationError as err:
raise APIResponseValidationError(response=response, body=data) from err
return self._client._process_response_data(
data=data,
cast_to=cast_to, # type: ignore
response=response,
)

@override
def __repr__(self) -> str:
Expand Down
2 changes: 1 addition & 1 deletion src/anthropic/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless.

__title__ = "anthropic"
__version__ = "0.7.2" # x-release-please-version
__version__ = "0.7.3" # x-release-please-version
42 changes: 42 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,27 @@ class Model2(BaseModel):
assert isinstance(response, Model1)
assert response.foo == 1

@pytest.mark.respx(base_url=base_url)
def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None:
"""
Response that sets Content-Type to something other than application/json but returns json data
"""

class Model(BaseModel):
foo: int

respx_mock.get("/foo").mock(
return_value=httpx.Response(
200,
content=json.dumps({"foo": 2}),
headers={"Content-Type": "application/text"},
)
)

response = self.client.get("/foo", cast_to=Model)
assert isinstance(response, Model)
assert response.foo == 2

def test_base_url_env(self) -> None:
with update_env(ANTHROPIC_BASE_URL="http://localhost:5000/from/env"):
client = Anthropic(api_key=api_key, _strict_response_validation=True)
Expand Down Expand Up @@ -1043,6 +1064,27 @@ class Model2(BaseModel):
assert isinstance(response, Model1)
assert response.foo == 1

@pytest.mark.respx(base_url=base_url)
async def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None:
"""
Response that sets Content-Type to something other than application/json but returns json data
"""

class Model(BaseModel):
foo: int

respx_mock.get("/foo").mock(
return_value=httpx.Response(
200,
content=json.dumps({"foo": 2}),
headers={"Content-Type": "application/text"},
)
)

response = await self.client.get("/foo", cast_to=Model)
assert isinstance(response, Model)
assert response.foo == 2

def test_base_url_env(self) -> None:
with update_env(ANTHROPIC_BASE_URL="http://localhost:5000/from/env"):
client = AsyncAnthropic(api_key=api_key, _strict_response_validation=True)
Expand Down