anthropic 0.72.1__py3-none-any.whl → 0.74.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. anthropic/__init__.py +3 -0
  2. anthropic/_client.py +8 -0
  3. anthropic/_compat.py +6 -0
  4. anthropic/_models.py +13 -1
  5. anthropic/_utils/_transform.py +1 -1
  6. anthropic/_version.py +1 -1
  7. anthropic/lib/_files.py +2 -2
  8. anthropic/lib/_parse/_response.py +44 -0
  9. anthropic/lib/_parse/_transform.py +167 -0
  10. anthropic/lib/foundry.md +127 -0
  11. anthropic/lib/foundry.py +443 -0
  12. anthropic/lib/streaming/__init__.py +14 -4
  13. anthropic/lib/streaming/_beta_messages.py +82 -43
  14. anthropic/lib/streaming/_beta_types.py +21 -13
  15. anthropic/lib/tools/_beta_runner.py +102 -101
  16. anthropic/resources/beta/messages/batches.py +12 -12
  17. anthropic/resources/beta/messages/messages.py +365 -29
  18. anthropic/resources/messages/batches.py +12 -12
  19. anthropic/resources/messages/messages.py +14 -8
  20. anthropic/types/beta/__init__.py +1 -0
  21. anthropic/types/beta/beta_code_execution_tool_20250522_param.py +2 -0
  22. anthropic/types/beta/beta_code_execution_tool_20250825_param.py +2 -0
  23. anthropic/types/beta/beta_json_output_format_param.py +15 -0
  24. anthropic/types/beta/beta_memory_tool_20250818_param.py +2 -0
  25. anthropic/types/beta/beta_tool_bash_20241022_param.py +2 -0
  26. anthropic/types/beta/beta_tool_bash_20250124_param.py +2 -0
  27. anthropic/types/beta/beta_tool_computer_use_20241022_param.py +2 -0
  28. anthropic/types/beta/beta_tool_computer_use_20250124_param.py +2 -0
  29. anthropic/types/beta/beta_tool_param.py +2 -0
  30. anthropic/types/beta/beta_tool_text_editor_20241022_param.py +2 -0
  31. anthropic/types/beta/beta_tool_text_editor_20250124_param.py +2 -0
  32. anthropic/types/beta/beta_tool_text_editor_20250429_param.py +2 -0
  33. anthropic/types/beta/beta_tool_text_editor_20250728_param.py +2 -0
  34. anthropic/types/beta/beta_web_fetch_tool_20250910_param.py +2 -0
  35. anthropic/types/beta/beta_web_search_tool_20250305_param.py +2 -0
  36. anthropic/types/beta/message_count_tokens_params.py +4 -0
  37. anthropic/types/beta/message_create_params.py +24 -2
  38. anthropic/types/beta/messages/batch_create_params.py +8 -2
  39. anthropic/types/beta/parsed_beta_message.py +68 -0
  40. anthropic/types/messages/batch_create_params.py +0 -1
  41. {anthropic-0.72.1.dist-info → anthropic-0.74.0.dist-info}/METADATA +1 -1
  42. {anthropic-0.72.1.dist-info → anthropic-0.74.0.dist-info}/RECORD +44 -38
  43. {anthropic-0.72.1.dist-info → anthropic-0.74.0.dist-info}/WHEEL +0 -0
  44. {anthropic-0.72.1.dist-info → anthropic-0.74.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,443 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload
6
+ from functools import cached_property
7
+ from typing_extensions import Self, override
8
+
9
+ import httpx
10
+
11
+ from .._types import NOT_GIVEN, Omit, Timeout, NotGiven
12
+ from .._utils import is_given
13
+ from .._client import Anthropic, AsyncAnthropic
14
+ from .._compat import model_copy
15
+ from .._models import FinalRequestOptions
16
+ from .._streaming import Stream, AsyncStream
17
+ from .._exceptions import AnthropicError
18
+ from .._base_client import DEFAULT_MAX_RETRIES, BaseClient
19
+ from ..resources.beta import Beta, AsyncBeta
20
+ from ..resources.messages import Messages, AsyncMessages
21
+ from ..resources.beta.messages import Messages as BetaMessages, AsyncMessages as AsyncBetaMessages
22
+
23
+ AzureADTokenProvider = Callable[[], str]
24
+ AsyncAzureADTokenProvider = Callable[[], "str | Awaitable[str]"]
25
+ _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient])
26
+ _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
27
+
28
+
29
+ class MutuallyExclusiveAuthError(AnthropicError):
30
+ def __init__(self) -> None:
31
+ super().__init__(
32
+ "The `api_key` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time"
33
+ )
34
+
35
+
36
+ class BaseFoundryClient(BaseClient[_HttpxClientT, _DefaultStreamT]): ...
37
+
38
+
39
+ class MessagesFoundry(Messages):
40
+ @cached_property
41
+ @override
42
+ def batches(self) -> None: # type: ignore[override]
43
+ """Batches endpoint is not supported for Anthropic Foundry client."""
44
+ return None
45
+
46
+
47
+ class BetaFoundryMessages(BetaMessages):
48
+ @cached_property
49
+ @override
50
+ def batches(self) -> None: # type: ignore[override]
51
+ """Batches endpoint is not supported for Anthropic Foundry client."""
52
+ return None
53
+
54
+
55
+ class BetaFoundry(Beta):
56
+ @cached_property
57
+ @override
58
+ def messages(self) -> BetaMessages: # type: ignore[override]
59
+ """Return beta messages resource instance with excluded unsupported endpoints."""
60
+ return BetaFoundryMessages(self._client)
61
+
62
+
63
+ class AsyncMessagesFoundry(AsyncMessages):
64
+ @cached_property
65
+ @override
66
+ def batches(self) -> None: # type: ignore[override]
67
+ """Batches endpoint is not supported for Anthropic Foundry client."""
68
+ return None
69
+
70
+
71
+ class AsyncBetaFoundryMessages(AsyncBetaMessages):
72
+ @cached_property
73
+ @override
74
+ def batches(self) -> None: # type: ignore[override]
75
+ """Batches endpoint is not supported for Anthropic Foundry client."""
76
+ return None
77
+
78
+
79
+ class AsyncBetaFoundry(AsyncBeta):
80
+ @cached_property
81
+ @override
82
+ def messages(self) -> AsyncBetaMessages: # type: ignore[override]
83
+ """Return beta messages resource instance with excluded unsupported endpoints."""
84
+ return AsyncBetaFoundryMessages(self._client)
85
+
86
+
87
+ # ==============================================================================
88
+
89
+
90
+ class AnthropicFoundry(BaseFoundryClient[httpx.Client, Stream[Any]], Anthropic):
91
+ @overload
92
+ def __init__(
93
+ self,
94
+ *,
95
+ resource: str | None = None,
96
+ api_key: str | None = None,
97
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
98
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
99
+ max_retries: int = DEFAULT_MAX_RETRIES,
100
+ default_headers: Mapping[str, str] | None = None,
101
+ default_query: Mapping[str, object] | None = None,
102
+ http_client: httpx.Client | None = None,
103
+ _strict_response_validation: bool = False,
104
+ ) -> None: ...
105
+
106
+ @overload
107
+ def __init__(
108
+ self,
109
+ *,
110
+ base_url: str,
111
+ api_key: str | None = None,
112
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
113
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
114
+ max_retries: int = DEFAULT_MAX_RETRIES,
115
+ default_headers: Mapping[str, str] | None = None,
116
+ default_query: Mapping[str, object] | None = None,
117
+ http_client: httpx.Client | None = None,
118
+ _strict_response_validation: bool = False,
119
+ ) -> None: ...
120
+
121
+ def __init__(
122
+ self,
123
+ *,
124
+ resource: str | None = None,
125
+ api_key: str | None = None,
126
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
127
+ base_url: str | None = None,
128
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
129
+ max_retries: int = DEFAULT_MAX_RETRIES,
130
+ default_headers: Mapping[str, str] | None = None,
131
+ default_query: Mapping[str, object] | None = None,
132
+ http_client: httpx.Client | None = None,
133
+ _strict_response_validation: bool = False,
134
+ ) -> None:
135
+ """Construct a new synchronous Anthropic Foundry client instance.
136
+
137
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
138
+ - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY`
139
+ - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE`
140
+ - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL`
141
+
142
+ Args:
143
+ resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/`
144
+ azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
145
+ """
146
+ api_key = api_key if api_key is not None else os.environ.get("ANTHROPIC_FOUNDRY_API_KEY")
147
+ resource = resource if resource is not None else os.environ.get("ANTHROPIC_FOUNDRY_RESOURCE")
148
+ base_url = base_url if base_url is not None else os.environ.get("ANTHROPIC_FOUNDRY_BASE_URL")
149
+
150
+ if api_key is None and azure_ad_token_provider is None:
151
+ raise AnthropicError(
152
+ "Missing credentials. Please pass one of `api_key`, `azure_ad_token_provider`, or the `ANTHROPIC_FOUNDRY_API_KEY` environment variable."
153
+ )
154
+
155
+ if base_url is None:
156
+ if resource is None:
157
+ raise ValueError(
158
+ "Must provide one of the `base_url` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable"
159
+ )
160
+ base_url = f"https://{resource}.services.ai.azure.com/anthropic/"
161
+ elif resource is not None:
162
+ raise ValueError("base_url and resource are mutually exclusive")
163
+
164
+ super().__init__(
165
+ api_key=api_key,
166
+ base_url=base_url,
167
+ timeout=timeout,
168
+ max_retries=max_retries,
169
+ default_headers=default_headers,
170
+ default_query=default_query,
171
+ http_client=http_client,
172
+ _strict_response_validation=_strict_response_validation,
173
+ )
174
+ self._azure_ad_token_provider = azure_ad_token_provider
175
+
176
+ @cached_property
177
+ @override
178
+ def models(self) -> None: # type: ignore[override]
179
+ """Models endpoint is not supported for Anthropic Foundry client."""
180
+ return None
181
+
182
+ @cached_property
183
+ @override
184
+ def messages(self) -> MessagesFoundry: # type: ignore[override]
185
+ """Return messages resource instance with excluded unsupported endpoints."""
186
+ return MessagesFoundry(client=self)
187
+
188
+ @cached_property
189
+ @override
190
+ def beta(self) -> Beta: # type: ignore[override]
191
+ """Return beta resource instance with excluded unsupported endpoints."""
192
+ return BetaFoundry(self)
193
+
194
+ @override
195
+ def copy(
196
+ self,
197
+ *,
198
+ api_key: str | None = None,
199
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
200
+ auth_token: str | None = None,
201
+ base_url: str | httpx.URL | None = None,
202
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
203
+ http_client: httpx.Client | None = None,
204
+ max_retries: int | NotGiven = NOT_GIVEN,
205
+ default_headers: Mapping[str, str] | None = None,
206
+ set_default_headers: Mapping[str, str] | None = None,
207
+ default_query: Mapping[str, object] | None = None,
208
+ set_default_query: Mapping[str, object] | None = None,
209
+ _extra_kwargs: Mapping[str, Any] = {},
210
+ ) -> Self:
211
+ """
212
+ Create a new client instance re-using the same options given to the current client with optional overriding.
213
+ """
214
+ return super().copy(
215
+ api_key=api_key,
216
+ auth_token=auth_token,
217
+ base_url=base_url,
218
+ timeout=timeout,
219
+ http_client=http_client,
220
+ max_retries=max_retries,
221
+ default_headers=default_headers,
222
+ set_default_headers=set_default_headers,
223
+ default_query=default_query,
224
+ set_default_query=set_default_query,
225
+ _extra_kwargs={
226
+ "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider,
227
+ **_extra_kwargs,
228
+ },
229
+ )
230
+
231
+ with_options = copy
232
+
233
+ def _get_azure_ad_token(self) -> str | None:
234
+ provider = self._azure_ad_token_provider
235
+ if provider is not None:
236
+ token = provider()
237
+ if not token or not isinstance(token, str): # pyright: ignore[reportUnnecessaryIsInstance]
238
+ raise ValueError(
239
+ f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}",
240
+ )
241
+ return token
242
+
243
+ return None
244
+
245
+ @override
246
+ def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
247
+ headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {}
248
+
249
+ options = model_copy(options)
250
+ options.headers = headers
251
+
252
+ azure_ad_token = self._get_azure_ad_token()
253
+ if azure_ad_token is not None:
254
+ if headers.get("Authorization") is None:
255
+ headers["Authorization"] = f"Bearer {azure_ad_token}"
256
+ elif self.api_key is not None:
257
+ if headers.get("api-key") is None:
258
+ assert self.api_key is not None
259
+ headers["api-key"] = self.api_key
260
+ else:
261
+ # should never be hit
262
+ raise ValueError("Unable to handle auth")
263
+
264
+ return options
265
+
266
+
267
+ class AsyncAnthropicFoundry(BaseFoundryClient[httpx.AsyncClient, AsyncStream[Any]], AsyncAnthropic):
268
+ @overload
269
+ def __init__(
270
+ self,
271
+ *,
272
+ resource: str | None = None,
273
+ api_key: str | None = None,
274
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
275
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
276
+ max_retries: int = DEFAULT_MAX_RETRIES,
277
+ default_headers: Mapping[str, str] | None = None,
278
+ default_query: Mapping[str, object] | None = None,
279
+ http_client: httpx.AsyncClient | None = None,
280
+ _strict_response_validation: bool = False,
281
+ ) -> None: ...
282
+
283
+ @overload
284
+ def __init__(
285
+ self,
286
+ *,
287
+ base_url: str,
288
+ api_key: str | None = None,
289
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
290
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
291
+ max_retries: int = DEFAULT_MAX_RETRIES,
292
+ default_headers: Mapping[str, str] | None = None,
293
+ default_query: Mapping[str, object] | None = None,
294
+ http_client: httpx.AsyncClient | None = None,
295
+ _strict_response_validation: bool = False,
296
+ ) -> None: ...
297
+
298
+ def __init__(
299
+ self,
300
+ *,
301
+ resource: str | None = None,
302
+ api_key: str | None = None,
303
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
304
+ base_url: str | None = None,
305
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
306
+ max_retries: int = DEFAULT_MAX_RETRIES,
307
+ default_headers: Mapping[str, str] | None = None,
308
+ default_query: Mapping[str, object] | None = None,
309
+ http_client: httpx.AsyncClient | None = None,
310
+ _strict_response_validation: bool = False,
311
+ ) -> None:
312
+ """Construct a new asynchronous Anthropic Foundry client instance.
313
+
314
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
315
+ - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY`
316
+ - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE`
317
+ - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL`
318
+
319
+ Args:
320
+ resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/`
321
+ azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
322
+ """
323
+ api_key = api_key if api_key is not None else os.environ.get("ANTHROPIC_FOUNDRY_API_KEY")
324
+ resource = resource if resource is not None else os.environ.get("ANTHROPIC_FOUNDRY_RESOURCE")
325
+ base_url = base_url if base_url is not None else os.environ.get("ANTHROPIC_FOUNDRY_BASE_URL")
326
+
327
+ if api_key is None and azure_ad_token_provider is None:
328
+ raise AnthropicError(
329
+ "Missing credentials. Please pass one of `api_key`, `azure_ad_token_provider`, or the `ANTHROPIC_FOUNDRY_API_KEY` environment variable."
330
+ )
331
+
332
+ if base_url is None:
333
+ if resource is None:
334
+ raise ValueError(
335
+ "Must provide one of the `base_url` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable"
336
+ )
337
+ base_url = f"https://{resource}.services.ai.azure.com/anthropic/"
338
+ elif resource is not None:
339
+ raise ValueError("base_url and resource are mutually exclusive")
340
+
341
+ super().__init__(
342
+ api_key=api_key,
343
+ base_url=base_url,
344
+ timeout=timeout,
345
+ max_retries=max_retries,
346
+ default_headers=default_headers,
347
+ default_query=default_query,
348
+ http_client=http_client,
349
+ _strict_response_validation=_strict_response_validation,
350
+ )
351
+ self._azure_ad_token_provider = azure_ad_token_provider
352
+
353
+ @cached_property
354
+ @override
355
+ def models(self) -> None: # type: ignore[override]
356
+ """Models endpoint is not supported for Azure Anthropic client."""
357
+ return None
358
+
359
+ @cached_property
360
+ @override
361
+ def messages(self) -> AsyncMessagesFoundry: # type: ignore[override]
362
+ """Return messages resource instance with excluded unsupported endpoints."""
363
+ return AsyncMessagesFoundry(client=self)
364
+
365
+ @cached_property
366
+ @override
367
+ def beta(self) -> AsyncBetaFoundry: # type: ignore[override]
368
+ """Return beta resource instance with excluded unsupported endpoints."""
369
+ return AsyncBetaFoundry(client=self)
370
+
371
+ @override
372
+ def copy(
373
+ self,
374
+ *,
375
+ api_key: str | None = None,
376
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
377
+ auth_token: str | None = None,
378
+ base_url: str | httpx.URL | None = None,
379
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
380
+ http_client: httpx.AsyncClient | None = None,
381
+ max_retries: int | NotGiven = NOT_GIVEN,
382
+ default_headers: Mapping[str, str] | None = None,
383
+ set_default_headers: Mapping[str, str] | None = None,
384
+ default_query: Mapping[str, object] | None = None,
385
+ set_default_query: Mapping[str, object] | None = None,
386
+ _extra_kwargs: Mapping[str, Any] = {},
387
+ ) -> Self:
388
+ """
389
+ Create a new client instance re-using the same options given to the current client with optional overriding.
390
+ """
391
+ return super().copy(
392
+ api_key=api_key,
393
+ auth_token=auth_token,
394
+ base_url=base_url,
395
+ timeout=timeout,
396
+ http_client=http_client,
397
+ max_retries=max_retries,
398
+ default_headers=default_headers,
399
+ set_default_headers=set_default_headers,
400
+ default_query=default_query,
401
+ set_default_query=set_default_query,
402
+ _extra_kwargs={
403
+ "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider,
404
+ **_extra_kwargs,
405
+ },
406
+ )
407
+
408
+ with_options = copy
409
+
410
+ async def _get_azure_ad_token(self) -> str | None:
411
+ provider = self._azure_ad_token_provider
412
+ if provider is not None:
413
+ token = provider()
414
+ if inspect.isawaitable(token):
415
+ token = await token
416
+ if not token or not isinstance(cast(Any, token), str):
417
+ raise ValueError(
418
+ f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}",
419
+ )
420
+ return str(token)
421
+
422
+ return None
423
+
424
+ @override
425
+ async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
426
+ headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {}
427
+
428
+ options = model_copy(options)
429
+ options.headers = headers
430
+
431
+ azure_ad_token = await self._get_azure_ad_token()
432
+ if azure_ad_token is not None:
433
+ if headers.get("Authorization") is None:
434
+ headers["Authorization"] = f"Bearer {azure_ad_token}"
435
+ elif self.api_key is not None:
436
+ assert self.api_key is not None
437
+ if headers.get("api-key") is None:
438
+ headers["api-key"] = self.api_key
439
+ else:
440
+ # should never be hit
441
+ raise ValueError("Unable to handle auth")
442
+
443
+ return options
@@ -1,3 +1,5 @@
1
+ from typing_extensions import TypeAlias
2
+
1
3
  from ._types import (
2
4
  TextEvent as TextEvent,
3
5
  InputJsonEvent as InputJsonEvent,
@@ -12,12 +14,20 @@ from ._messages import (
12
14
  AsyncMessageStreamManager as AsyncMessageStreamManager,
13
15
  )
14
16
  from ._beta_types import (
15
- BetaTextEvent as BetaTextEvent,
16
17
  BetaInputJsonEvent as BetaInputJsonEvent,
17
- BetaMessageStopEvent as BetaMessageStopEvent,
18
- BetaMessageStreamEvent as BetaMessageStreamEvent,
19
- BetaContentBlockStopEvent as BetaContentBlockStopEvent,
18
+ ParsedBetaTextEvent as ParsedBetaTextEvent,
19
+ ParsedBetaMessageStopEvent as ParsedBetaMessageStopEvent,
20
+ ParsedBetaMessageStreamEvent as ParsedBetaMessageStreamEvent,
21
+ ParsedBetaContentBlockStopEvent as ParsedBetaContentBlockStopEvent,
20
22
  )
23
+
24
+ # For backwards compatibility
25
+ BetaTextEvent: TypeAlias = ParsedBetaTextEvent
26
+ BetaMessageStopEvent: TypeAlias = ParsedBetaMessageStopEvent[object]
27
+ BetaMessageStreamEvent: TypeAlias = ParsedBetaMessageStreamEvent
28
+ BetaContentBlockStopEvent: TypeAlias = ParsedBetaContentBlockStopEvent[object]
29
+
30
+
21
31
  from ._beta_messages import (
22
32
  BetaMessageStream as BetaMessageStream,
23
33
  BetaAsyncMessageStream as BetaAsyncMessageStream,