From e3548ac1c5a5bc3124bb4345438b2bd1491965ec Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 23:28:27 +0000 Subject: [PATCH 01/10] fix(pydantic v1): more robust ModelField.annotation check --- src/anthropic/_models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/anthropic/_models.py b/src/anthropic/_models.py index fa55865ee..7842c1503 100644 --- a/src/anthropic/_models.py +++ b/src/anthropic/_models.py @@ -642,8 +642,8 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, # Note: if one variant defines an alias then they all should discriminator_alias = field_info.alias - if field_info.annotation and is_literal_type(field_info.annotation): - for entry in get_args(field_info.annotation): + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): + for entry in get_args(annotation): if isinstance(entry, str): mapping[entry] = variant From bfebcd91c67d955f6a34bd1a4b7f949dee41119d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:22:23 +0000 Subject: [PATCH 02/10] chore(internal): minor formatting changes --- src/anthropic/types/beta/beta_message_delta_usage.py | 1 - src/anthropic/types/beta/beta_message_tokens_count.py | 1 - .../beta/messages/beta_message_batch_individual_response.py | 1 - .../types/beta/messages/beta_message_batch_request_counts.py | 1 - src/anthropic/types/content_block_delta_event.py | 1 - src/anthropic/types/content_block_start_event.py | 1 - src/anthropic/types/content_block_stop_event.py | 1 - src/anthropic/types/message_delta_event.py | 1 - src/anthropic/types/message_delta_usage.py | 1 - src/anthropic/types/message_start_event.py | 1 - src/anthropic/types/message_stop_event.py | 1 - src/anthropic/types/message_stream_event.py | 1 - src/anthropic/types/message_tokens_count.py | 1 - .../types/messages/message_batch_individual_response.py | 1 - src/anthropic/types/messages/message_batch_request_counts.py | 1 - 15 files changed, 15 deletions(-) diff --git a/src/anthropic/types/beta/beta_message_delta_usage.py b/src/anthropic/types/beta/beta_message_delta_usage.py index cc6819114..4a74731af 100644 --- a/src/anthropic/types/beta/beta_message_delta_usage.py +++ b/src/anthropic/types/beta/beta_message_delta_usage.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["BetaMessageDeltaUsage"] diff --git a/src/anthropic/types/beta/beta_message_tokens_count.py b/src/anthropic/types/beta/beta_message_tokens_count.py index e11daee72..8effd45fd 100644 --- a/src/anthropic/types/beta/beta_message_tokens_count.py +++ b/src/anthropic/types/beta/beta_message_tokens_count.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["BetaMessageTokensCount"] diff --git a/src/anthropic/types/beta/messages/beta_message_batch_individual_response.py b/src/anthropic/types/beta/messages/beta_message_batch_individual_response.py index 8c4939342..f9ed70a20 100644 --- a/src/anthropic/types/beta/messages/beta_message_batch_individual_response.py +++ b/src/anthropic/types/beta/messages/beta_message_batch_individual_response.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ...._models import BaseModel from .beta_message_batch_result import BetaMessageBatchResult diff --git a/src/anthropic/types/beta/messages/beta_message_batch_request_counts.py b/src/anthropic/types/beta/messages/beta_message_batch_request_counts.py index 48e6952f1..8b5750f66 100644 --- a/src/anthropic/types/beta/messages/beta_message_batch_request_counts.py +++ b/src/anthropic/types/beta/messages/beta_message_batch_request_counts.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ...._models import BaseModel __all__ = ["BetaMessageBatchRequestCounts"] diff --git a/src/anthropic/types/content_block_delta_event.py b/src/anthropic/types/content_block_delta_event.py index a32602b45..8d30cdefe 100644 --- a/src/anthropic/types/content_block_delta_event.py +++ b/src/anthropic/types/content_block_delta_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_content_block_delta_event import RawContentBlockDeltaEvent __all__ = ["ContentBlockDeltaEvent"] diff --git a/src/anthropic/types/content_block_start_event.py b/src/anthropic/types/content_block_start_event.py index 873cba3b3..2244a975a 100644 --- a/src/anthropic/types/content_block_start_event.py +++ b/src/anthropic/types/content_block_start_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_content_block_start_event import RawContentBlockStartEvent __all__ = ["ContentBlockStartEvent"] diff --git a/src/anthropic/types/content_block_stop_event.py b/src/anthropic/types/content_block_stop_event.py index 36c62c894..2c67bcccf 100644 --- a/src/anthropic/types/content_block_stop_event.py +++ b/src/anthropic/types/content_block_stop_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_content_block_stop_event import RawContentBlockStopEvent __all__ = ["ContentBlockStopEvent"] diff --git a/src/anthropic/types/message_delta_event.py b/src/anthropic/types/message_delta_event.py index 3803629af..cb1687bad 100644 --- a/src/anthropic/types/message_delta_event.py +++ b/src/anthropic/types/message_delta_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_message_delta_event import RawMessageDeltaEvent __all__ = ["MessageDeltaEvent"] diff --git a/src/anthropic/types/message_delta_usage.py b/src/anthropic/types/message_delta_usage.py index e4321be4f..d6ca79e64 100644 --- a/src/anthropic/types/message_delta_usage.py +++ b/src/anthropic/types/message_delta_usage.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["MessageDeltaUsage"] diff --git a/src/anthropic/types/message_start_event.py b/src/anthropic/types/message_start_event.py index c210d3ad6..d089e5636 100644 --- a/src/anthropic/types/message_start_event.py +++ b/src/anthropic/types/message_start_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_message_start_event import RawMessageStartEvent __all__ = ["MessageStartEvent"] diff --git a/src/anthropic/types/message_stop_event.py b/src/anthropic/types/message_stop_event.py index 1076a62c6..30564cbed 100644 --- a/src/anthropic/types/message_stop_event.py +++ b/src/anthropic/types/message_stop_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_message_stop_event import RawMessageStopEvent __all__ = ["MessageStopEvent"] diff --git a/src/anthropic/types/message_stream_event.py b/src/anthropic/types/message_stream_event.py index ec5a01254..65485501a 100644 --- a/src/anthropic/types/message_stream_event.py +++ b/src/anthropic/types/message_stream_event.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .raw_message_stream_event import RawMessageStreamEvent __all__ = ["MessageStreamEvent"] diff --git a/src/anthropic/types/message_tokens_count.py b/src/anthropic/types/message_tokens_count.py index d570019f9..ff1144934 100644 --- a/src/anthropic/types/message_tokens_count.py +++ b/src/anthropic/types/message_tokens_count.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["MessageTokensCount"] diff --git a/src/anthropic/types/messages/message_batch_individual_response.py b/src/anthropic/types/messages/message_batch_individual_response.py index 19d4f0902..6370a835c 100644 --- a/src/anthropic/types/messages/message_batch_individual_response.py +++ b/src/anthropic/types/messages/message_batch_individual_response.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel from .message_batch_result import MessageBatchResult diff --git a/src/anthropic/types/messages/message_batch_request_counts.py b/src/anthropic/types/messages/message_batch_request_counts.py index 04edc3c32..041f3b380 100644 --- a/src/anthropic/types/messages/message_batch_request_counts.py +++ b/src/anthropic/types/messages/message_batch_request_counts.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["MessageBatchRequestCounts"] From a41e9c346aecebefc71646544e44b51b227047cb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 19:11:07 +0000 Subject: [PATCH 03/10] chore(ci): run on more branches and use depot runners --- .github/workflows/ci.yml | 16 ++++++++-------- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/release-doctor.yml | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04b083ca7..33820422d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,18 +1,18 @@ name: CI on: push: - branches: - - main - pull_request: - branches: - - main - - next + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' jobs: lint: timeout-minutes: 10 name: lint - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -33,7 +33,7 @@ jobs: test: timeout-minutes: 10 name: test - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 2f45952de..c24322249 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -7,7 +7,7 @@ on: jobs: publish: name: publish - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 environment: production-release steps: diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 5b0131495..10a3e644f 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -8,7 +8,7 @@ on: jobs: release_doctor: name: release doctor - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 environment: production-release if: github.repository == 'anthropics/anthropic-sdk-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') From bcaa8a582b6f1a6056122c780369616e1d86dcbc Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 20:29:26 +0000 Subject: [PATCH 04/10] chore(ci): only use depot for staging repos --- .github/workflows/ci.yml | 4 ++-- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/release-doctor.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 33820422d..3265f3b93 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: lint: timeout-minutes: 10 name: lint - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/anthropic-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - uses: actions/checkout@v4 @@ -33,7 +33,7 @@ jobs: test: timeout-minutes: 10 name: test - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/anthropic-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index c24322249..2f45952de 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -7,7 +7,7 @@ on: jobs: publish: name: publish - runs-on: depot-ubuntu-24.04 + runs-on: ubuntu-latest environment: production-release steps: diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 10a3e644f..5b0131495 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -8,7 +8,7 @@ on: jobs: release_doctor: name: release doctor - runs-on: depot-ubuntu-24.04 + runs-on: ubuntu-latest environment: production-release if: github.repository == 'anthropics/anthropic-sdk-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') From 215f5bbe56377888c0473a2f6fd37a4b3004346e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 22:08:07 +0000 Subject: [PATCH 05/10] chore: broadly detect json family of content-type headers --- src/anthropic/_legacy_response.py | 2 +- src/anthropic/_response.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/anthropic/_legacy_response.py b/src/anthropic/_legacy_response.py index 5703932e5..e8315de0f 100644 --- a/src/anthropic/_legacy_response.py +++ b/src/anthropic/_legacy_response.py @@ -327,7 +327,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 content_type, *_ = response.headers.get("content-type", "*").split(";") - if content_type != "application/json": + if not content_type.endswith("json"): if is_basemodel(cast_to): try: data = response.json() diff --git a/src/anthropic/_response.py b/src/anthropic/_response.py index 64a3f158e..985b8a6bf 100644 --- a/src/anthropic/_response.py +++ b/src/anthropic/_response.py @@ -261,7 +261,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 content_type, *_ = response.headers.get("content-type", "*").split(";") - if content_type != "application/json": + if not content_type.endswith("json"): if is_basemodel(cast_to): try: data = response.json() From ac6cfee09022a0ef97fc59e55ed890bbed8ac810 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 May 2025 13:15:02 +0000 Subject: [PATCH 06/10] chore: use lazy imports for resources --- src/anthropic/_client.py | 225 +++++++++++++++++++++++++++++++-------- 1 file changed, 179 insertions(+), 46 deletions(-) diff --git a/src/anthropic/_client.py b/src/anthropic/_client.py index 0218dd9f0..987d919af 100644 --- a/src/anthropic/_client.py +++ b/src/anthropic/_client.py @@ -3,7 +3,7 @@ from __future__ import annotations import os -from typing import Any, Union, Mapping +from typing import TYPE_CHECKING, Any, Union, Mapping from typing_extensions import Self, override import httpx @@ -21,8 +21,8 @@ RequestOptions, ) from ._utils import is_given, get_async_library +from ._compat import cached_property from ._version import __version__ -from .resources import models, completions from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import APIStatusError from ._base_client import ( @@ -30,8 +30,13 @@ SyncAPIClient, AsyncAPIClient, ) -from .resources.beta import beta -from .resources.messages import messages + +if TYPE_CHECKING: + from .resources import beta, models, messages, completions + from .resources.models import Models, AsyncModels + from .resources.beta.beta import Beta, AsyncBeta + from .resources.completions import Completions, AsyncCompletions + from .resources.messages.messages import Messages, AsyncMessages __all__ = [ "Timeout", @@ -46,13 +51,6 @@ class Anthropic(SyncAPIClient): - completions: completions.Completions - messages: messages.Messages - models: models.Models - beta: beta.Beta - with_raw_response: AnthropicWithRawResponse - with_streaming_response: AnthropicWithStreamedResponse - # client options api_key: str | None auth_token: str | None @@ -117,12 +115,37 @@ def __init__( self._default_stream_cls = Stream - self.completions = completions.Completions(self) - self.messages = messages.Messages(self) - self.models = models.Models(self) - self.beta = beta.Beta(self) - self.with_raw_response = AnthropicWithRawResponse(self) - self.with_streaming_response = AnthropicWithStreamedResponse(self) + @cached_property + def completions(self) -> Completions: + from .resources.completions import Completions + + return Completions(self) + + @cached_property + def messages(self) -> Messages: + from .resources.messages import Messages + + return Messages(self) + + @cached_property + def models(self) -> Models: + from .resources.models import Models + + return Models(self) + + @cached_property + def beta(self) -> Beta: + from .resources.beta import Beta + + return Beta(self) + + @cached_property + def with_raw_response(self) -> AnthropicWithRawResponse: + return AnthropicWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AnthropicWithStreamedResponse: + return AnthropicWithStreamedResponse(self) @property @override @@ -268,13 +291,6 @@ def _make_status_error( class AsyncAnthropic(AsyncAPIClient): - completions: completions.AsyncCompletions - messages: messages.AsyncMessages - models: models.AsyncModels - beta: beta.AsyncBeta - with_raw_response: AsyncAnthropicWithRawResponse - with_streaming_response: AsyncAnthropicWithStreamedResponse - # client options api_key: str | None auth_token: str | None @@ -339,12 +355,37 @@ def __init__( self._default_stream_cls = AsyncStream - self.completions = completions.AsyncCompletions(self) - self.messages = messages.AsyncMessages(self) - self.models = models.AsyncModels(self) - self.beta = beta.AsyncBeta(self) - self.with_raw_response = AsyncAnthropicWithRawResponse(self) - self.with_streaming_response = AsyncAnthropicWithStreamedResponse(self) + @cached_property + def completions(self) -> AsyncCompletions: + from .resources.completions import AsyncCompletions + + return AsyncCompletions(self) + + @cached_property + def messages(self) -> AsyncMessages: + from .resources.messages import AsyncMessages + + return AsyncMessages(self) + + @cached_property + def models(self) -> AsyncModels: + from .resources.models import AsyncModels + + return AsyncModels(self) + + @cached_property + def beta(self) -> AsyncBeta: + from .resources.beta import AsyncBeta + + return AsyncBeta(self) + + @cached_property + def with_raw_response(self) -> AsyncAnthropicWithRawResponse: + return AsyncAnthropicWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAnthropicWithStreamedResponse: + return AsyncAnthropicWithStreamedResponse(self) @property @override @@ -484,35 +525,127 @@ def _make_status_error( class AnthropicWithRawResponse: + _client: Anthropic + def __init__(self, client: Anthropic) -> None: - self.completions = completions.CompletionsWithRawResponse(client.completions) - self.messages = messages.MessagesWithRawResponse(client.messages) - self.models = models.ModelsWithRawResponse(client.models) - self.beta = beta.BetaWithRawResponse(client.beta) + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithRawResponse: + from .resources.completions import CompletionsWithRawResponse + + return CompletionsWithRawResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.MessagesWithRawResponse: + from .resources.messages import MessagesWithRawResponse + + return MessagesWithRawResponse(self._client.messages) + + @cached_property + def models(self) -> models.ModelsWithRawResponse: + from .resources.models import ModelsWithRawResponse + + return ModelsWithRawResponse(self._client.models) + + @cached_property + def beta(self) -> beta.BetaWithRawResponse: + from .resources.beta import BetaWithRawResponse + + return BetaWithRawResponse(self._client.beta) class AsyncAnthropicWithRawResponse: + _client: AsyncAnthropic + def __init__(self, client: AsyncAnthropic) -> None: - self.completions = completions.AsyncCompletionsWithRawResponse(client.completions) - self.messages = messages.AsyncMessagesWithRawResponse(client.messages) - self.models = models.AsyncModelsWithRawResponse(client.models) - self.beta = beta.AsyncBetaWithRawResponse(client.beta) + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithRawResponse: + from .resources.completions import AsyncCompletionsWithRawResponse + + return AsyncCompletionsWithRawResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.AsyncMessagesWithRawResponse: + from .resources.messages import AsyncMessagesWithRawResponse + + return AsyncMessagesWithRawResponse(self._client.messages) + + @cached_property + def models(self) -> models.AsyncModelsWithRawResponse: + from .resources.models import AsyncModelsWithRawResponse + + return AsyncModelsWithRawResponse(self._client.models) + + @cached_property + def beta(self) -> beta.AsyncBetaWithRawResponse: + from .resources.beta import AsyncBetaWithRawResponse + + return AsyncBetaWithRawResponse(self._client.beta) class AnthropicWithStreamedResponse: + _client: Anthropic + def __init__(self, client: Anthropic) -> None: - self.completions = completions.CompletionsWithStreamingResponse(client.completions) - self.messages = messages.MessagesWithStreamingResponse(client.messages) - self.models = models.ModelsWithStreamingResponse(client.models) - self.beta = beta.BetaWithStreamingResponse(client.beta) + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithStreamingResponse: + from .resources.completions import CompletionsWithStreamingResponse + + return CompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.MessagesWithStreamingResponse: + from .resources.messages import MessagesWithStreamingResponse + + return MessagesWithStreamingResponse(self._client.messages) + + @cached_property + def models(self) -> models.ModelsWithStreamingResponse: + from .resources.models import ModelsWithStreamingResponse + + return ModelsWithStreamingResponse(self._client.models) + + @cached_property + def beta(self) -> beta.BetaWithStreamingResponse: + from .resources.beta import BetaWithStreamingResponse + + return BetaWithStreamingResponse(self._client.beta) class AsyncAnthropicWithStreamedResponse: + _client: AsyncAnthropic + def __init__(self, client: AsyncAnthropic) -> None: - self.completions = completions.AsyncCompletionsWithStreamingResponse(client.completions) - self.messages = messages.AsyncMessagesWithStreamingResponse(client.messages) - self.models = models.AsyncModelsWithStreamingResponse(client.models) - self.beta = beta.AsyncBetaWithStreamingResponse(client.beta) + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithStreamingResponse: + from .resources.completions import AsyncCompletionsWithStreamingResponse + + return AsyncCompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.AsyncMessagesWithStreamingResponse: + from .resources.messages import AsyncMessagesWithStreamingResponse + + return AsyncMessagesWithStreamingResponse(self._client.messages) + + @cached_property + def models(self) -> models.AsyncModelsWithStreamingResponse: + from .resources.models import AsyncModelsWithStreamingResponse + + return AsyncModelsWithStreamingResponse(self._client.models) + + @cached_property + def beta(self) -> beta.AsyncBetaWithStreamingResponse: + from .resources.beta import AsyncBetaWithStreamingResponse + + return AsyncBetaWithStreamingResponse(self._client.beta) Client = Anthropic From 51fd796456952c30478545ad8be7d486713e8d1d Mon Sep 17 00:00:00 2001 From: ksaurabh02 Date: Tue, 6 May 2025 12:47:01 +0200 Subject: [PATCH 07/10] fix(sockets): handle non-portable socket flags (#935) * Not all socket constants are available on every platform * Match the style of base code * Add the change of the socket constant to async client * Fix lint errors * Fix formatting --------- Co-authored-by: Kumar Saurabh Co-authored-by: Robert Craigie --- src/anthropic/_base_client.py | 40 ++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/src/anthropic/_base_client.py b/src/anthropic/_base_client.py index 49a7e9739..614346339 100644 --- a/src/anthropic/_base_client.py +++ b/src/anthropic/_base_client.py @@ -17,7 +17,9 @@ TYPE_CHECKING, Any, Dict, + List, Type, + Tuple, Union, Generic, Mapping, @@ -806,11 +808,20 @@ def __init__(self, **kwargs: Any) -> None: kwargs.setdefault("follow_redirects", True) if "transport" not in kwargs: - socket_options = [ - (socket.SOL_SOCKET, socket.SO_KEEPALIVE, True), - (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60), - (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5), - ] + socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)] + + TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None) + + if TCP_KEEPINTVL is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60)) + elif sys.platform == "darwin": + TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10) + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60)) + + TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None) + if TCP_KEEPCNT is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5)) + TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None) if TCP_KEEPIDLE is not None: socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60)) @@ -1335,11 +1346,20 @@ def __init__(self, **kwargs: Any) -> None: kwargs.setdefault("follow_redirects", True) if "transport" not in kwargs: - socket_options = [ - (socket.SOL_SOCKET, socket.SO_KEEPALIVE, True), - (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60), - (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5), - ] + socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)] + + TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None) + + if TCP_KEEPINTVL is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60)) + elif sys.platform == "darwin": + TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10) + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60)) + + TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None) + if TCP_KEEPCNT is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5)) + TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None) if TCP_KEEPIDLE is not None: socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60)) From 2da00f26c5f0bbf4f4039caec3c0500a2c2156bd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 7 May 2025 14:52:43 +0000 Subject: [PATCH 08/10] feat(api): adds web search capabilities to the Claude API --- .stats.yml | 6 +- api.md | 28 ++++++++ .../resources/beta/messages/messages.py | 16 +++++ src/anthropic/resources/beta/models.py | 33 +++++++++- src/anthropic/resources/completions.py | 31 ++++++++- src/anthropic/resources/messages/messages.py | 16 +++++ src/anthropic/resources/models.py | 33 +++++++++- src/anthropic/types/__init__.py | 18 ++++++ src/anthropic/types/beta/__init__.py | 26 ++++++++ .../types/beta/beta_base64_pdf_block_param.py | 1 + ...tation_web_search_result_location_param.py | 20 ++++++ .../types/beta/beta_citations_delta.py | 8 ++- ...ta_citations_web_search_result_location.py | 20 ++++++ .../types/beta/beta_content_block.py | 11 +++- .../types/beta/beta_content_block_param.py | 4 ++ .../types/beta/beta_image_block_param.py | 1 + .../types/beta/beta_message_delta_usage.py | 15 +++++ .../beta_raw_content_block_start_event.py | 11 +++- .../types/beta/beta_server_tool_usage.py | 10 +++ .../types/beta/beta_server_tool_use_block.py | 17 +++++ .../beta/beta_server_tool_use_block_param.py | 23 +++++++ src/anthropic/types/beta/beta_stop_reason.py | 2 +- .../types/beta/beta_text_block_param.py | 1 + .../types/beta/beta_text_citation.py | 8 ++- .../types/beta/beta_text_citation_param.py | 6 +- .../beta/beta_tool_bash_20241022_param.py | 3 +- .../beta/beta_tool_bash_20250124_param.py | 3 +- .../beta_tool_computer_use_20241022_param.py | 3 +- .../beta_tool_computer_use_20250124_param.py | 3 +- src/anthropic/types/beta/beta_tool_param.py | 3 +- .../beta/beta_tool_result_block_param.py | 1 + .../beta_tool_text_editor_20241022_param.py | 3 +- .../beta_tool_text_editor_20250124_param.py | 3 +- .../types/beta/beta_tool_union_param.py | 2 + .../types/beta/beta_tool_use_block_param.py | 1 + src/anthropic/types/beta/beta_usage.py | 4 ++ .../beta/beta_web_search_result_block.py | 20 ++++++ .../beta_web_search_result_block_param.py | 20 ++++++ .../beta_web_search_tool_20250305_param.py | 64 +++++++++++++++++++ ...eta_web_search_tool_request_error_param.py | 15 +++++ .../beta/beta_web_search_tool_result_block.py | 16 +++++ ...ta_web_search_tool_result_block_content.py | 11 ++++ ...beta_web_search_tool_result_block_param.py | 22 +++++++ ...h_tool_result_block_param_content_param.py | 15 +++++ .../beta/beta_web_search_tool_result_error.py | 13 ++++ .../types/beta/message_count_tokens_params.py | 4 ++ .../types/beta/message_create_params.py | 2 + src/anthropic/types/beta/model_list_params.py | 9 ++- ...tation_web_search_result_location_param.py | 20 ++++++ src/anthropic/types/citations_delta.py | 4 +- .../citations_web_search_result_location.py | 20 ++++++ .../types/completion_create_params.py | 7 +- src/anthropic/types/content_block.py | 5 +- src/anthropic/types/content_block_param.py | 4 ++ src/anthropic/types/document_block_param.py | 1 + src/anthropic/types/image_block_param.py | 1 + .../types/message_count_tokens_params.py | 2 + .../types/message_count_tokens_tool_param.py | 5 +- src/anthropic/types/message_create_params.py | 2 + src/anthropic/types/message_delta_usage.py | 15 +++++ src/anthropic/types/message_param.py | 4 ++ src/anthropic/types/model_list_params.py | 9 ++- .../types/raw_content_block_start_event.py | 5 +- src/anthropic/types/server_tool_usage.py | 10 +++ src/anthropic/types/server_tool_use_block.py | 17 +++++ .../types/server_tool_use_block_param.py | 23 +++++++ src/anthropic/types/stop_reason.py | 2 +- src/anthropic/types/text_block_param.py | 1 + src/anthropic/types/text_citation.py | 4 +- src/anthropic/types/text_citation_param.py | 6 +- .../types/tool_bash_20250124_param.py | 3 +- src/anthropic/types/tool_param.py | 5 +- .../types/tool_result_block_param.py | 1 + .../types/tool_text_editor_20250124_param.py | 3 +- src/anthropic/types/tool_union_param.py | 5 +- src/anthropic/types/tool_use_block_param.py | 1 + src/anthropic/types/usage.py | 4 ++ .../types/web_search_result_block.py | 20 ++++++ .../types/web_search_result_block_param.py | 20 ++++++ .../types/web_search_tool_20250305_param.py | 64 +++++++++++++++++++ .../web_search_tool_request_error_param.py | 15 +++++ .../types/web_search_tool_result_block.py | 16 +++++ .../web_search_tool_result_block_content.py | 11 ++++ .../web_search_tool_result_block_param.py | 22 +++++++ ...h_tool_result_block_param_content_param.py | 15 +++++ .../types/web_search_tool_result_error.py | 13 ++++ tests/api_resources/beta/test_models.py | 34 +++++++--- tests/api_resources/test_completions.py | 4 ++ tests/api_resources/test_messages.py | 6 ++ tests/api_resources/test_models.py | 34 +++++++--- 90 files changed, 1019 insertions(+), 49 deletions(-) create mode 100644 src/anthropic/types/beta/beta_citation_web_search_result_location_param.py create mode 100644 src/anthropic/types/beta/beta_citations_web_search_result_location.py create mode 100644 src/anthropic/types/beta/beta_server_tool_usage.py create mode 100644 src/anthropic/types/beta/beta_server_tool_use_block.py create mode 100644 src/anthropic/types/beta/beta_server_tool_use_block_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_result_block.py create mode 100644 src/anthropic/types/beta/beta_web_search_result_block_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_20250305_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_request_error_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_result_block.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_result_block_content.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_result_block_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py create mode 100644 src/anthropic/types/beta/beta_web_search_tool_result_error.py create mode 100644 src/anthropic/types/citation_web_search_result_location_param.py create mode 100644 src/anthropic/types/citations_web_search_result_location.py create mode 100644 src/anthropic/types/server_tool_usage.py create mode 100644 src/anthropic/types/server_tool_use_block.py create mode 100644 src/anthropic/types/server_tool_use_block_param.py create mode 100644 src/anthropic/types/web_search_result_block.py create mode 100644 src/anthropic/types/web_search_result_block_param.py create mode 100644 src/anthropic/types/web_search_tool_20250305_param.py create mode 100644 src/anthropic/types/web_search_tool_request_error_param.py create mode 100644 src/anthropic/types/web_search_tool_result_block.py create mode 100644 src/anthropic/types/web_search_tool_result_block_content.py create mode 100644 src/anthropic/types/web_search_tool_result_block_param.py create mode 100644 src/anthropic/types/web_search_tool_result_block_param_content_param.py create mode 100644 src/anthropic/types/web_search_tool_result_error.py diff --git a/.stats.yml b/.stats.yml index 30b9556db..5aa47f53d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 21 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-ea0576fceb17a0976feca9aa03aa426984d6fe1390f2bcdbf9de0212a81c8334.yml -openapi_spec_hash: d2d7ec2a7a35a1ed2443c3b690c802c4 -config_hash: 9d5b992847099d8fe5a5c09e66adbe5f +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7015ea2d98991d6c2e7931c521e36448778fe868cc1b8a21173898d67b14b819.yml +openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d +config_hash: 4d0dcf47d77eae22d34624d2ac0f0b46 diff --git a/api.md b/api.md index dc6402f1d..18224b046 100644 --- a/api.md +++ b/api.md @@ -31,8 +31,10 @@ from anthropic.types import ( CitationContentBlockLocationParam, CitationPageLocation, CitationPageLocationParam, + CitationWebSearchResultLocationParam, CitationsConfigParam, CitationsDelta, + CitationsWebSearchResultLocation, ContentBlock, ContentBlockParam, ContentBlockSource, @@ -58,6 +60,9 @@ from anthropic.types import ( RawMessageStreamEvent, RedactedThinkingBlock, RedactedThinkingBlockParam, + ServerToolUsage, + ServerToolUseBlock, + ServerToolUseBlockParam, SignatureDelta, StopReason, TextBlock, @@ -86,6 +91,15 @@ from anthropic.types import ( URLImageSource, URLPDFSource, Usage, + WebSearchResultBlock, + WebSearchResultBlockParam, + WebSearchTool20250305, + WebSearchToolRequestError, + WebSearchToolResultBlock, + WebSearchToolResultBlockContent, + WebSearchToolResultBlockParam, + WebSearchToolResultBlockParamContent, + WebSearchToolResultError, MessageStreamEvent, MessageStartEvent, MessageDeltaEvent, @@ -192,8 +206,10 @@ from anthropic.types.beta import ( BetaCitationContentBlockLocationParam, BetaCitationPageLocation, BetaCitationPageLocationParam, + BetaCitationWebSearchResultLocationParam, BetaCitationsConfigParam, BetaCitationsDelta, + BetaCitationsWebSearchResultLocation, BetaContentBlock, BetaContentBlockParam, BetaContentBlockSource, @@ -216,6 +232,9 @@ from anthropic.types.beta import ( BetaRawMessageStreamEvent, BetaRedactedThinkingBlock, BetaRedactedThinkingBlockParam, + BetaServerToolUsage, + BetaServerToolUseBlock, + BetaServerToolUseBlockParam, BetaSignatureDelta, BetaStopReason, BetaTextBlock, @@ -248,6 +267,15 @@ from anthropic.types.beta import ( BetaURLImageSource, BetaURLPDFSource, BetaUsage, + BetaWebSearchResultBlock, + BetaWebSearchResultBlockParam, + BetaWebSearchTool20250305, + BetaWebSearchToolRequestError, + BetaWebSearchToolResultBlock, + BetaWebSearchToolResultBlockContent, + BetaWebSearchToolResultBlockParam, + BetaWebSearchToolResultBlockParamContent, + BetaWebSearchToolResultError, ) ``` diff --git a/src/anthropic/resources/beta/messages/messages.py b/src/anthropic/resources/beta/messages/messages.py index df96cc2fa..a171d58ec 100644 --- a/src/anthropic/resources/beta/messages/messages.py +++ b/src/anthropic/resources/beta/messages/messages.py @@ -203,6 +203,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -482,6 +484,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -761,6 +765,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1152,6 +1158,8 @@ def count_tokens( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1440,6 +1448,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1719,6 +1729,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1998,6 +2010,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -2387,6 +2401,8 @@ async def count_tokens( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. diff --git a/src/anthropic/resources/beta/models.py b/src/anthropic/resources/beta/models.py index 04d620c50..51e2af953 100644 --- a/src/anthropic/resources/beta/models.py +++ b/src/anthropic/resources/beta/models.py @@ -2,17 +2,20 @@ from __future__ import annotations +from typing import List + import httpx from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import maybe_transform +from ..._utils import is_given, maybe_transform, strip_not_given from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...pagination import SyncPage, AsyncPage from ...types.beta import model_list_params from ..._base_client import AsyncPaginator, make_request_options +from ...types.anthropic_beta_param import AnthropicBetaParam from ...types.beta.beta_model_info import BetaModelInfo __all__ = ["Models", "AsyncModels"] @@ -42,6 +45,7 @@ def retrieve( self, model_id: str, *, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -58,6 +62,8 @@ def retrieve( Args: model_id: Model identifier or alias. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -68,6 +74,10 @@ def retrieve( """ if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get( f"/v1/models/{model_id}?beta=true", options=make_request_options( @@ -82,6 +92,7 @@ def list( after_id: str | NotGiven = NOT_GIVEN, before_id: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -106,6 +117,8 @@ def list( Defaults to `20`. Ranges from `1` to `1000`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -114,6 +127,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get_api_list( "/v1/models?beta=true", page=SyncPage[BetaModelInfo], @@ -159,6 +176,7 @@ async def retrieve( self, model_id: str, *, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -175,6 +193,8 @@ async def retrieve( Args: model_id: Model identifier or alias. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -185,6 +205,10 @@ async def retrieve( """ if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return await self._get( f"/v1/models/{model_id}?beta=true", options=make_request_options( @@ -199,6 +223,7 @@ def list( after_id: str | NotGiven = NOT_GIVEN, before_id: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -223,6 +248,8 @@ def list( Defaults to `20`. Ranges from `1` to `1000`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -231,6 +258,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get_api_list( "/v1/models?beta=true", page=AsyncPage[BetaModelInfo], diff --git a/src/anthropic/resources/completions.py b/src/anthropic/resources/completions.py index ae45f4ad5..913ec43cb 100644 --- a/src/anthropic/resources/completions.py +++ b/src/anthropic/resources/completions.py @@ -10,7 +10,7 @@ from .. import _legacy_response from ..types import completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import is_given, required_args, maybe_transform, async_maybe_transform +from .._utils import is_given, required_args, maybe_transform, strip_not_given, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -20,6 +20,7 @@ from ..types.completion import Completion from ..types.model_param import ModelParam from ..types.metadata_param import MetadataParam +from ..types.anthropic_beta_param import AnthropicBetaParam __all__ = ["Completions", "AsyncCompletions"] @@ -57,6 +58,7 @@ def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -138,6 +140,8 @@ def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -161,6 +165,7 @@ def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -242,6 +247,8 @@ def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -265,6 +272,7 @@ def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -346,6 +354,8 @@ def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -369,6 +379,7 @@ def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -378,6 +389,10 @@ def create( ) -> Completion | Stream[Completion]: if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT: timeout = 600 + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._post( "/v1/complete", body=maybe_transform( @@ -438,6 +453,7 @@ async def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -519,6 +535,8 @@ async def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -542,6 +560,7 @@ async def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -623,6 +642,8 @@ async def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -646,6 +667,7 @@ async def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -727,6 +749,8 @@ async def create( Recommended for advanced use cases only. You usually only need to use `temperature`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -750,6 +774,7 @@ async def create( temperature: float | NotGiven = NOT_GIVEN, top_k: int | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -759,6 +784,10 @@ async def create( ) -> Completion | AsyncStream[Completion]: if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT: timeout = 600 + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return await self._post( "/v1/complete", body=await async_maybe_transform( diff --git a/src/anthropic/resources/messages/messages.py b/src/anthropic/resources/messages/messages.py index a9ae18e6d..59088a504 100644 --- a/src/anthropic/resources/messages/messages.py +++ b/src/anthropic/resources/messages/messages.py @@ -212,6 +212,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -488,6 +490,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -764,6 +768,8 @@ def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1152,6 +1158,8 @@ def count_tokens( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1426,6 +1434,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1702,6 +1712,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -1978,6 +1990,8 @@ async def create( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. @@ -2365,6 +2379,8 @@ async def count_tokens( the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + There is a limit of 100000 messages in a single request. + model: The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. diff --git a/src/anthropic/resources/models.py b/src/anthropic/resources/models.py index 3469ccf95..64fe67b66 100644 --- a/src/anthropic/resources/models.py +++ b/src/anthropic/resources/models.py @@ -2,18 +2,21 @@ from __future__ import annotations +from typing import List + import httpx from .. import _legacy_response from ..types import model_list_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import maybe_transform +from .._utils import is_given, maybe_transform, strip_not_given from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..pagination import SyncPage, AsyncPage from .._base_client import AsyncPaginator, make_request_options from ..types.model_info import ModelInfo +from ..types.anthropic_beta_param import AnthropicBetaParam __all__ = ["Models", "AsyncModels"] @@ -42,6 +45,7 @@ def retrieve( self, model_id: str, *, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -58,6 +62,8 @@ def retrieve( Args: model_id: Model identifier or alias. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -68,6 +74,10 @@ def retrieve( """ if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get( f"/v1/models/{model_id}", options=make_request_options( @@ -82,6 +92,7 @@ def list( after_id: str | NotGiven = NOT_GIVEN, before_id: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -106,6 +117,8 @@ def list( Defaults to `20`. Ranges from `1` to `1000`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -114,6 +127,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get_api_list( "/v1/models", page=SyncPage[ModelInfo], @@ -159,6 +176,7 @@ async def retrieve( self, model_id: str, *, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -175,6 +193,8 @@ async def retrieve( Args: model_id: Model identifier or alias. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -185,6 +205,10 @@ async def retrieve( """ if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return await self._get( f"/v1/models/{model_id}", options=make_request_options( @@ -199,6 +223,7 @@ def list( after_id: str | NotGiven = NOT_GIVEN, before_id: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + betas: List[AnthropicBetaParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -223,6 +248,8 @@ def list( Defaults to `20`. Ranges from `1` to `1000`. + betas: Optional header to specify the beta version(s) you want to use. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -231,6 +258,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = { + **strip_not_given({"anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else NOT_GIVEN}), + **(extra_headers or {}), + } return self._get_api_list( "/v1/models", page=AsyncPage[ModelInfo], diff --git a/src/anthropic/types/__init__.py b/src/anthropic/types/__init__.py index 4f04f2764..407f6415f 100644 --- a/src/anthropic/types/__init__.py +++ b/src/anthropic/types/__init__.py @@ -41,6 +41,7 @@ from .tool_union_param import ToolUnionParam as ToolUnionParam from .image_block_param import ImageBlockParam as ImageBlockParam from .model_list_params import ModelListParams as ModelListParams +from .server_tool_usage import ServerToolUsage as ServerToolUsage from .tool_choice_param import ToolChoiceParam as ToolChoiceParam from .beta_billing_error import BetaBillingError as BetaBillingError from .message_stop_event import MessageStopEvent as MessageStopEvent @@ -62,6 +63,7 @@ from .beta_permission_error import BetaPermissionError as BetaPermissionError from .beta_rate_limit_error import BetaRateLimitError as BetaRateLimitError from .message_create_params import MessageCreateParams as MessageCreateParams +from .server_tool_use_block import ServerToolUseBlock as ServerToolUseBlock from .thinking_config_param import ThinkingConfigParam as ThinkingConfigParam from .tool_choice_any_param import ToolChoiceAnyParam as ToolChoiceAnyParam from .citation_char_location import CitationCharLocation as CitationCharLocation @@ -79,6 +81,7 @@ from .raw_message_start_event import RawMessageStartEvent as RawMessageStartEvent from .redacted_thinking_block import RedactedThinkingBlock as RedactedThinkingBlock from .tool_result_block_param import ToolResultBlockParam as ToolResultBlockParam +from .web_search_result_block import WebSearchResultBlock as WebSearchResultBlock from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .content_block_stop_event import ContentBlockStopEvent as ContentBlockStopEvent from .raw_message_stream_event import RawMessageStreamEvent as RawMessageStreamEvent @@ -91,19 +94,34 @@ from .beta_invalid_request_error import BetaInvalidRequestError as BetaInvalidRequestError from .content_block_source_param import ContentBlockSourceParam as ContentBlockSourceParam from .message_count_tokens_params import MessageCountTokensParams as MessageCountTokensParams +from .server_tool_use_block_param import ServerToolUseBlockParam as ServerToolUseBlockParam from .citation_char_location_param import CitationCharLocationParam as CitationCharLocationParam from .citation_page_location_param import CitationPageLocationParam as CitationPageLocationParam from .raw_content_block_stop_event import RawContentBlockStopEvent as RawContentBlockStopEvent +from .web_search_tool_result_block import WebSearchToolResultBlock as WebSearchToolResultBlock +from .web_search_tool_result_error import WebSearchToolResultError as WebSearchToolResultError from .cache_control_ephemeral_param import CacheControlEphemeralParam as CacheControlEphemeralParam from .raw_content_block_delta_event import RawContentBlockDeltaEvent as RawContentBlockDeltaEvent from .raw_content_block_start_event import RawContentBlockStartEvent as RawContentBlockStartEvent from .redacted_thinking_block_param import RedactedThinkingBlockParam as RedactedThinkingBlockParam from .thinking_config_enabled_param import ThinkingConfigEnabledParam as ThinkingConfigEnabledParam +from .web_search_result_block_param import WebSearchResultBlockParam as WebSearchResultBlockParam from .thinking_config_disabled_param import ThinkingConfigDisabledParam as ThinkingConfigDisabledParam +from .web_search_tool_20250305_param import WebSearchTool20250305Param as WebSearchTool20250305Param from .citation_content_block_location import CitationContentBlockLocation as CitationContentBlockLocation from .message_count_tokens_tool_param import MessageCountTokensToolParam as MessageCountTokensToolParam from .tool_text_editor_20250124_param import ToolTextEditor20250124Param as ToolTextEditor20250124Param from .content_block_source_content_param import ContentBlockSourceContentParam as ContentBlockSourceContentParam +from .web_search_tool_result_block_param import WebSearchToolResultBlockParam as WebSearchToolResultBlockParam +from .web_search_tool_request_error_param import WebSearchToolRequestErrorParam as WebSearchToolRequestErrorParam +from .citations_web_search_result_location import CitationsWebSearchResultLocation as CitationsWebSearchResultLocation +from .web_search_tool_result_block_content import WebSearchToolResultBlockContent as WebSearchToolResultBlockContent from .citation_content_block_location_param import ( CitationContentBlockLocationParam as CitationContentBlockLocationParam, ) +from .citation_web_search_result_location_param import ( + CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam, +) +from .web_search_tool_result_block_param_content_param import ( + WebSearchToolResultBlockParamContentParam as WebSearchToolResultBlockParamContentParam, +) diff --git a/src/anthropic/types/beta/__init__.py b/src/anthropic/types/beta/__init__.py index ea76f2a98..054386c8b 100644 --- a/src/anthropic/types/beta/__init__.py +++ b/src/anthropic/types/beta/__init__.py @@ -24,6 +24,7 @@ from .beta_tool_union_param import BetaToolUnionParam as BetaToolUnionParam from .message_create_params import MessageCreateParams as MessageCreateParams from .beta_image_block_param import BetaImageBlockParam as BetaImageBlockParam +from .beta_server_tool_usage import BetaServerToolUsage as BetaServerToolUsage from .beta_tool_choice_param import BetaToolChoiceParam as BetaToolChoiceParam from .beta_content_block_param import BetaContentBlockParam as BetaContentBlockParam from .beta_message_delta_usage import BetaMessageDeltaUsage as BetaMessageDeltaUsage @@ -32,6 +33,7 @@ from .beta_thinking_block_param import BetaThinkingBlockParam as BetaThinkingBlockParam from .beta_tool_use_block_param import BetaToolUseBlockParam as BetaToolUseBlockParam from .beta_url_pdf_source_param import BetaURLPDFSourceParam as BetaURLPDFSourceParam +from .beta_server_tool_use_block import BetaServerToolUseBlock as BetaServerToolUseBlock from .beta_thinking_config_param import BetaThinkingConfigParam as BetaThinkingConfigParam from .beta_tool_choice_any_param import BetaToolChoiceAnyParam as BetaToolChoiceAnyParam from .beta_base64_pdf_block_param import BetaBase64PDFBlockParam as BetaBase64PDFBlockParam @@ -51,20 +53,26 @@ from .beta_raw_message_start_event import BetaRawMessageStartEvent as BetaRawMessageStartEvent from .beta_redacted_thinking_block import BetaRedactedThinkingBlock as BetaRedactedThinkingBlock from .beta_tool_result_block_param import BetaToolResultBlockParam as BetaToolResultBlockParam +from .beta_web_search_result_block import BetaWebSearchResultBlock as BetaWebSearchResultBlock from .beta_raw_message_stream_event import BetaRawMessageStreamEvent as BetaRawMessageStreamEvent from .beta_tool_bash_20241022_param import BetaToolBash20241022Param as BetaToolBash20241022Param from .beta_tool_bash_20250124_param import BetaToolBash20250124Param as BetaToolBash20250124Param from .beta_base64_image_source_param import BetaBase64ImageSourceParam as BetaBase64ImageSourceParam from .beta_content_block_source_param import BetaContentBlockSourceParam as BetaContentBlockSourceParam +from .beta_server_tool_use_block_param import BetaServerToolUseBlockParam as BetaServerToolUseBlockParam from .beta_citation_char_location_param import BetaCitationCharLocationParam as BetaCitationCharLocationParam from .beta_citation_page_location_param import BetaCitationPageLocationParam as BetaCitationPageLocationParam from .beta_raw_content_block_stop_event import BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock +from .beta_web_search_tool_result_error import BetaWebSearchToolResultError as BetaWebSearchToolResultError from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam as BetaCacheControlEphemeralParam from .beta_raw_content_block_delta_event import BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent from .beta_raw_content_block_start_event import BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent from .beta_redacted_thinking_block_param import BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam from .beta_thinking_config_enabled_param import BetaThinkingConfigEnabledParam as BetaThinkingConfigEnabledParam +from .beta_web_search_result_block_param import BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam from .beta_thinking_config_disabled_param import BetaThinkingConfigDisabledParam as BetaThinkingConfigDisabledParam +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param as BetaWebSearchTool20250305Param from .beta_citation_content_block_location import BetaCitationContentBlockLocation as BetaCitationContentBlockLocation from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param as BetaToolTextEditor20241022Param from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param as BetaToolTextEditor20250124Param @@ -73,6 +81,24 @@ from .beta_content_block_source_content_param import ( BetaContentBlockSourceContentParam as BetaContentBlockSourceContentParam, ) +from .beta_web_search_tool_result_block_param import ( + BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam, +) +from .beta_web_search_tool_request_error_param import ( + BetaWebSearchToolRequestErrorParam as BetaWebSearchToolRequestErrorParam, +) +from .beta_citations_web_search_result_location import ( + BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation, +) +from .beta_web_search_tool_result_block_content import ( + BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent, +) from .beta_citation_content_block_location_param import ( BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam, ) +from .beta_citation_web_search_result_location_param import ( + BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam, +) +from .beta_web_search_tool_result_block_param_content_param import ( + BetaWebSearchToolResultBlockParamContentParam as BetaWebSearchToolResultBlockParamContentParam, +) diff --git a/src/anthropic/types/beta/beta_base64_pdf_block_param.py b/src/anthropic/types/beta/beta_base64_pdf_block_param.py index 16f51a9d9..b9dd3ee13 100644 --- a/src/anthropic/types/beta/beta_base64_pdf_block_param.py +++ b/src/anthropic/types/beta/beta_base64_pdf_block_param.py @@ -25,6 +25,7 @@ class BetaBase64PDFBlockParam(TypedDict, total=False): type: Required[Literal["document"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" citations: BetaCitationsConfigParam diff --git a/src/anthropic/types/beta/beta_citation_web_search_result_location_param.py b/src/anthropic/types/beta/beta_citation_web_search_result_location_param.py new file mode 100644 index 000000000..90625af1b --- /dev/null +++ b/src/anthropic/types/beta/beta_citation_web_search_result_location_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCitationWebSearchResultLocationParam"] + + +class BetaCitationWebSearchResultLocationParam(TypedDict, total=False): + cited_text: Required[str] + + encrypted_index: Required[str] + + title: Required[Optional[str]] + + type: Required[Literal["web_search_result_location"]] + + url: Required[str] diff --git a/src/anthropic/types/beta/beta_citations_delta.py b/src/anthropic/types/beta/beta_citations_delta.py index 2c6c02b2c..cd8f60719 100644 --- a/src/anthropic/types/beta/beta_citations_delta.py +++ b/src/anthropic/types/beta/beta_citations_delta.py @@ -8,11 +8,17 @@ from .beta_citation_char_location import BetaCitationCharLocation from .beta_citation_page_location import BetaCitationPageLocation from .beta_citation_content_block_location import BetaCitationContentBlockLocation +from .beta_citations_web_search_result_location import BetaCitationsWebSearchResultLocation __all__ = ["BetaCitationsDelta", "Citation"] Citation: TypeAlias = Annotated[ - Union[BetaCitationCharLocation, BetaCitationPageLocation, BetaCitationContentBlockLocation], + Union[ + BetaCitationCharLocation, + BetaCitationPageLocation, + BetaCitationContentBlockLocation, + BetaCitationsWebSearchResultLocation, + ], PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/beta/beta_citations_web_search_result_location.py b/src/anthropic/types/beta/beta_citations_web_search_result_location.py new file mode 100644 index 000000000..111ffe7c0 --- /dev/null +++ b/src/anthropic/types/beta/beta_citations_web_search_result_location.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCitationsWebSearchResultLocation"] + + +class BetaCitationsWebSearchResultLocation(BaseModel): + cited_text: str + + encrypted_index: str + + title: Optional[str] = None + + type: Literal["web_search_result_location"] + + url: str diff --git a/src/anthropic/types/beta/beta_content_block.py b/src/anthropic/types/beta/beta_content_block.py index 7cf9736e0..3925102f1 100644 --- a/src/anthropic/types/beta/beta_content_block.py +++ b/src/anthropic/types/beta/beta_content_block.py @@ -7,11 +7,20 @@ from .beta_text_block import BetaTextBlock from .beta_thinking_block import BetaThinkingBlock from .beta_tool_use_block import BetaToolUseBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock from .beta_redacted_thinking_block import BetaRedactedThinkingBlock +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock __all__ = ["BetaContentBlock"] BetaContentBlock: TypeAlias = Annotated[ - Union[BetaTextBlock, BetaToolUseBlock, BetaThinkingBlock, BetaRedactedThinkingBlock], + Union[ + BetaTextBlock, + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaWebSearchToolResultBlock, + BetaThinkingBlock, + BetaRedactedThinkingBlock, + ], PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/beta/beta_content_block_param.py b/src/anthropic/types/beta/beta_content_block_param.py index 1768f321e..5b9e2f011 100644 --- a/src/anthropic/types/beta/beta_content_block_param.py +++ b/src/anthropic/types/beta/beta_content_block_param.py @@ -11,7 +11,9 @@ from .beta_tool_use_block_param import BetaToolUseBlockParam from .beta_base64_pdf_block_param import BetaBase64PDFBlockParam from .beta_tool_result_block_param import BetaToolResultBlockParam +from .beta_server_tool_use_block_param import BetaServerToolUseBlockParam from .beta_redacted_thinking_block_param import BetaRedactedThinkingBlockParam +from .beta_web_search_tool_result_block_param import BetaWebSearchToolResultBlockParam __all__ = ["BetaContentBlockParam"] @@ -19,6 +21,8 @@ BetaTextBlockParam, BetaImageBlockParam, BetaToolUseBlockParam, + BetaServerToolUseBlockParam, + BetaWebSearchToolResultBlockParam, BetaToolResultBlockParam, BetaBase64PDFBlockParam, BetaThinkingBlockParam, diff --git a/src/anthropic/types/beta/beta_image_block_param.py b/src/anthropic/types/beta/beta_image_block_param.py index ddb9d4c07..d7759b2c1 100644 --- a/src/anthropic/types/beta/beta_image_block_param.py +++ b/src/anthropic/types/beta/beta_image_block_param.py @@ -20,3 +20,4 @@ class BetaImageBlockParam(TypedDict, total=False): type: Required[Literal["image"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_message_delta_usage.py b/src/anthropic/types/beta/beta_message_delta_usage.py index 4a74731af..11c815d8e 100644 --- a/src/anthropic/types/beta/beta_message_delta_usage.py +++ b/src/anthropic/types/beta/beta_message_delta_usage.py @@ -1,10 +1,25 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import Optional + from ..._models import BaseModel +from .beta_server_tool_usage import BetaServerToolUsage __all__ = ["BetaMessageDeltaUsage"] class BetaMessageDeltaUsage(BaseModel): + cache_creation_input_tokens: Optional[int] = None + """The cumulative number of input tokens used to create the cache entry.""" + + cache_read_input_tokens: Optional[int] = None + """The cumulative number of input tokens read from the cache.""" + + input_tokens: Optional[int] = None + """The cumulative number of input tokens which were used.""" + output_tokens: int """The cumulative number of output tokens which were used.""" + + server_tool_use: Optional[BetaServerToolUsage] = None + """The number of server tool requests.""" diff --git a/src/anthropic/types/beta/beta_raw_content_block_start_event.py b/src/anthropic/types/beta/beta_raw_content_block_start_event.py index 086c216c8..6c5ff162c 100644 --- a/src/anthropic/types/beta/beta_raw_content_block_start_event.py +++ b/src/anthropic/types/beta/beta_raw_content_block_start_event.py @@ -8,12 +8,21 @@ from .beta_text_block import BetaTextBlock from .beta_thinking_block import BetaThinkingBlock from .beta_tool_use_block import BetaToolUseBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock from .beta_redacted_thinking_block import BetaRedactedThinkingBlock +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock __all__ = ["BetaRawContentBlockStartEvent", "ContentBlock"] ContentBlock: TypeAlias = Annotated[ - Union[BetaTextBlock, BetaToolUseBlock, BetaThinkingBlock, BetaRedactedThinkingBlock], + Union[ + BetaTextBlock, + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaWebSearchToolResultBlock, + BetaThinkingBlock, + BetaRedactedThinkingBlock, + ], PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/beta/beta_server_tool_usage.py b/src/anthropic/types/beta/beta_server_tool_usage.py new file mode 100644 index 000000000..8a17085f8 --- /dev/null +++ b/src/anthropic/types/beta/beta_server_tool_usage.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaServerToolUsage"] + + +class BetaServerToolUsage(BaseModel): + web_search_requests: int + """The number of web search tool requests.""" diff --git a/src/anthropic/types/beta/beta_server_tool_use_block.py b/src/anthropic/types/beta/beta_server_tool_use_block.py new file mode 100644 index 000000000..f0703f4b7 --- /dev/null +++ b/src/anthropic/types/beta/beta_server_tool_use_block.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaServerToolUseBlock"] + + +class BetaServerToolUseBlock(BaseModel): + id: str + + input: object + + name: Literal["web_search"] + + type: Literal["server_tool_use"] diff --git a/src/anthropic/types/beta/beta_server_tool_use_block_param.py b/src/anthropic/types/beta/beta_server_tool_use_block_param.py new file mode 100644 index 000000000..e1edce865 --- /dev/null +++ b/src/anthropic/types/beta/beta_server_tool_use_block_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaServerToolUseBlockParam"] + + +class BetaServerToolUseBlockParam(TypedDict, total=False): + id: Required[str] + + input: Required[object] + + name: Required[Literal["web_search"]] + + type: Required[Literal["server_tool_use"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_stop_reason.py b/src/anthropic/types/beta/beta_stop_reason.py index 87200ecf8..f9eff6e27 100644 --- a/src/anthropic/types/beta/beta_stop_reason.py +++ b/src/anthropic/types/beta/beta_stop_reason.py @@ -4,4 +4,4 @@ __all__ = ["BetaStopReason"] -BetaStopReason: TypeAlias = Literal["end_turn", "max_tokens", "stop_sequence", "tool_use"] +BetaStopReason: TypeAlias = Literal["end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", "refusal"] diff --git a/src/anthropic/types/beta/beta_text_block_param.py b/src/anthropic/types/beta/beta_text_block_param.py index e40b03a55..066f56151 100644 --- a/src/anthropic/types/beta/beta_text_block_param.py +++ b/src/anthropic/types/beta/beta_text_block_param.py @@ -17,5 +17,6 @@ class BetaTextBlockParam(TypedDict, total=False): type: Required[Literal["text"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" citations: Optional[Iterable[BetaTextCitationParam]] diff --git a/src/anthropic/types/beta/beta_text_citation.py b/src/anthropic/types/beta/beta_text_citation.py index 538878b69..d0b697ade 100644 --- a/src/anthropic/types/beta/beta_text_citation.py +++ b/src/anthropic/types/beta/beta_text_citation.py @@ -7,10 +7,16 @@ from .beta_citation_char_location import BetaCitationCharLocation from .beta_citation_page_location import BetaCitationPageLocation from .beta_citation_content_block_location import BetaCitationContentBlockLocation +from .beta_citations_web_search_result_location import BetaCitationsWebSearchResultLocation __all__ = ["BetaTextCitation"] BetaTextCitation: TypeAlias = Annotated[ - Union[BetaCitationCharLocation, BetaCitationPageLocation, BetaCitationContentBlockLocation], + Union[ + BetaCitationCharLocation, + BetaCitationPageLocation, + BetaCitationContentBlockLocation, + BetaCitationsWebSearchResultLocation, + ], PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/beta/beta_text_citation_param.py b/src/anthropic/types/beta/beta_text_citation_param.py index b04c33052..9a07926f5 100644 --- a/src/anthropic/types/beta/beta_text_citation_param.py +++ b/src/anthropic/types/beta/beta_text_citation_param.py @@ -8,9 +8,13 @@ from .beta_citation_char_location_param import BetaCitationCharLocationParam from .beta_citation_page_location_param import BetaCitationPageLocationParam from .beta_citation_content_block_location_param import BetaCitationContentBlockLocationParam +from .beta_citation_web_search_result_location_param import BetaCitationWebSearchResultLocationParam __all__ = ["BetaTextCitationParam"] BetaTextCitationParam: TypeAlias = Union[ - BetaCitationCharLocationParam, BetaCitationPageLocationParam, BetaCitationContentBlockLocationParam + BetaCitationCharLocationParam, + BetaCitationPageLocationParam, + BetaCitationContentBlockLocationParam, + BetaCitationWebSearchResultLocationParam, ] diff --git a/src/anthropic/types/beta/beta_tool_bash_20241022_param.py b/src/anthropic/types/beta/beta_tool_bash_20241022_param.py index 82ed02b3b..51576c581 100644 --- a/src/anthropic/types/beta/beta_tool_bash_20241022_param.py +++ b/src/anthropic/types/beta/beta_tool_bash_20241022_param.py @@ -14,9 +14,10 @@ class BetaToolBash20241022Param(TypedDict, total=False): name: Required[Literal["bash"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["bash_20241022"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_tool_bash_20250124_param.py b/src/anthropic/types/beta/beta_tool_bash_20250124_param.py index 3fcab4402..d1af1c359 100644 --- a/src/anthropic/types/beta/beta_tool_bash_20250124_param.py +++ b/src/anthropic/types/beta/beta_tool_bash_20250124_param.py @@ -14,9 +14,10 @@ class BetaToolBash20250124Param(TypedDict, total=False): name: Required[Literal["bash"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["bash_20250124"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_tool_computer_use_20241022_param.py b/src/anthropic/types/beta/beta_tool_computer_use_20241022_param.py index b95472be3..4ea036ac2 100644 --- a/src/anthropic/types/beta/beta_tool_computer_use_20241022_param.py +++ b/src/anthropic/types/beta/beta_tool_computer_use_20241022_param.py @@ -20,12 +20,13 @@ class BetaToolComputerUse20241022Param(TypedDict, total=False): name: Required[Literal["computer"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["computer_20241022"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" display_number: Optional[int] """The X11 display number (e.g. 0, 1) for the display.""" diff --git a/src/anthropic/types/beta/beta_tool_computer_use_20250124_param.py b/src/anthropic/types/beta/beta_tool_computer_use_20250124_param.py index 089d67aa6..e68f462de 100644 --- a/src/anthropic/types/beta/beta_tool_computer_use_20250124_param.py +++ b/src/anthropic/types/beta/beta_tool_computer_use_20250124_param.py @@ -20,12 +20,13 @@ class BetaToolComputerUse20250124Param(TypedDict, total=False): name: Required[Literal["computer"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["computer_20250124"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" display_number: Optional[int] """The X11 display number (e.g. 0, 1) for the display.""" diff --git a/src/anthropic/types/beta/beta_tool_param.py b/src/anthropic/types/beta/beta_tool_param.py index da9d43bcc..19dd5b92f 100644 --- a/src/anthropic/types/beta/beta_tool_param.py +++ b/src/anthropic/types/beta/beta_tool_param.py @@ -30,10 +30,11 @@ class BetaToolParam(TypedDict, total=False): name: Required[str] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" description: str """Description of what this tool does. diff --git a/src/anthropic/types/beta/beta_tool_result_block_param.py b/src/anthropic/types/beta/beta_tool_result_block_param.py index 9418b650e..eb712a3fe 100644 --- a/src/anthropic/types/beta/beta_tool_result_block_param.py +++ b/src/anthropic/types/beta/beta_tool_result_block_param.py @@ -20,6 +20,7 @@ class BetaToolResultBlockParam(TypedDict, total=False): type: Required[Literal["tool_result"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" content: Union[str, Iterable[Content]] diff --git a/src/anthropic/types/beta/beta_tool_text_editor_20241022_param.py b/src/anthropic/types/beta/beta_tool_text_editor_20241022_param.py index 86c932781..d6e72f87d 100644 --- a/src/anthropic/types/beta/beta_tool_text_editor_20241022_param.py +++ b/src/anthropic/types/beta/beta_tool_text_editor_20241022_param.py @@ -14,9 +14,10 @@ class BetaToolTextEditor20241022Param(TypedDict, total=False): name: Required[Literal["str_replace_editor"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["text_editor_20241022"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_tool_text_editor_20250124_param.py b/src/anthropic/types/beta/beta_tool_text_editor_20250124_param.py index 07b86bd58..bcf35dc3b 100644 --- a/src/anthropic/types/beta/beta_tool_text_editor_20250124_param.py +++ b/src/anthropic/types/beta/beta_tool_text_editor_20250124_param.py @@ -14,9 +14,10 @@ class BetaToolTextEditor20250124Param(TypedDict, total=False): name: Required[Literal["str_replace_editor"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["text_editor_20250124"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_tool_union_param.py b/src/anthropic/types/beta/beta_tool_union_param.py index d37480daf..95bb50496 100644 --- a/src/anthropic/types/beta/beta_tool_union_param.py +++ b/src/anthropic/types/beta/beta_tool_union_param.py @@ -8,6 +8,7 @@ from .beta_tool_param import BetaToolParam from .beta_tool_bash_20241022_param import BetaToolBash20241022Param from .beta_tool_bash_20250124_param import BetaToolBash20250124Param +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param from .beta_tool_computer_use_20241022_param import BetaToolComputerUse20241022Param @@ -23,4 +24,5 @@ BetaToolComputerUse20250124Param, BetaToolBash20250124Param, BetaToolTextEditor20250124Param, + BetaWebSearchTool20250305Param, ] diff --git a/src/anthropic/types/beta/beta_tool_use_block_param.py b/src/anthropic/types/beta/beta_tool_use_block_param.py index 603dc85fc..8eb09cf24 100644 --- a/src/anthropic/types/beta/beta_tool_use_block_param.py +++ b/src/anthropic/types/beta/beta_tool_use_block_param.py @@ -20,3 +20,4 @@ class BetaToolUseBlockParam(TypedDict, total=False): type: Required[Literal["tool_use"]] cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_usage.py b/src/anthropic/types/beta/beta_usage.py index 0d956c707..59f775037 100644 --- a/src/anthropic/types/beta/beta_usage.py +++ b/src/anthropic/types/beta/beta_usage.py @@ -3,6 +3,7 @@ from typing import Optional from ..._models import BaseModel +from .beta_server_tool_usage import BetaServerToolUsage __all__ = ["BetaUsage"] @@ -19,3 +20,6 @@ class BetaUsage(BaseModel): output_tokens: int """The number of output tokens which were used.""" + + server_tool_use: Optional[BetaServerToolUsage] = None + """The number of server tool requests.""" diff --git a/src/anthropic/types/beta/beta_web_search_result_block.py b/src/anthropic/types/beta/beta_web_search_result_block.py new file mode 100644 index 000000000..35ed87cef --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebSearchResultBlock"] + + +class BetaWebSearchResultBlock(BaseModel): + encrypted_content: str + + page_age: Optional[str] = None + + title: str + + type: Literal["web_search_result"] + + url: str diff --git a/src/anthropic/types/beta/beta_web_search_result_block_param.py b/src/anthropic/types/beta/beta_web_search_result_block_param.py new file mode 100644 index 000000000..4a829ddbf --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_result_block_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaWebSearchResultBlockParam"] + + +class BetaWebSearchResultBlockParam(TypedDict, total=False): + encrypted_content: Required[str] + + title: Required[str] + + type: Required[Literal["web_search_result"]] + + url: Required[str] + + page_age: Optional[str] diff --git a/src/anthropic/types/beta/beta_web_search_tool_20250305_param.py b/src/anthropic/types/beta/beta_web_search_tool_20250305_param.py new file mode 100644 index 000000000..740c37b55 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_20250305_param.py @@ -0,0 +1,64 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebSearchTool20250305Param", "UserLocation"] + + +class UserLocation(TypedDict, total=False): + type: Required[Literal["approximate"]] + + city: Optional[str] + """The city of the user.""" + + country: Optional[str] + """ + The two letter + [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the + user. + """ + + region: Optional[str] + """The region of the user.""" + + timezone: Optional[str] + """The [IANA timezone](https://nodatime.org/TimeZones) of the user.""" + + +class BetaWebSearchTool20250305Param(TypedDict, total=False): + name: Required[Literal["web_search"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_search_20250305"]] + + allowed_domains: Optional[List[str]] + """If provided, only these domains will be included in results. + + Cannot be used alongside `blocked_domains`. + """ + + blocked_domains: Optional[List[str]] + """If provided, these domains will never appear in results. + + Cannot be used alongside `allowed_domains`. + """ + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + user_location: Optional[UserLocation] + """Parameters for the user's location. + + Used to provide more relevant search results. + """ diff --git a/src/anthropic/types/beta/beta_web_search_tool_request_error_param.py b/src/anthropic/types/beta/beta_web_search_tool_request_error_param.py new file mode 100644 index 000000000..1a0181eae --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_request_error_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaWebSearchToolRequestErrorParam"] + + +class BetaWebSearchToolRequestErrorParam(TypedDict, total=False): + error_code: Required[ + Literal["invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long"] + ] + + type: Required[Literal["web_search_tool_result_error"]] diff --git a/src/anthropic/types/beta/beta_web_search_tool_result_block.py b/src/anthropic/types/beta/beta_web_search_tool_result_block.py new file mode 100644 index 000000000..f1501e750 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_result_block.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_web_search_tool_result_block_content import BetaWebSearchToolResultBlockContent + +__all__ = ["BetaWebSearchToolResultBlock"] + + +class BetaWebSearchToolResultBlock(BaseModel): + content: BetaWebSearchToolResultBlockContent + + tool_use_id: str + + type: Literal["web_search_tool_result"] diff --git a/src/anthropic/types/beta/beta_web_search_tool_result_block_content.py b/src/anthropic/types/beta/beta_web_search_tool_result_block_content.py new file mode 100644 index 000000000..2a03429f9 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_result_block_content.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import TypeAlias + +from .beta_web_search_result_block import BetaWebSearchResultBlock +from .beta_web_search_tool_result_error import BetaWebSearchToolResultError + +__all__ = ["BetaWebSearchToolResultBlockContent"] + +BetaWebSearchToolResultBlockContent: TypeAlias = Union[BetaWebSearchToolResultError, List[BetaWebSearchResultBlock]] diff --git a/src/anthropic/types/beta/beta_web_search_tool_result_block_param.py b/src/anthropic/types/beta/beta_web_search_tool_result_block_param.py new file mode 100644 index 000000000..001d43978 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_result_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_web_search_tool_result_block_param_content_param import BetaWebSearchToolResultBlockParamContentParam + +__all__ = ["BetaWebSearchToolResultBlockParam"] + + +class BetaWebSearchToolResultBlockParam(TypedDict, total=False): + content: Required[BetaWebSearchToolResultBlockParamContentParam] + + tool_use_id: Required[str] + + type: Required[Literal["web_search_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py b/src/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py new file mode 100644 index 000000000..17edadb37 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypeAlias + +from .beta_web_search_result_block_param import BetaWebSearchResultBlockParam +from .beta_web_search_tool_request_error_param import BetaWebSearchToolRequestErrorParam + +__all__ = ["BetaWebSearchToolResultBlockParamContentParam"] + +BetaWebSearchToolResultBlockParamContentParam: TypeAlias = Union[ + Iterable[BetaWebSearchResultBlockParam], BetaWebSearchToolRequestErrorParam +] diff --git a/src/anthropic/types/beta/beta_web_search_tool_result_error.py b/src/anthropic/types/beta/beta_web_search_tool_result_error.py new file mode 100644 index 000000000..b1aee3be5 --- /dev/null +++ b/src/anthropic/types/beta/beta_web_search_tool_result_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebSearchToolResultError"] + + +class BetaWebSearchToolResultError(BaseModel): + error_code: Literal["invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long"] + + type: Literal["web_search_tool_result_error"] diff --git a/src/anthropic/types/beta/message_count_tokens_params.py b/src/anthropic/types/beta/message_count_tokens_params.py index 056c42891..7849e74c4 100644 --- a/src/anthropic/types/beta/message_count_tokens_params.py +++ b/src/anthropic/types/beta/message_count_tokens_params.py @@ -15,6 +15,7 @@ from .beta_thinking_config_param import BetaThinkingConfigParam from .beta_tool_bash_20241022_param import BetaToolBash20241022Param from .beta_tool_bash_20250124_param import BetaToolBash20250124Param +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param from .beta_tool_computer_use_20241022_param import BetaToolComputerUse20241022Param @@ -111,6 +112,8 @@ class MessageCountTokensParams(TypedDict, total=False): [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + + There is a limit of 100000 messages in a single request. """ model: Required[ModelParam] @@ -231,4 +234,5 @@ class MessageCountTokensParams(TypedDict, total=False): BetaToolComputerUse20250124Param, BetaToolBash20250124Param, BetaToolTextEditor20250124Param, + BetaWebSearchTool20250305Param, ] diff --git a/src/anthropic/types/beta/message_create_params.py b/src/anthropic/types/beta/message_create_params.py index e05f92daa..1b79baa11 100644 --- a/src/anthropic/types/beta/message_create_params.py +++ b/src/anthropic/types/beta/message_create_params.py @@ -116,6 +116,8 @@ class MessageCreateParamsBase(TypedDict, total=False): [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + + There is a limit of 100000 messages in a single request. """ model: Required[ModelParam] diff --git a/src/anthropic/types/beta/model_list_params.py b/src/anthropic/types/beta/model_list_params.py index b16d22a30..f353e0772 100644 --- a/src/anthropic/types/beta/model_list_params.py +++ b/src/anthropic/types/beta/model_list_params.py @@ -2,7 +2,11 @@ from __future__ import annotations -from typing_extensions import TypedDict +from typing import List +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam __all__ = ["ModelListParams"] @@ -25,3 +29,6 @@ class ModelListParams(TypedDict, total=False): Defaults to `20`. Ranges from `1` to `1000`. """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/src/anthropic/types/citation_web_search_result_location_param.py b/src/anthropic/types/citation_web_search_result_location_param.py new file mode 100644 index 000000000..dd46e59cf --- /dev/null +++ b/src/anthropic/types/citation_web_search_result_location_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["CitationWebSearchResultLocationParam"] + + +class CitationWebSearchResultLocationParam(TypedDict, total=False): + cited_text: Required[str] + + encrypted_index: Required[str] + + title: Required[Optional[str]] + + type: Required[Literal["web_search_result_location"]] + + url: Required[str] diff --git a/src/anthropic/types/citations_delta.py b/src/anthropic/types/citations_delta.py index 3eab03d18..87248edc2 100644 --- a/src/anthropic/types/citations_delta.py +++ b/src/anthropic/types/citations_delta.py @@ -8,11 +8,13 @@ from .citation_char_location import CitationCharLocation from .citation_page_location import CitationPageLocation from .citation_content_block_location import CitationContentBlockLocation +from .citations_web_search_result_location import CitationsWebSearchResultLocation __all__ = ["CitationsDelta", "Citation"] Citation: TypeAlias = Annotated[ - Union[CitationCharLocation, CitationPageLocation, CitationContentBlockLocation], PropertyInfo(discriminator="type") + Union[CitationCharLocation, CitationPageLocation, CitationContentBlockLocation, CitationsWebSearchResultLocation], + PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/citations_web_search_result_location.py b/src/anthropic/types/citations_web_search_result_location.py new file mode 100644 index 000000000..02a113caf --- /dev/null +++ b/src/anthropic/types/citations_web_search_result_location.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["CitationsWebSearchResultLocation"] + + +class CitationsWebSearchResultLocation(BaseModel): + cited_text: str + + encrypted_index: str + + title: Optional[str] = None + + type: Literal["web_search_result_location"] + + url: str diff --git a/src/anthropic/types/completion_create_params.py b/src/anthropic/types/completion_create_params.py index 0eb25725f..cc49c3d73 100644 --- a/src/anthropic/types/completion_create_params.py +++ b/src/anthropic/types/completion_create_params.py @@ -3,10 +3,12 @@ from __future__ import annotations from typing import List, Union -from typing_extensions import Literal, Required, TypeAlias, TypedDict +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict +from .._utils import PropertyInfo from .model_param import ModelParam from .metadata_param import MetadataParam +from .anthropic_beta_param import AnthropicBetaParam __all__ = [ "CompletionRequestStreamingMetadata", @@ -95,6 +97,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): `temperature`. """ + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + Metadata: TypeAlias = MetadataParam """This is deprecated, `MetadataParam` should be used instead""" diff --git a/src/anthropic/types/content_block.py b/src/anthropic/types/content_block.py index 1bc77596e..70d6200bb 100644 --- a/src/anthropic/types/content_block.py +++ b/src/anthropic/types/content_block.py @@ -7,10 +7,13 @@ from .text_block import TextBlock from .thinking_block import ThinkingBlock from .tool_use_block import ToolUseBlock +from .server_tool_use_block import ServerToolUseBlock from .redacted_thinking_block import RedactedThinkingBlock +from .web_search_tool_result_block import WebSearchToolResultBlock __all__ = ["ContentBlock"] ContentBlock: TypeAlias = Annotated[ - Union[TextBlock, ToolUseBlock, ThinkingBlock, RedactedThinkingBlock], PropertyInfo(discriminator="type") + Union[TextBlock, ToolUseBlock, ServerToolUseBlock, WebSearchToolResultBlock, ThinkingBlock, RedactedThinkingBlock], + PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/content_block_param.py b/src/anthropic/types/content_block_param.py index 97f132e76..536ae15f5 100644 --- a/src/anthropic/types/content_block_param.py +++ b/src/anthropic/types/content_block_param.py @@ -11,7 +11,9 @@ from .thinking_block_param import ThinkingBlockParam from .tool_use_block_param import ToolUseBlockParam from .tool_result_block_param import ToolResultBlockParam +from .server_tool_use_block_param import ServerToolUseBlockParam from .redacted_thinking_block_param import RedactedThinkingBlockParam +from .web_search_tool_result_block_param import WebSearchToolResultBlockParam __all__ = ["ContentBlockParam"] @@ -19,6 +21,8 @@ TextBlockParam, ImageBlockParam, ToolUseBlockParam, + ServerToolUseBlockParam, + WebSearchToolResultBlockParam, ToolResultBlockParam, DocumentBlockParam, ThinkingBlockParam, diff --git a/src/anthropic/types/document_block_param.py b/src/anthropic/types/document_block_param.py index e3285266e..a2e776c51 100644 --- a/src/anthropic/types/document_block_param.py +++ b/src/anthropic/types/document_block_param.py @@ -23,6 +23,7 @@ class DocumentBlockParam(TypedDict, total=False): type: Required[Literal["document"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" citations: CitationsConfigParam diff --git a/src/anthropic/types/image_block_param.py b/src/anthropic/types/image_block_param.py index 914ed6bb7..24691f857 100644 --- a/src/anthropic/types/image_block_param.py +++ b/src/anthropic/types/image_block_param.py @@ -20,3 +20,4 @@ class ImageBlockParam(TypedDict, total=False): type: Required[Literal["image"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/message_count_tokens_params.py b/src/anthropic/types/message_count_tokens_params.py index ea88dd5dc..bf34adaa4 100644 --- a/src/anthropic/types/message_count_tokens_params.py +++ b/src/anthropic/types/message_count_tokens_params.py @@ -103,6 +103,8 @@ class MessageCountTokensParams(TypedDict, total=False): [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + + There is a limit of 100000 messages in a single request. """ model: Required[ModelParam] diff --git a/src/anthropic/types/message_count_tokens_tool_param.py b/src/anthropic/types/message_count_tokens_tool_param.py index e28c0ccf6..4c3a3df92 100644 --- a/src/anthropic/types/message_count_tokens_tool_param.py +++ b/src/anthropic/types/message_count_tokens_tool_param.py @@ -7,8 +7,11 @@ from .tool_param import ToolParam from .tool_bash_20250124_param import ToolBash20250124Param +from .web_search_tool_20250305_param import WebSearchTool20250305Param from .tool_text_editor_20250124_param import ToolTextEditor20250124Param __all__ = ["MessageCountTokensToolParam"] -MessageCountTokensToolParam: TypeAlias = Union[ToolParam, ToolBash20250124Param, ToolTextEditor20250124Param] +MessageCountTokensToolParam: TypeAlias = Union[ + ToolParam, ToolBash20250124Param, ToolTextEditor20250124Param, WebSearchTool20250305Param +] diff --git a/src/anthropic/types/message_create_params.py b/src/anthropic/types/message_create_params.py index c079bafd8..cf6771847 100644 --- a/src/anthropic/types/message_create_params.py +++ b/src/anthropic/types/message_create_params.py @@ -126,6 +126,8 @@ class MessageCreateParamsBase(TypedDict, total=False): [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. + + There is a limit of 100000 messages in a single request. """ model: Required[ModelParam] diff --git a/src/anthropic/types/message_delta_usage.py b/src/anthropic/types/message_delta_usage.py index d6ca79e64..11bd49d7f 100644 --- a/src/anthropic/types/message_delta_usage.py +++ b/src/anthropic/types/message_delta_usage.py @@ -1,10 +1,25 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import Optional + from .._models import BaseModel +from .server_tool_usage import ServerToolUsage __all__ = ["MessageDeltaUsage"] class MessageDeltaUsage(BaseModel): + cache_creation_input_tokens: Optional[int] = None + """The cumulative number of input tokens used to create the cache entry.""" + + cache_read_input_tokens: Optional[int] = None + """The cumulative number of input tokens read from the cache.""" + + input_tokens: Optional[int] = None + """The cumulative number of input tokens which were used.""" + output_tokens: int """The cumulative number of output tokens which were used.""" + + server_tool_use: Optional[ServerToolUsage] = None + """The number of server tool requests.""" diff --git a/src/anthropic/types/message_param.py b/src/anthropic/types/message_param.py index 3c0543959..fc2449a08 100644 --- a/src/anthropic/types/message_param.py +++ b/src/anthropic/types/message_param.py @@ -12,7 +12,9 @@ from .thinking_block_param import ThinkingBlockParam from .tool_use_block_param import ToolUseBlockParam from .tool_result_block_param import ToolResultBlockParam +from .server_tool_use_block_param import ServerToolUseBlockParam from .redacted_thinking_block_param import RedactedThinkingBlockParam +from .web_search_tool_result_block_param import WebSearchToolResultBlockParam __all__ = ["MessageParam"] @@ -26,6 +28,8 @@ class MessageParam(TypedDict, total=False): TextBlockParam, ImageBlockParam, ToolUseBlockParam, + ServerToolUseBlockParam, + WebSearchToolResultBlockParam, ToolResultBlockParam, DocumentBlockParam, ThinkingBlockParam, diff --git a/src/anthropic/types/model_list_params.py b/src/anthropic/types/model_list_params.py index b16d22a30..9ef1a04c0 100644 --- a/src/anthropic/types/model_list_params.py +++ b/src/anthropic/types/model_list_params.py @@ -2,7 +2,11 @@ from __future__ import annotations -from typing_extensions import TypedDict +from typing import List +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo +from .anthropic_beta_param import AnthropicBetaParam __all__ = ["ModelListParams"] @@ -25,3 +29,6 @@ class ModelListParams(TypedDict, total=False): Defaults to `20`. Ranges from `1` to `1000`. """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/src/anthropic/types/raw_content_block_start_event.py b/src/anthropic/types/raw_content_block_start_event.py index bfbaa63df..845ae4bcb 100644 --- a/src/anthropic/types/raw_content_block_start_event.py +++ b/src/anthropic/types/raw_content_block_start_event.py @@ -8,12 +8,15 @@ from .text_block import TextBlock from .thinking_block import ThinkingBlock from .tool_use_block import ToolUseBlock +from .server_tool_use_block import ServerToolUseBlock from .redacted_thinking_block import RedactedThinkingBlock +from .web_search_tool_result_block import WebSearchToolResultBlock __all__ = ["RawContentBlockStartEvent", "ContentBlock"] ContentBlock: TypeAlias = Annotated[ - Union[TextBlock, ToolUseBlock, ThinkingBlock, RedactedThinkingBlock], PropertyInfo(discriminator="type") + Union[TextBlock, ToolUseBlock, ServerToolUseBlock, WebSearchToolResultBlock, ThinkingBlock, RedactedThinkingBlock], + PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/server_tool_usage.py b/src/anthropic/types/server_tool_usage.py new file mode 100644 index 000000000..664dae2dc --- /dev/null +++ b/src/anthropic/types/server_tool_usage.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["ServerToolUsage"] + + +class ServerToolUsage(BaseModel): + web_search_requests: int + """The number of web search tool requests.""" diff --git a/src/anthropic/types/server_tool_use_block.py b/src/anthropic/types/server_tool_use_block.py new file mode 100644 index 000000000..abf515d39 --- /dev/null +++ b/src/anthropic/types/server_tool_use_block.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ServerToolUseBlock"] + + +class ServerToolUseBlock(BaseModel): + id: str + + input: object + + name: Literal["web_search"] + + type: Literal["server_tool_use"] diff --git a/src/anthropic/types/server_tool_use_block_param.py b/src/anthropic/types/server_tool_use_block_param.py new file mode 100644 index 000000000..e0849292f --- /dev/null +++ b/src/anthropic/types/server_tool_use_block_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["ServerToolUseBlockParam"] + + +class ServerToolUseBlockParam(TypedDict, total=False): + id: Required[str] + + input: Required[object] + + name: Required[Literal["web_search"]] + + type: Required[Literal["server_tool_use"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/stop_reason.py b/src/anthropic/types/stop_reason.py index b071c4b52..3d371592f 100644 --- a/src/anthropic/types/stop_reason.py +++ b/src/anthropic/types/stop_reason.py @@ -4,4 +4,4 @@ __all__ = ["StopReason"] -StopReason: TypeAlias = Literal["end_turn", "max_tokens", "stop_sequence", "tool_use"] +StopReason: TypeAlias = Literal["end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", "refusal"] diff --git a/src/anthropic/types/text_block_param.py b/src/anthropic/types/text_block_param.py index 921517330..5a0f1215d 100644 --- a/src/anthropic/types/text_block_param.py +++ b/src/anthropic/types/text_block_param.py @@ -17,5 +17,6 @@ class TextBlockParam(TypedDict, total=False): type: Required[Literal["text"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" citations: Optional[Iterable[TextCitationParam]] diff --git a/src/anthropic/types/text_citation.py b/src/anthropic/types/text_citation.py index 159771ae8..fde4fb58f 100644 --- a/src/anthropic/types/text_citation.py +++ b/src/anthropic/types/text_citation.py @@ -7,9 +7,11 @@ from .citation_char_location import CitationCharLocation from .citation_page_location import CitationPageLocation from .citation_content_block_location import CitationContentBlockLocation +from .citations_web_search_result_location import CitationsWebSearchResultLocation __all__ = ["TextCitation"] TextCitation: TypeAlias = Annotated[ - Union[CitationCharLocation, CitationPageLocation, CitationContentBlockLocation], PropertyInfo(discriminator="type") + Union[CitationCharLocation, CitationPageLocation, CitationContentBlockLocation, CitationsWebSearchResultLocation], + PropertyInfo(discriminator="type"), ] diff --git a/src/anthropic/types/text_citation_param.py b/src/anthropic/types/text_citation_param.py index 8e9881410..47853ff5e 100644 --- a/src/anthropic/types/text_citation_param.py +++ b/src/anthropic/types/text_citation_param.py @@ -8,9 +8,13 @@ from .citation_char_location_param import CitationCharLocationParam from .citation_page_location_param import CitationPageLocationParam from .citation_content_block_location_param import CitationContentBlockLocationParam +from .citation_web_search_result_location_param import CitationWebSearchResultLocationParam __all__ = ["TextCitationParam"] TextCitationParam: TypeAlias = Union[ - CitationCharLocationParam, CitationPageLocationParam, CitationContentBlockLocationParam + CitationCharLocationParam, + CitationPageLocationParam, + CitationContentBlockLocationParam, + CitationWebSearchResultLocationParam, ] diff --git a/src/anthropic/types/tool_bash_20250124_param.py b/src/anthropic/types/tool_bash_20250124_param.py index 6c8ff0fc7..0a1d620ee 100644 --- a/src/anthropic/types/tool_bash_20250124_param.py +++ b/src/anthropic/types/tool_bash_20250124_param.py @@ -14,9 +14,10 @@ class ToolBash20250124Param(TypedDict, total=False): name: Required[Literal["bash"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["bash_20250124"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/tool_param.py b/src/anthropic/types/tool_param.py index a01a014e8..9ca8581f7 100644 --- a/src/anthropic/types/tool_param.py +++ b/src/anthropic/types/tool_param.py @@ -33,10 +33,11 @@ class ToolParam(TypedDict, total=False): name: Required[str] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" description: str """Description of what this tool does. @@ -46,3 +47,5 @@ class ToolParam(TypedDict, total=False): perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema. """ + + type: Optional[Literal["custom"]] diff --git a/src/anthropic/types/tool_result_block_param.py b/src/anthropic/types/tool_result_block_param.py index b6ca8aa91..4c057c86f 100644 --- a/src/anthropic/types/tool_result_block_param.py +++ b/src/anthropic/types/tool_result_block_param.py @@ -20,6 +20,7 @@ class ToolResultBlockParam(TypedDict, total=False): type: Required[Literal["tool_result"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" content: Union[str, Iterable[Content]] diff --git a/src/anthropic/types/tool_text_editor_20250124_param.py b/src/anthropic/types/tool_text_editor_20250124_param.py index 94f631023..8e9fb9e88 100644 --- a/src/anthropic/types/tool_text_editor_20250124_param.py +++ b/src/anthropic/types/tool_text_editor_20250124_param.py @@ -14,9 +14,10 @@ class ToolTextEditor20250124Param(TypedDict, total=False): name: Required[Literal["str_replace_editor"]] """Name of the tool. - This is how the tool will be called by the model and in tool_use blocks. + This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["text_editor_20250124"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/tool_union_param.py b/src/anthropic/types/tool_union_param.py index 6c02090e6..051e85323 100644 --- a/src/anthropic/types/tool_union_param.py +++ b/src/anthropic/types/tool_union_param.py @@ -7,8 +7,11 @@ from .tool_param import ToolParam from .tool_bash_20250124_param import ToolBash20250124Param +from .web_search_tool_20250305_param import WebSearchTool20250305Param from .tool_text_editor_20250124_param import ToolTextEditor20250124Param __all__ = ["ToolUnionParam"] -ToolUnionParam: TypeAlias = Union[ToolParam, ToolBash20250124Param, ToolTextEditor20250124Param] +ToolUnionParam: TypeAlias = Union[ + ToolParam, ToolBash20250124Param, ToolTextEditor20250124Param, WebSearchTool20250305Param +] diff --git a/src/anthropic/types/tool_use_block_param.py b/src/anthropic/types/tool_use_block_param.py index cc2850795..2ef1d5eb9 100644 --- a/src/anthropic/types/tool_use_block_param.py +++ b/src/anthropic/types/tool_use_block_param.py @@ -20,3 +20,4 @@ class ToolUseBlockParam(TypedDict, total=False): type: Required[Literal["tool_use"]] cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/usage.py b/src/anthropic/types/usage.py index b4f817bd8..4960131bb 100644 --- a/src/anthropic/types/usage.py +++ b/src/anthropic/types/usage.py @@ -3,6 +3,7 @@ from typing import Optional from .._models import BaseModel +from .server_tool_usage import ServerToolUsage __all__ = ["Usage"] @@ -19,3 +20,6 @@ class Usage(BaseModel): output_tokens: int """The number of output tokens which were used.""" + + server_tool_use: Optional[ServerToolUsage] = None + """The number of server tool requests.""" diff --git a/src/anthropic/types/web_search_result_block.py b/src/anthropic/types/web_search_result_block.py new file mode 100644 index 000000000..21d36abae --- /dev/null +++ b/src/anthropic/types/web_search_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["WebSearchResultBlock"] + + +class WebSearchResultBlock(BaseModel): + encrypted_content: str + + page_age: Optional[str] = None + + title: str + + type: Literal["web_search_result"] + + url: str diff --git a/src/anthropic/types/web_search_result_block_param.py b/src/anthropic/types/web_search_result_block_param.py new file mode 100644 index 000000000..1950c710d --- /dev/null +++ b/src/anthropic/types/web_search_result_block_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WebSearchResultBlockParam"] + + +class WebSearchResultBlockParam(TypedDict, total=False): + encrypted_content: Required[str] + + title: Required[str] + + type: Required[Literal["web_search_result"]] + + url: Required[str] + + page_age: Optional[str] diff --git a/src/anthropic/types/web_search_tool_20250305_param.py b/src/anthropic/types/web_search_tool_20250305_param.py new file mode 100644 index 000000000..534bd69d9 --- /dev/null +++ b/src/anthropic/types/web_search_tool_20250305_param.py @@ -0,0 +1,64 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["WebSearchTool20250305Param", "UserLocation"] + + +class UserLocation(TypedDict, total=False): + type: Required[Literal["approximate"]] + + city: Optional[str] + """The city of the user.""" + + country: Optional[str] + """ + The two letter + [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the + user. + """ + + region: Optional[str] + """The region of the user.""" + + timezone: Optional[str] + """The [IANA timezone](https://nodatime.org/TimeZones) of the user.""" + + +class WebSearchTool20250305Param(TypedDict, total=False): + name: Required[Literal["web_search"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_search_20250305"]] + + allowed_domains: Optional[List[str]] + """If provided, only these domains will be included in results. + + Cannot be used alongside `blocked_domains`. + """ + + blocked_domains: Optional[List[str]] + """If provided, these domains will never appear in results. + + Cannot be used alongside `allowed_domains`. + """ + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + user_location: Optional[UserLocation] + """Parameters for the user's location. + + Used to provide more relevant search results. + """ diff --git a/src/anthropic/types/web_search_tool_request_error_param.py b/src/anthropic/types/web_search_tool_request_error_param.py new file mode 100644 index 000000000..ce814bef4 --- /dev/null +++ b/src/anthropic/types/web_search_tool_request_error_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WebSearchToolRequestErrorParam"] + + +class WebSearchToolRequestErrorParam(TypedDict, total=False): + error_code: Required[ + Literal["invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long"] + ] + + type: Required[Literal["web_search_tool_result_error"]] diff --git a/src/anthropic/types/web_search_tool_result_block.py b/src/anthropic/types/web_search_tool_result_block.py new file mode 100644 index 000000000..32cfc2b08 --- /dev/null +++ b/src/anthropic/types/web_search_tool_result_block.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel +from .web_search_tool_result_block_content import WebSearchToolResultBlockContent + +__all__ = ["WebSearchToolResultBlock"] + + +class WebSearchToolResultBlock(BaseModel): + content: WebSearchToolResultBlockContent + + tool_use_id: str + + type: Literal["web_search_tool_result"] diff --git a/src/anthropic/types/web_search_tool_result_block_content.py b/src/anthropic/types/web_search_tool_result_block_content.py new file mode 100644 index 000000000..c617e2ee0 --- /dev/null +++ b/src/anthropic/types/web_search_tool_result_block_content.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import TypeAlias + +from .web_search_result_block import WebSearchResultBlock +from .web_search_tool_result_error import WebSearchToolResultError + +__all__ = ["WebSearchToolResultBlockContent"] + +WebSearchToolResultBlockContent: TypeAlias = Union[WebSearchToolResultError, List[WebSearchResultBlock]] diff --git a/src/anthropic/types/web_search_tool_result_block_param.py b/src/anthropic/types/web_search_tool_result_block_param.py new file mode 100644 index 000000000..f75fa988e --- /dev/null +++ b/src/anthropic/types/web_search_tool_result_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .cache_control_ephemeral_param import CacheControlEphemeralParam +from .web_search_tool_result_block_param_content_param import WebSearchToolResultBlockParamContentParam + +__all__ = ["WebSearchToolResultBlockParam"] + + +class WebSearchToolResultBlockParam(TypedDict, total=False): + content: Required[WebSearchToolResultBlockParamContentParam] + + tool_use_id: Required[str] + + type: Required[Literal["web_search_tool_result"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/src/anthropic/types/web_search_tool_result_block_param_content_param.py b/src/anthropic/types/web_search_tool_result_block_param_content_param.py new file mode 100644 index 000000000..0d9c63f63 --- /dev/null +++ b/src/anthropic/types/web_search_tool_result_block_param_content_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypeAlias + +from .web_search_result_block_param import WebSearchResultBlockParam +from .web_search_tool_request_error_param import WebSearchToolRequestErrorParam + +__all__ = ["WebSearchToolResultBlockParamContentParam"] + +WebSearchToolResultBlockParamContentParam: TypeAlias = Union[ + Iterable[WebSearchResultBlockParam], WebSearchToolRequestErrorParam +] diff --git a/src/anthropic/types/web_search_tool_result_error.py b/src/anthropic/types/web_search_tool_result_error.py new file mode 100644 index 000000000..0a79b65a1 --- /dev/null +++ b/src/anthropic/types/web_search_tool_result_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["WebSearchToolResultError"] + + +class WebSearchToolResultError(BaseModel): + error_code: Literal["invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long"] + + type: Literal["web_search_tool_result_error"] diff --git a/tests/api_resources/beta/test_models.py b/tests/api_resources/beta/test_models.py index 17ffd939a..ee0fb5459 100644 --- a/tests/api_resources/beta/test_models.py +++ b/tests/api_resources/beta/test_models.py @@ -21,14 +21,22 @@ class TestModels: @parametrize def test_method_retrieve(self, client: Anthropic) -> None: model = client.beta.models.retrieve( - "model_id", + model_id="model_id", + ) + assert_matches_type(BetaModelInfo, model, path=["response"]) + + @parametrize + def test_method_retrieve_with_all_params(self, client: Anthropic) -> None: + model = client.beta.models.retrieve( + model_id="model_id", + betas=["string"], ) assert_matches_type(BetaModelInfo, model, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: Anthropic) -> None: response = client.beta.models.with_raw_response.retrieve( - "model_id", + model_id="model_id", ) assert response.is_closed is True @@ -39,7 +47,7 @@ def test_raw_response_retrieve(self, client: Anthropic) -> None: @parametrize def test_streaming_response_retrieve(self, client: Anthropic) -> None: with client.beta.models.with_streaming_response.retrieve( - "model_id", + model_id="model_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -53,7 +61,7 @@ def test_streaming_response_retrieve(self, client: Anthropic) -> None: def test_path_params_retrieve(self, client: Anthropic) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model_id` but received ''"): client.beta.models.with_raw_response.retrieve( - "", + model_id="", ) @parametrize @@ -67,6 +75,7 @@ def test_method_list_with_all_params(self, client: Anthropic) -> None: after_id="after_id", before_id="before_id", limit=1, + betas=["string"], ) assert_matches_type(SyncPage[BetaModelInfo], model, path=["response"]) @@ -97,14 +106,22 @@ class TestAsyncModels: @parametrize async def test_method_retrieve(self, async_client: AsyncAnthropic) -> None: model = await async_client.beta.models.retrieve( - "model_id", + model_id="model_id", + ) + assert_matches_type(BetaModelInfo, model, path=["response"]) + + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncAnthropic) -> None: + model = await async_client.beta.models.retrieve( + model_id="model_id", + betas=["string"], ) assert_matches_type(BetaModelInfo, model, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncAnthropic) -> None: response = await async_client.beta.models.with_raw_response.retrieve( - "model_id", + model_id="model_id", ) assert response.is_closed is True @@ -115,7 +132,7 @@ async def test_raw_response_retrieve(self, async_client: AsyncAnthropic) -> None @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncAnthropic) -> None: async with async_client.beta.models.with_streaming_response.retrieve( - "model_id", + model_id="model_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -129,7 +146,7 @@ async def test_streaming_response_retrieve(self, async_client: AsyncAnthropic) - async def test_path_params_retrieve(self, async_client: AsyncAnthropic) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model_id` but received ''"): await async_client.beta.models.with_raw_response.retrieve( - "", + model_id="", ) @parametrize @@ -143,6 +160,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncAnthropic) - after_id="after_id", before_id="before_id", limit=1, + betas=["string"], ) assert_matches_type(AsyncPage[BetaModelInfo], model, path=["response"]) diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index dd5f81d6b..c180c2ae6 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -38,6 +38,7 @@ def test_method_create_with_all_params_overload_1(self, client: Anthropic) -> No temperature=1, top_k=5, top_p=0.7, + betas=["string"], ) assert_matches_type(Completion, completion, path=["response"]) @@ -91,6 +92,7 @@ def test_method_create_with_all_params_overload_2(self, client: Anthropic) -> No temperature=1, top_k=5, top_p=0.7, + betas=["string"], ) completion_stream.response.close() @@ -148,6 +150,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn temperature=1, top_k=5, top_p=0.7, + betas=["string"], ) assert_matches_type(Completion, completion, path=["response"]) @@ -201,6 +204,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn temperature=1, top_k=5, top_p=0.7, + betas=["string"], ) await completion_stream.response.aclose() diff --git a/tests/api_resources/test_messages.py b/tests/api_resources/test_messages.py index b68daf9e9..eea9c33ea 100644 --- a/tests/api_resources/test_messages.py +++ b/tests/api_resources/test_messages.py @@ -93,6 +93,7 @@ def test_method_create_with_all_params_overload_1(self, client: Anthropic) -> No "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], top_k=5, @@ -211,6 +212,7 @@ def test_method_create_with_all_params_overload_2(self, client: Anthropic) -> No "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], top_k=5, @@ -333,6 +335,7 @@ def test_method_count_tokens_with_all_params(self, client: Anthropic) -> None: "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], ) @@ -450,6 +453,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], top_k=5, @@ -568,6 +572,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], top_k=5, @@ -690,6 +695,7 @@ async def test_method_count_tokens_with_all_params(self, async_client: AsyncAnth "name": "name", "cache_control": {"type": "ephemeral"}, "description": "Get the current weather in a given location", + "type": "custom", } ], ) diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 34b4961a3..f19322456 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -21,14 +21,22 @@ class TestModels: @parametrize def test_method_retrieve(self, client: Anthropic) -> None: model = client.models.retrieve( - "model_id", + model_id="model_id", + ) + assert_matches_type(ModelInfo, model, path=["response"]) + + @parametrize + def test_method_retrieve_with_all_params(self, client: Anthropic) -> None: + model = client.models.retrieve( + model_id="model_id", + betas=["string"], ) assert_matches_type(ModelInfo, model, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: Anthropic) -> None: response = client.models.with_raw_response.retrieve( - "model_id", + model_id="model_id", ) assert response.is_closed is True @@ -39,7 +47,7 @@ def test_raw_response_retrieve(self, client: Anthropic) -> None: @parametrize def test_streaming_response_retrieve(self, client: Anthropic) -> None: with client.models.with_streaming_response.retrieve( - "model_id", + model_id="model_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -53,7 +61,7 @@ def test_streaming_response_retrieve(self, client: Anthropic) -> None: def test_path_params_retrieve(self, client: Anthropic) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model_id` but received ''"): client.models.with_raw_response.retrieve( - "", + model_id="", ) @parametrize @@ -67,6 +75,7 @@ def test_method_list_with_all_params(self, client: Anthropic) -> None: after_id="after_id", before_id="before_id", limit=1, + betas=["string"], ) assert_matches_type(SyncPage[ModelInfo], model, path=["response"]) @@ -97,14 +106,22 @@ class TestAsyncModels: @parametrize async def test_method_retrieve(self, async_client: AsyncAnthropic) -> None: model = await async_client.models.retrieve( - "model_id", + model_id="model_id", + ) + assert_matches_type(ModelInfo, model, path=["response"]) + + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncAnthropic) -> None: + model = await async_client.models.retrieve( + model_id="model_id", + betas=["string"], ) assert_matches_type(ModelInfo, model, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncAnthropic) -> None: response = await async_client.models.with_raw_response.retrieve( - "model_id", + model_id="model_id", ) assert response.is_closed is True @@ -115,7 +132,7 @@ async def test_raw_response_retrieve(self, async_client: AsyncAnthropic) -> None @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncAnthropic) -> None: async with async_client.models.with_streaming_response.retrieve( - "model_id", + model_id="model_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -129,7 +146,7 @@ async def test_streaming_response_retrieve(self, async_client: AsyncAnthropic) - async def test_path_params_retrieve(self, async_client: AsyncAnthropic) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model_id` but received ''"): await async_client.models.with_raw_response.retrieve( - "", + model_id="", ) @parametrize @@ -143,6 +160,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncAnthropic) - after_id="after_id", before_id="before_id", limit=1, + betas=["string"], ) assert_matches_type(AsyncPage[ModelInfo], model, path=["response"]) From 4c7f97f3ea31ab90f3dfe8aa1c7cacaabfa6b53b Mon Sep 17 00:00:00 2001 From: David Meadows Date: Wed, 7 May 2025 11:22:12 -0400 Subject: [PATCH 09/10] chore(internal): add back missing custom modifications for Web Search --- examples/web_search.py | 35 +++++++++++ examples/web_search_stream.py | 61 +++++++++++++++++++ src/anthropic/lib/streaming/_beta_messages.py | 10 +++ src/anthropic/lib/streaming/_messages.py | 10 +++ 4 files changed, 116 insertions(+) create mode 100644 examples/web_search.py create mode 100644 examples/web_search_stream.py diff --git a/examples/web_search.py b/examples/web_search.py new file mode 100644 index 000000000..9e3d64eef --- /dev/null +++ b/examples/web_search.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from anthropic import Anthropic + +client = Anthropic() + +# Create a message with web search enabled +message = client.messages.create( + model="claude-3-5-sonnet-latest", + max_tokens=1024, + messages=[{"role": "user", "content": "What's the weather in New York?"}], + tools=[ + { + "name": "web_search", + "type": "web_search_20250305", + } + ], +) + +# Print the full response +print("\nFull response:") +print(message.model_dump_json(indent=2)) + +# Extract and print the content +print("\nResponse content:") +for content_block in message.content: + if content_block.type == "text": + print(content_block.text) + +# Print usage information +print("\nUsage statistics:") +print(f"Input tokens: {message.usage.input_tokens}") +print(f"Output tokens: {message.usage.output_tokens}") +if message.usage.server_tool_use: + print(f"Web search requests: {message.usage.server_tool_use.web_search_requests}") diff --git a/examples/web_search_stream.py b/examples/web_search_stream.py new file mode 100644 index 000000000..078355636 --- /dev/null +++ b/examples/web_search_stream.py @@ -0,0 +1,61 @@ +import asyncio + +from anthropic import AsyncAnthropic + + +async def main() -> None: + client = AsyncAnthropic() + + print("Claude with Web Search (Streaming)") + print("==================================") + + # Create an async stream with web search enabled + async with client.beta.messages.stream( + model="claude-3-5-sonnet-latest", + max_tokens=1024, + messages=[{"role": "user", "content": "What's the weather in New York?"}], + tools=[ + { + "name": "web_search", + "type": "web_search_20250305", + } + ], + ) as stream: + # Process streaming events + async for chunk in stream: + # Print text deltas as they arrive + if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": + print(chunk.delta.text, end="", flush=True) + + # Track when web search is being used + elif chunk.type == "content_block_start" and chunk.content_block.type == "web_search_tool_result": + print("\n[Web search started...]", end="", flush=True) + + elif chunk.type == "content_block_stop" and chunk.content_block.type == "web_search_tool_result": + print("[Web search completed]", end="\n\n", flush=True) + + # Get the final complete message + message = await stream.get_final_message() + + print("\n\nFinal usage statistics:") + print(f"Input tokens: {message.usage.input_tokens}") + print(f"Output tokens: {message.usage.output_tokens}") + + if message.usage.server_tool_use: + print(f"Web search requests: {message.usage.server_tool_use.web_search_requests}") + else: + print("No web search requests recorded in usage") + + # Rather than parsing the web search results structure (which varies), + # we'll just show the complete message structure for debugging + print("\nMessage Content Types:") + for i, block in enumerate(message.content): + print(f"Content Block {i + 1}: Type = {block.type}") + + # Show the entire message structure as JSON for debugging + print("\nComplete message structure (JSON):") + print(message.model_dump_json(indent=2)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/src/anthropic/lib/streaming/_beta_messages.py b/src/anthropic/lib/streaming/_beta_messages.py index d979f83c5..37c5087ed 100644 --- a/src/anthropic/lib/streaming/_beta_messages.py +++ b/src/anthropic/lib/streaming/_beta_messages.py @@ -459,4 +459,14 @@ def accumulate_event( current_snapshot.stop_sequence = event.delta.stop_sequence current_snapshot.usage.output_tokens = event.usage.output_tokens + # Update other usage fields if they exist in the event + if event.usage.input_tokens is not None: + current_snapshot.usage.input_tokens = event.usage.input_tokens + if event.usage.cache_creation_input_tokens is not None: + current_snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens + if event.usage.cache_read_input_tokens is not None: + current_snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens + if event.usage.server_tool_use is not None: + current_snapshot.usage.server_tool_use = event.usage.server_tool_use + return current_snapshot diff --git a/src/anthropic/lib/streaming/_messages.py b/src/anthropic/lib/streaming/_messages.py index 09ed24f9d..16a2e762e 100644 --- a/src/anthropic/lib/streaming/_messages.py +++ b/src/anthropic/lib/streaming/_messages.py @@ -459,4 +459,14 @@ def accumulate_event( current_snapshot.stop_sequence = event.delta.stop_sequence current_snapshot.usage.output_tokens = event.usage.output_tokens + # Update other usage fields if they exist in the event + if event.usage.input_tokens is not None: + current_snapshot.usage.input_tokens = event.usage.input_tokens + if event.usage.cache_creation_input_tokens is not None: + current_snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens + if event.usage.cache_read_input_tokens is not None: + current_snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens + if event.usage.server_tool_use is not None: + current_snapshot.usage.server_tool_use = event.usage.server_tool_use + return current_snapshot From e42451ab3f14443c0ed8076b17032a6d8986b6bf Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 7 May 2025 15:22:48 +0000 Subject: [PATCH 10/10] release: 0.51.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ pyproject.toml | 2 +- src/anthropic/_version.py | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 26b1ce24e..2b2b4fa9e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.50.0" + ".": "0.51.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 287e4a47b..3054338d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 0.51.0 (2025-05-07) + +Full Changelog: [v0.50.0...v0.51.0](https://github.com/anthropics/anthropic-sdk-python/compare/v0.50.0...v0.51.0) + +### Features + +* **api:** adds web search capabilities to the Claude API ([bec0cf9](https://github.com/anthropics/anthropic-sdk-python/commit/bec0cf93c2d7cb47c921236a14c8569e0e22793e)) + + +### Bug Fixes + +* **pydantic v1:** more robust ModelField.annotation check ([c50f406](https://github.com/anthropics/anthropic-sdk-python/commit/c50f406767d8e7737a2754d6e1488d8a19216ac0)) +* **sockets:** handle non-portable socket flags ([#935](https://github.com/anthropics/anthropic-sdk-python/issues/935)) ([205c8dd](https://github.com/anthropics/anthropic-sdk-python/commit/205c8dda371caa3b393d3cfb4d323714b1fab336)) + + +### Chores + +* broadly detect json family of content-type headers ([66bbb3a](https://github.com/anthropics/anthropic-sdk-python/commit/66bbb3a6689a4e2dd4915a7a2940dec53e2b8eb9)) +* **ci:** only use depot for staging repos ([c867a11](https://github.com/anthropics/anthropic-sdk-python/commit/c867a11af37416c0d513aa177f77e1bcd0d70949)) +* **ci:** run on more branches and use depot runners ([95f5f17](https://github.com/anthropics/anthropic-sdk-python/commit/95f5f17be0ab05ed4e258ccc488d8cf55ffb8f29)) +* **internal:** add back missing custom modifications for Web Search ([f43ba69](https://github.com/anthropics/anthropic-sdk-python/commit/f43ba69d5337e5d99f7ca9bd2e773cc57bae5d1c)) +* **internal:** minor formatting changes ([8afef08](https://github.com/anthropics/anthropic-sdk-python/commit/8afef086af194df1e4b0d6d25b7fbe4d74bd6850)) +* use lazy imports for resources ([704be81](https://github.com/anthropics/anthropic-sdk-python/commit/704be817f436d92d96915cf02608b6827e06945f)) + ## 0.50.0 (2025-04-22) Full Changelog: [v0.49.0...v0.50.0](https://github.com/anthropics/anthropic-sdk-python/compare/v0.49.0...v0.50.0) diff --git a/pyproject.toml b/pyproject.toml index 97eff6218..63ae072dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "anthropic" -version = "0.50.0" +version = "0.51.0" description = "The official Python library for the anthropic API" dynamic = ["readme"] license = "MIT" diff --git a/src/anthropic/_version.py b/src/anthropic/_version.py index 939ae1dc8..139e0801c 100644 --- a/src/anthropic/_version.py +++ b/src/anthropic/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "anthropic" -__version__ = "0.50.0" # x-release-please-version +__version__ = "0.51.0" # x-release-please-version