| 1 |
import json |
| 2 |
from typing import Any, List, Union, cast |
| 3 |
from typing_extensions import Annotated |
| 4 |
|
| 5 |
import httpx2 |
| 6 |
import pytest |
| 7 |
import pydantic |
| 8 |
|
| 9 |
from anthropic import Anthropic, BaseModel, AsyncAnthropic |
| 10 |
from anthropic._response import ( |
| 11 |
APIResponse, |
| 12 |
BaseAPIResponse, |
| 13 |
AsyncAPIResponse, |
| 14 |
BinaryAPIResponse, |
| 15 |
AsyncBinaryAPIResponse, |
| 16 |
extract_response_type, |
| 17 |
) |
| 18 |
from anthropic._streaming import Stream |
| 19 |
from anthropic._base_client import FinalRequestOptions |
| 20 |
|
| 21 |
|
| 22 |
class ConcreteBaseAPIResponse(APIResponse[bytes]): ... |
| 23 |
|
| 24 |
|
| 25 |
class ConcreteAPIResponse(APIResponse[List[str]]): ... |
| 26 |
|
| 27 |
|
| 28 |
class ConcreteAsyncAPIResponse(APIResponse[httpx2.Response]): ... |
| 29 |
|
| 30 |
|
| 31 |
def test_extract_response_type_direct_classes() -> None: |
| 32 |
assert extract_response_type(BaseAPIResponse[str]) == str |
| 33 |
assert extract_response_type(APIResponse[str]) == str |
| 34 |
assert extract_response_type(AsyncAPIResponse[str]) == str |
| 35 |
|
| 36 |
|
| 37 |
def test_extract_response_type_direct_class_missing_type_arg() -> None: |
| 38 |
with pytest.raises( |
| 39 |
RuntimeError, |
| 40 |
match="Expected type <class 'anthropic._response.AsyncAPIResponse'> to have a type argument at index 0 but it did not", |
| 41 |
): |
| 42 |
extract_response_type(AsyncAPIResponse) |
| 43 |
|
| 44 |
|
| 45 |
def test_extract_response_type_concrete_subclasses() -> None: |
| 46 |
assert extract_response_type(ConcreteBaseAPIResponse) == bytes |
| 47 |
assert extract_response_type(ConcreteAPIResponse) == List[str] |
| 48 |
assert extract_response_type(ConcreteAsyncAPIResponse) == httpx2.Response |
| 49 |
|
| 50 |
|
| 51 |
def test_extract_response_type_binary_response() -> None: |
| 52 |
assert extract_response_type(BinaryAPIResponse) == bytes |
| 53 |
assert extract_response_type(AsyncBinaryAPIResponse) == bytes |
| 54 |
|
| 55 |
|
| 56 |
class PydanticModel(pydantic.BaseModel): ... |
| 57 |
|
| 58 |
|
| 59 |
def test_response_parse_mismatched_basemodel(client: Anthropic) -> None: |
| 60 |
response = APIResponse( |
| 61 |
raw=httpx2.Response(200, content=b"foo"), |
| 62 |
client=client, |
| 63 |
stream=False, |
| 64 |
stream_cls=None, |
| 65 |
cast_to=str, |
| 66 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 67 |
) |
| 68 |
|
| 69 |
with pytest.raises( |
| 70 |
TypeError, |
| 71 |
match="Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`", |
| 72 |
): |
| 73 |
response.parse(to=PydanticModel) |
| 74 |
|
| 75 |
|
| 76 |
@pytest.mark.asyncio |
| 77 |
async def test_async_response_parse_mismatched_basemodel(async_client: AsyncAnthropic) -> None: |
| 78 |
response = AsyncAPIResponse( |
| 79 |
raw=httpx2.Response(200, content=b"foo"), |
| 80 |
client=async_client, |
| 81 |
stream=False, |
| 82 |
stream_cls=None, |
| 83 |
cast_to=str, |
| 84 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 85 |
) |
| 86 |
|
| 87 |
with pytest.raises( |
| 88 |
TypeError, |
| 89 |
match="Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`", |
| 90 |
): |
| 91 |
await response.parse(to=PydanticModel) |
| 92 |
|
| 93 |
|
| 94 |
def test_response_parse_custom_stream(client: Anthropic) -> None: |
| 95 |
response = APIResponse( |
| 96 |
raw=httpx2.Response(200, content=b"foo"), |
| 97 |
client=client, |
| 98 |
stream=True, |
| 99 |
stream_cls=None, |
| 100 |
cast_to=str, |
| 101 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 102 |
) |
| 103 |
|
| 104 |
stream = response.parse(to=Stream[int]) |
| 105 |
assert stream._cast_to == int |
| 106 |
|
| 107 |
|
| 108 |
@pytest.mark.asyncio |
| 109 |
async def test_async_response_parse_custom_stream(async_client: AsyncAnthropic) -> None: |
| 110 |
response = AsyncAPIResponse( |
| 111 |
raw=httpx2.Response(200, content=b"foo"), |
| 112 |
client=async_client, |
| 113 |
stream=True, |
| 114 |
stream_cls=None, |
| 115 |
cast_to=str, |
| 116 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 117 |
) |
| 118 |
|
| 119 |
stream = await response.parse(to=Stream[int]) |
| 120 |
assert stream._cast_to == int |
| 121 |
|
| 122 |
|
| 123 |
class CustomModel(BaseModel): |
| 124 |
foo: str |
| 125 |
bar: int |
| 126 |
|
| 127 |
|
| 128 |
def test_response_parse_custom_model(client: Anthropic) -> None: |
| 129 |
response = APIResponse( |
| 130 |
raw=httpx2.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 131 |
client=client, |
| 132 |
stream=False, |
| 133 |
stream_cls=None, |
| 134 |
cast_to=str, |
| 135 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 136 |
) |
| 137 |
|
| 138 |
obj = response.parse(to=CustomModel) |
| 139 |
assert obj.foo == "hello!" |
| 140 |
assert obj.bar == 2 |
| 141 |
|
| 142 |
|
| 143 |
@pytest.mark.asyncio |
| 144 |
async def test_async_response_parse_custom_model(async_client: AsyncAnthropic) -> None: |
| 145 |
response = AsyncAPIResponse( |
| 146 |
raw=httpx2.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 147 |
client=async_client, |
| 148 |
stream=False, |
| 149 |
stream_cls=None, |
| 150 |
cast_to=str, |
| 151 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 152 |
) |
| 153 |
|
| 154 |
obj = await response.parse(to=CustomModel) |
| 155 |
assert obj.foo == "hello!" |
| 156 |
assert obj.bar == 2 |
| 157 |
|
| 158 |
|
| 159 |
def test_response_basemodel_request_id(client: Anthropic) -> None: |
| 160 |
response = APIResponse( |
| 161 |
raw=httpx2.Response( |
| 162 |
200, |
| 163 |
headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"}, |
| 164 |
content=json.dumps({"foo": "hello!", "bar": 2}), |
| 165 |
), |
| 166 |
client=client, |
| 167 |
stream=False, |
| 168 |
stream_cls=None, |
| 169 |
cast_to=str, |
| 170 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 171 |
) |
| 172 |
obj = response.parse(to=CustomModel) |
| 173 |
assert obj._request_id == "my-req-id" |
| 174 |
assert obj._workspace_id == "wrkspc_123" |
| 175 |
assert obj.foo == "hello!" |
| 176 |
assert obj.bar == 2 |
| 177 |
assert obj.to_dict() == {"foo": "hello!", "bar": 2} |
| 178 |
|
| 179 |
|
| 180 |
@pytest.mark.asyncio |
| 181 |
async def test_async_response_basemodel_request_id(client: Anthropic) -> None: |
| 182 |
response = AsyncAPIResponse( |
| 183 |
raw=httpx2.Response( |
| 184 |
200, |
| 185 |
headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"}, |
| 186 |
content=json.dumps({"foo": "hello!", "bar": 2}), |
| 187 |
), |
| 188 |
client=client, |
| 189 |
stream=False, |
| 190 |
stream_cls=None, |
| 191 |
cast_to=str, |
| 192 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 193 |
) |
| 194 |
obj = await response.parse(to=CustomModel) |
| 195 |
assert obj._request_id == "my-req-id" |
| 196 |
assert obj._workspace_id == "wrkspc_123" |
| 197 |
assert obj.foo == "hello!" |
| 198 |
assert obj.bar == 2 |
| 199 |
assert obj.to_dict() == {"foo": "hello!", "bar": 2} |
| 200 |
|
| 201 |
|
| 202 |
def test_response_parse_annotated_type(client: Anthropic) -> None: |
| 203 |
response = APIResponse( |
| 204 |
raw=httpx2.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 205 |
client=client, |
| 206 |
stream=False, |
| 207 |
stream_cls=None, |
| 208 |
cast_to=str, |
| 209 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 210 |
) |
| 211 |
|
| 212 |
obj = response.parse( |
| 213 |
to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), |
| 214 |
) |
| 215 |
assert obj.foo == "hello!" |
| 216 |
assert obj.bar == 2 |
| 217 |
|
| 218 |
|
| 219 |
async def test_async_response_parse_annotated_type(async_client: AsyncAnthropic) -> None: |
| 220 |
response = AsyncAPIResponse( |
| 221 |
raw=httpx2.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 222 |
client=async_client, |
| 223 |
stream=False, |
| 224 |
stream_cls=None, |
| 225 |
cast_to=str, |
| 226 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 227 |
) |
| 228 |
|
| 229 |
obj = await response.parse( |
| 230 |
to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), |
| 231 |
) |
| 232 |
assert obj.foo == "hello!" |
| 233 |
assert obj.bar == 2 |
| 234 |
|
| 235 |
|
| 236 |
@pytest.mark.parametrize( |
| 237 |
"content, expected", |
| 238 |
[ |
| 239 |
("false", False), |
| 240 |
("true", True), |
| 241 |
("False", False), |
| 242 |
("True", True), |
| 243 |
("TrUe", True), |
| 244 |
("FalSe", False), |
| 245 |
], |
| 246 |
) |
| 247 |
def test_response_parse_bool(client: Anthropic, content: str, expected: bool) -> None: |
| 248 |
response = APIResponse( |
| 249 |
raw=httpx2.Response(200, content=content), |
| 250 |
client=client, |
| 251 |
stream=False, |
| 252 |
stream_cls=None, |
| 253 |
cast_to=str, |
| 254 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 255 |
) |
| 256 |
|
| 257 |
result = response.parse(to=bool) |
| 258 |
assert result is expected |
| 259 |
|
| 260 |
|
| 261 |
@pytest.mark.parametrize( |
| 262 |
"content, expected", |
| 263 |
[ |
| 264 |
("false", False), |
| 265 |
("true", True), |
| 266 |
("False", False), |
| 267 |
("True", True), |
| 268 |
("TrUe", True), |
| 269 |
("FalSe", False), |
| 270 |
], |
| 271 |
) |
| 272 |
async def test_async_response_parse_bool(client: AsyncAnthropic, content: str, expected: bool) -> None: |
| 273 |
response = AsyncAPIResponse( |
| 274 |
raw=httpx2.Response(200, content=content), |
| 275 |
client=client, |
| 276 |
stream=False, |
| 277 |
stream_cls=None, |
| 278 |
cast_to=str, |
| 279 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 280 |
) |
| 281 |
|
| 282 |
result = await response.parse(to=bool) |
| 283 |
assert result is expected |
| 284 |
|
| 285 |
|
| 286 |
class OtherModel(BaseModel): |
| 287 |
a: str |
| 288 |
|
| 289 |
|
| 290 |
@pytest.mark.parametrize("client", [False], indirect=True) # loose validation |
| 291 |
def test_response_parse_expect_model_union_non_json_content(client: Anthropic) -> None: |
| 292 |
response = APIResponse( |
| 293 |
raw=httpx2.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), |
| 294 |
client=client, |
| 295 |
stream=False, |
| 296 |
stream_cls=None, |
| 297 |
cast_to=str, |
| 298 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 299 |
) |
| 300 |
|
| 301 |
obj = response.parse(to=cast(Any, Union[CustomModel, OtherModel])) |
| 302 |
assert isinstance(obj, str) |
| 303 |
assert obj == "foo" |
| 304 |
|
| 305 |
|
| 306 |
@pytest.mark.asyncio |
| 307 |
@pytest.mark.parametrize("async_client", [False], indirect=True) # loose validation |
| 308 |
async def test_async_response_parse_expect_model_union_non_json_content(async_client: AsyncAnthropic) -> None: |
| 309 |
response = AsyncAPIResponse( |
| 310 |
raw=httpx2.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), |
| 311 |
client=async_client, |
| 312 |
stream=False, |
| 313 |
stream_cls=None, |
| 314 |
cast_to=str, |
| 315 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 316 |
) |
| 317 |
|
| 318 |
obj = await response.parse(to=cast(Any, Union[CustomModel, OtherModel])) |
| 319 |
assert isinstance(obj, str) |
| 320 |
assert obj == "foo" |
| 321 |
|
| 322 |
|
| 323 |
def test_response_parse_pep604_union(client: Anthropic) -> None: |
| 324 |
response = APIResponse( |
| 325 |
raw=httpx2.Response(200, content=json.dumps({"a": "hello!"}), headers={"Content-Type": "application/json"}), |
| 326 |
client=client, |
| 327 |
stream=False, |
| 328 |
stream_cls=None, |
| 329 |
cast_to=str, |
| 330 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 331 |
) |
| 332 |
|
| 333 |
obj = response.parse(to=cast(Any, CustomModel | OtherModel)) |
| 334 |
assert isinstance(obj, OtherModel) |
| 335 |
assert obj.a == "hello!" |
| 336 |
|
| 337 |
|
| 338 |
@pytest.mark.asyncio |
| 339 |
async def test_async_response_parse_pep604_union(async_client: AsyncAnthropic) -> None: |
| 340 |
response = AsyncAPIResponse( |
| 341 |
raw=httpx2.Response(200, content=json.dumps({"a": "hello!"}), headers={"Content-Type": "application/json"}), |
| 342 |
client=async_client, |
| 343 |
stream=False, |
| 344 |
stream_cls=None, |
| 345 |
cast_to=str, |
| 346 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 347 |
) |
| 348 |
|
| 349 |
obj = await response.parse(to=cast(Any, CustomModel | OtherModel)) |
| 350 |
assert isinstance(obj, OtherModel) |
| 351 |
assert obj.a == "hello!" |
| 352 |
|
| 353 |
|
| 354 |
def test_response_parse_json_content_type_case_insensitive(client: Anthropic) -> None: |
| 355 |
response = APIResponse( |
| 356 |
raw=httpx2.Response( |
| 357 |
200, |
| 358 |
content=b'{"foo": "bar"}', |
| 359 |
headers={"Content-Type": "Application/JSON; Charset=UTF-8"}, |
| 360 |
request=httpx2.Request("GET", "/foo"), |
| 361 |
), |
| 362 |
client=client, |
| 363 |
stream=False, |
| 364 |
stream_cls=None, |
| 365 |
cast_to=str, |
| 366 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 367 |
) |
| 368 |
|
| 369 |
obj = response.parse(to=object) |
| 370 |
assert obj == {"foo": "bar"} |
| 371 |
|
| 372 |
|
| 373 |
@pytest.mark.asyncio |
| 374 |
async def test_async_response_parse_json_content_type_case_insensitive(async_client: AsyncAnthropic) -> None: |
| 375 |
response = AsyncAPIResponse( |
| 376 |
raw=httpx2.Response( |
| 377 |
200, |
| 378 |
content=b'{"foo": "bar"}', |
| 379 |
headers={"Content-Type": "Application/JSON; Charset=UTF-8"}, |
| 380 |
request=httpx2.Request("GET", "/foo"), |
| 381 |
), |
| 382 |
client=async_client, |
| 383 |
stream=False, |
| 384 |
stream_cls=None, |
| 385 |
cast_to=str, |
| 386 |
options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 387 |
) |
| 388 |
|
| 389 |
obj = await response.parse(to=object) |
| 390 |
assert obj == {"foo": "bar"} |